OSDN Git Service

2010-10-21 Robert Dewar <dewar@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          --  This is a reasonable place to propagate predicates
1363
1364          if Has_Predicates (Iface) then
1365             Set_Has_Predicates (Typ);
1366          end if;
1367
1368          Def :=
1369            Make_Component_Definition (Loc,
1370              Aliased_Present    => True,
1371              Subtype_Indication =>
1372                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1373
1374          Tag := Make_Temporary (Loc, 'V');
1375
1376          Decl :=
1377            Make_Component_Declaration (Loc,
1378              Defining_Identifier  => Tag,
1379              Component_Definition => Def);
1380
1381          Analyze_Component_Declaration (Decl);
1382
1383          Set_Analyzed (Decl);
1384          Set_Ekind               (Tag, E_Component);
1385          Set_Is_Tag              (Tag);
1386          Set_Is_Aliased          (Tag);
1387          Set_Related_Type        (Tag, Iface);
1388          Init_Component_Location (Tag);
1389
1390          pragma Assert (Is_Frozen (Iface));
1391
1392          Set_DT_Entry_Count    (Tag,
1393            DT_Entry_Count (First_Entity (Iface)));
1394
1395          if No (Last_Tag) then
1396             Prepend (Decl, L);
1397          else
1398             Insert_After (Last_Tag, Decl);
1399          end if;
1400
1401          Last_Tag := Decl;
1402
1403          --  If the ancestor has discriminants we need to give special support
1404          --  to store the offset_to_top value of the secondary dispatch tables.
1405          --  For this purpose we add a supplementary component just after the
1406          --  field that contains the tag associated with each secondary DT.
1407
1408          if Typ /= Etype (Typ)
1409            and then Has_Discriminants (Etype (Typ))
1410          then
1411             Def :=
1412               Make_Component_Definition (Loc,
1413                 Subtype_Indication =>
1414                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1415
1416             Offset := Make_Temporary (Loc, 'V');
1417
1418             Decl :=
1419               Make_Component_Declaration (Loc,
1420                 Defining_Identifier  => Offset,
1421                 Component_Definition => Def);
1422
1423             Analyze_Component_Declaration (Decl);
1424
1425             Set_Analyzed (Decl);
1426             Set_Ekind               (Offset, E_Component);
1427             Set_Is_Aliased          (Offset);
1428             Set_Related_Type        (Offset, Iface);
1429             Init_Component_Location (Offset);
1430             Insert_After (Last_Tag, Decl);
1431             Last_Tag := Decl;
1432          end if;
1433       end Add_Tag;
1434
1435       --  Local variables
1436
1437       Elmt : Elmt_Id;
1438       Ext  : Node_Id;
1439       Comp : Node_Id;
1440
1441    --  Start of processing for Add_Interface_Tag_Components
1442
1443    begin
1444       if not RTE_Available (RE_Interface_Tag) then
1445          Error_Msg
1446            ("(Ada 2005) interface types not supported by this run-time!",
1447             Sloc (N));
1448          return;
1449       end if;
1450
1451       if Ekind (Typ) /= E_Record_Type
1452         or else (Is_Concurrent_Record_Type (Typ)
1453                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1454         or else (not Is_Concurrent_Record_Type (Typ)
1455                   and then No (Interfaces (Typ))
1456                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1457       then
1458          return;
1459       end if;
1460
1461       --  Find the current last tag
1462
1463       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1464          Ext := Record_Extension_Part (Type_Definition (N));
1465       else
1466          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1467          Ext := Type_Definition (N);
1468       end if;
1469
1470       Last_Tag := Empty;
1471
1472       if not (Present (Component_List (Ext))) then
1473          Set_Null_Present (Ext, False);
1474          L := New_List;
1475          Set_Component_List (Ext,
1476            Make_Component_List (Loc,
1477              Component_Items => L,
1478              Null_Present => False));
1479       else
1480          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1481             L := Component_Items
1482                    (Component_List
1483                      (Record_Extension_Part
1484                        (Type_Definition (N))));
1485          else
1486             L := Component_Items
1487                    (Component_List
1488                      (Type_Definition (N)));
1489          end if;
1490
1491          --  Find the last tag component
1492
1493          Comp := First (L);
1494          while Present (Comp) loop
1495             if Nkind (Comp) = N_Component_Declaration
1496               and then Is_Tag (Defining_Identifier (Comp))
1497             then
1498                Last_Tag := Comp;
1499             end if;
1500
1501             Next (Comp);
1502          end loop;
1503       end if;
1504
1505       --  At this point L references the list of components and Last_Tag
1506       --  references the current last tag (if any). Now we add the tag
1507       --  corresponding with all the interfaces that are not implemented
1508       --  by the parent.
1509
1510       if Present (Interfaces (Typ)) then
1511          Elmt := First_Elmt (Interfaces (Typ));
1512          while Present (Elmt) loop
1513             Add_Tag (Node (Elmt));
1514             Next_Elmt (Elmt);
1515          end loop;
1516       end if;
1517    end Add_Interface_Tag_Components;
1518
1519    -------------------------------------
1520    -- Add_Internal_Interface_Entities --
1521    -------------------------------------
1522
1523    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1524       Elmt          : Elmt_Id;
1525       Iface         : Entity_Id;
1526       Iface_Elmt    : Elmt_Id;
1527       Iface_Prim    : Entity_Id;
1528       Ifaces_List   : Elist_Id;
1529       New_Subp      : Entity_Id := Empty;
1530       Prim          : Entity_Id;
1531       Restore_Scope : Boolean := False;
1532
1533    begin
1534       pragma Assert (Ada_Version >= Ada_2005
1535         and then Is_Record_Type (Tagged_Type)
1536         and then Is_Tagged_Type (Tagged_Type)
1537         and then Has_Interfaces (Tagged_Type)
1538         and then not Is_Interface (Tagged_Type));
1539
1540       --  Ensure that the internal entities are added to the scope of the type
1541
1542       if Scope (Tagged_Type) /= Current_Scope then
1543          Push_Scope (Scope (Tagged_Type));
1544          Restore_Scope := True;
1545       end if;
1546
1547       Collect_Interfaces (Tagged_Type, Ifaces_List);
1548
1549       Iface_Elmt := First_Elmt (Ifaces_List);
1550       while Present (Iface_Elmt) loop
1551          Iface := Node (Iface_Elmt);
1552
1553          --  Originally we excluded here from this processing interfaces that
1554          --  are parents of Tagged_Type because their primitives are located
1555          --  in the primary dispatch table (and hence no auxiliary internal
1556          --  entities are required to handle secondary dispatch tables in such
1557          --  case). However, these auxiliary entities are also required to
1558          --  handle derivations of interfaces in formals of generics (see
1559          --  Derive_Subprograms).
1560
1561          Elmt := First_Elmt (Primitive_Operations (Iface));
1562          while Present (Elmt) loop
1563             Iface_Prim := Node (Elmt);
1564
1565             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1566                Prim :=
1567                  Find_Primitive_Covering_Interface
1568                    (Tagged_Type => Tagged_Type,
1569                     Iface_Prim  => Iface_Prim);
1570
1571                pragma Assert (Present (Prim));
1572
1573                Derive_Subprogram
1574                  (New_Subp     => New_Subp,
1575                   Parent_Subp  => Iface_Prim,
1576                   Derived_Type => Tagged_Type,
1577                   Parent_Type  => Iface);
1578
1579                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1580                --  associated with interface types. These entities are
1581                --  only registered in the list of primitives of its
1582                --  corresponding tagged type because they are only used
1583                --  to fill the contents of the secondary dispatch tables.
1584                --  Therefore they are removed from the homonym chains.
1585
1586                Set_Is_Hidden (New_Subp);
1587                Set_Is_Internal (New_Subp);
1588                Set_Alias (New_Subp, Prim);
1589                Set_Is_Abstract_Subprogram
1590                  (New_Subp, Is_Abstract_Subprogram (Prim));
1591                Set_Interface_Alias (New_Subp, Iface_Prim);
1592
1593                --  Internal entities associated with interface types are
1594                --  only registered in the list of primitives of the tagged
1595                --  type. They are only used to fill the contents of the
1596                --  secondary dispatch tables. Therefore they are not needed
1597                --  in the homonym chains.
1598
1599                Remove_Homonym (New_Subp);
1600
1601                --  Hidden entities associated with interfaces must have set
1602                --  the Has_Delay_Freeze attribute to ensure that, in case of
1603                --  locally defined tagged types (or compiling with static
1604                --  dispatch tables generation disabled) the corresponding
1605                --  entry of the secondary dispatch table is filled when
1606                --  such an entity is frozen.
1607
1608                Set_Has_Delayed_Freeze (New_Subp);
1609             end if;
1610
1611             Next_Elmt (Elmt);
1612          end loop;
1613
1614          Next_Elmt (Iface_Elmt);
1615       end loop;
1616
1617       if Restore_Scope then
1618          Pop_Scope;
1619       end if;
1620    end Add_Internal_Interface_Entities;
1621
1622    -----------------------------------
1623    -- Analyze_Component_Declaration --
1624    -----------------------------------
1625
1626    procedure Analyze_Component_Declaration (N : Node_Id) is
1627       Id : constant Entity_Id := Defining_Identifier (N);
1628       E  : constant Node_Id   := Expression (N);
1629       T  : Entity_Id;
1630       P  : Entity_Id;
1631
1632       function Contains_POC (Constr : Node_Id) return Boolean;
1633       --  Determines whether a constraint uses the discriminant of a record
1634       --  type thus becoming a per-object constraint (POC).
1635
1636       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1637       --  Typ is the type of the current component, check whether this type is
1638       --  a limited type. Used to validate declaration against that of
1639       --  enclosing record.
1640
1641       ------------------
1642       -- Contains_POC --
1643       ------------------
1644
1645       function Contains_POC (Constr : Node_Id) return Boolean is
1646       begin
1647          --  Prevent cascaded errors
1648
1649          if Error_Posted (Constr) then
1650             return False;
1651          end if;
1652
1653          case Nkind (Constr) is
1654             when N_Attribute_Reference =>
1655                return
1656                  Attribute_Name (Constr) = Name_Access
1657                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1658
1659             when N_Discriminant_Association =>
1660                return Denotes_Discriminant (Expression (Constr));
1661
1662             when N_Identifier =>
1663                return Denotes_Discriminant (Constr);
1664
1665             when N_Index_Or_Discriminant_Constraint =>
1666                declare
1667                   IDC : Node_Id;
1668
1669                begin
1670                   IDC := First (Constraints (Constr));
1671                   while Present (IDC) loop
1672
1673                      --  One per-object constraint is sufficient
1674
1675                      if Contains_POC (IDC) then
1676                         return True;
1677                      end if;
1678
1679                      Next (IDC);
1680                   end loop;
1681
1682                   return False;
1683                end;
1684
1685             when N_Range =>
1686                return Denotes_Discriminant (Low_Bound (Constr))
1687                         or else
1688                       Denotes_Discriminant (High_Bound (Constr));
1689
1690             when N_Range_Constraint =>
1691                return Denotes_Discriminant (Range_Expression (Constr));
1692
1693             when others =>
1694                return False;
1695
1696          end case;
1697       end Contains_POC;
1698
1699       ----------------------
1700       -- Is_Known_Limited --
1701       ----------------------
1702
1703       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1704          P : constant Entity_Id := Etype (Typ);
1705          R : constant Entity_Id := Root_Type (Typ);
1706
1707       begin
1708          if Is_Limited_Record (Typ) then
1709             return True;
1710
1711          --  If the root type is limited (and not a limited interface)
1712          --  so is the current type
1713
1714          elsif Is_Limited_Record (R)
1715            and then
1716              (not Is_Interface (R)
1717                or else not Is_Limited_Interface (R))
1718          then
1719             return True;
1720
1721          --  Else the type may have a limited interface progenitor, but a
1722          --  limited record parent.
1723
1724          elsif R /= P
1725            and then Is_Limited_Record (P)
1726          then
1727             return True;
1728
1729          else
1730             return False;
1731          end if;
1732       end Is_Known_Limited;
1733
1734    --  Start of processing for Analyze_Component_Declaration
1735
1736    begin
1737       Generate_Definition (Id);
1738       Enter_Name (Id);
1739
1740       if Present (Subtype_Indication (Component_Definition (N))) then
1741          T := Find_Type_Of_Object
1742                 (Subtype_Indication (Component_Definition (N)), N);
1743
1744       --  Ada 2005 (AI-230): Access Definition case
1745
1746       else
1747          pragma Assert (Present
1748                           (Access_Definition (Component_Definition (N))));
1749
1750          T := Access_Definition
1751                 (Related_Nod => N,
1752                  N => Access_Definition (Component_Definition (N)));
1753          Set_Is_Local_Anonymous_Access (T);
1754
1755          --  Ada 2005 (AI-254)
1756
1757          if Present (Access_To_Subprogram_Definition
1758                       (Access_Definition (Component_Definition (N))))
1759            and then Protected_Present (Access_To_Subprogram_Definition
1760                                         (Access_Definition
1761                                           (Component_Definition (N))))
1762          then
1763             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1764          end if;
1765       end if;
1766
1767       --  If the subtype is a constrained subtype of the enclosing record,
1768       --  (which must have a partial view) the back-end does not properly
1769       --  handle the recursion. Rewrite the component declaration with an
1770       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1771       --  the tree directly because side effects have already been removed from
1772       --  discriminant constraints.
1773
1774       if Ekind (T) = E_Access_Subtype
1775         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1776         and then Comes_From_Source (T)
1777         and then Nkind (Parent (T)) = N_Subtype_Declaration
1778         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1779       then
1780          Rewrite
1781            (Subtype_Indication (Component_Definition (N)),
1782              New_Copy_Tree (Subtype_Indication (Parent (T))));
1783          T := Find_Type_Of_Object
1784                  (Subtype_Indication (Component_Definition (N)), N);
1785       end if;
1786
1787       --  If the component declaration includes a default expression, then we
1788       --  check that the component is not of a limited type (RM 3.7(5)),
1789       --  and do the special preanalysis of the expression (see section on
1790       --  "Handling of Default and Per-Object Expressions" in the spec of
1791       --  package Sem).
1792
1793       if Present (E) then
1794          Preanalyze_Spec_Expression (E, T);
1795          Check_Initialization (T, E);
1796
1797          if Ada_Version >= Ada_2005
1798            and then Ekind (T) = E_Anonymous_Access_Type
1799            and then Etype (E) /= Any_Type
1800          then
1801             --  Check RM 3.9.2(9): "if the expected type for an expression is
1802             --  an anonymous access-to-specific tagged type, then the object
1803             --  designated by the expression shall not be dynamically tagged
1804             --  unless it is a controlling operand in a call on a dispatching
1805             --  operation"
1806
1807             if Is_Tagged_Type (Directly_Designated_Type (T))
1808               and then
1809                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1810               and then
1811                 Ekind (Directly_Designated_Type (Etype (E))) =
1812                   E_Class_Wide_Type
1813             then
1814                Error_Msg_N
1815                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1816             end if;
1817
1818             --  (Ada 2005: AI-230): Accessibility check for anonymous
1819             --  components
1820
1821             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1822                Error_Msg_N
1823                  ("expression has deeper access level than component " &
1824                   "(RM 3.10.2 (12.2))", E);
1825             end if;
1826
1827             --  The initialization expression is a reference to an access
1828             --  discriminant. The type of the discriminant is always deeper
1829             --  than any access type.
1830
1831             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1832               and then Is_Entity_Name (E)
1833               and then Ekind (Entity (E)) = E_In_Parameter
1834               and then Present (Discriminal_Link (Entity (E)))
1835             then
1836                Error_Msg_N
1837                  ("discriminant has deeper accessibility level than target",
1838                   E);
1839             end if;
1840          end if;
1841       end if;
1842
1843       --  The parent type may be a private view with unknown discriminants,
1844       --  and thus unconstrained. Regular components must be constrained.
1845
1846       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1847          if Is_Class_Wide_Type (T) then
1848             Error_Msg_N
1849                ("class-wide subtype with unknown discriminants" &
1850                  " in component declaration",
1851                  Subtype_Indication (Component_Definition (N)));
1852          else
1853             Error_Msg_N
1854               ("unconstrained subtype in component declaration",
1855                Subtype_Indication (Component_Definition (N)));
1856          end if;
1857
1858       --  Components cannot be abstract, except for the special case of
1859       --  the _Parent field (case of extending an abstract tagged type)
1860
1861       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1862          Error_Msg_N ("type of a component cannot be abstract", N);
1863       end if;
1864
1865       Set_Etype (Id, T);
1866       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1867
1868       --  The component declaration may have a per-object constraint, set
1869       --  the appropriate flag in the defining identifier of the subtype.
1870
1871       if Present (Subtype_Indication (Component_Definition (N))) then
1872          declare
1873             Sindic : constant Node_Id :=
1874                        Subtype_Indication (Component_Definition (N));
1875          begin
1876             if Nkind (Sindic) = N_Subtype_Indication
1877               and then Present (Constraint (Sindic))
1878               and then Contains_POC (Constraint (Sindic))
1879             then
1880                Set_Has_Per_Object_Constraint (Id);
1881             end if;
1882          end;
1883       end if;
1884
1885       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1886       --  out some static checks.
1887
1888       if Ada_Version >= Ada_2005
1889         and then Can_Never_Be_Null (T)
1890       then
1891          Null_Exclusion_Static_Checks (N);
1892       end if;
1893
1894       --  If this component is private (or depends on a private type), flag the
1895       --  record type to indicate that some operations are not available.
1896
1897       P := Private_Component (T);
1898
1899       if Present (P) then
1900
1901          --  Check for circular definitions
1902
1903          if P = Any_Type then
1904             Set_Etype (Id, Any_Type);
1905
1906          --  There is a gap in the visibility of operations only if the
1907          --  component type is not defined in the scope of the record type.
1908
1909          elsif Scope (P) = Scope (Current_Scope) then
1910             null;
1911
1912          elsif Is_Limited_Type (P) then
1913             Set_Is_Limited_Composite (Current_Scope);
1914
1915          else
1916             Set_Is_Private_Composite (Current_Scope);
1917          end if;
1918       end if;
1919
1920       if P /= Any_Type
1921         and then Is_Limited_Type (T)
1922         and then Chars (Id) /= Name_uParent
1923         and then Is_Tagged_Type (Current_Scope)
1924       then
1925          if Is_Derived_Type (Current_Scope)
1926            and then not Is_Known_Limited (Current_Scope)
1927          then
1928             Error_Msg_N
1929               ("extension of nonlimited type cannot have limited components",
1930                N);
1931
1932             if Is_Interface (Root_Type (Current_Scope)) then
1933                Error_Msg_N
1934                  ("\limitedness is not inherited from limited interface", N);
1935                Error_Msg_N ("\add LIMITED to type indication", N);
1936             end if;
1937
1938             Explain_Limited_Type (T, N);
1939             Set_Etype (Id, Any_Type);
1940             Set_Is_Limited_Composite (Current_Scope, False);
1941
1942          elsif not Is_Derived_Type (Current_Scope)
1943            and then not Is_Limited_Record (Current_Scope)
1944            and then not Is_Concurrent_Type (Current_Scope)
1945          then
1946             Error_Msg_N
1947               ("nonlimited tagged type cannot have limited components", N);
1948             Explain_Limited_Type (T, N);
1949             Set_Etype (Id, Any_Type);
1950             Set_Is_Limited_Composite (Current_Scope, False);
1951          end if;
1952       end if;
1953
1954       Set_Original_Record_Component (Id, Id);
1955       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
1956    end Analyze_Component_Declaration;
1957
1958    --------------------------
1959    -- Analyze_Declarations --
1960    --------------------------
1961
1962    procedure Analyze_Declarations (L : List_Id) is
1963       D           : Node_Id;
1964       Freeze_From : Entity_Id := Empty;
1965       Next_Node   : Node_Id;
1966
1967       procedure Adjust_D;
1968       --  Adjust D not to include implicit label declarations, since these
1969       --  have strange Sloc values that result in elaboration check problems.
1970       --  (They have the sloc of the label as found in the source, and that
1971       --  is ahead of the current declarative part).
1972
1973       --------------
1974       -- Adjust_D --
1975       --------------
1976
1977       procedure Adjust_D is
1978       begin
1979          while Present (Prev (D))
1980            and then Nkind (D) = N_Implicit_Label_Declaration
1981          loop
1982             Prev (D);
1983          end loop;
1984       end Adjust_D;
1985
1986    --  Start of processing for Analyze_Declarations
1987
1988    begin
1989       D := First (L);
1990       while Present (D) loop
1991
1992          --  Complete analysis of declaration
1993
1994          Analyze (D);
1995          Next_Node := Next (D);
1996
1997          if No (Freeze_From) then
1998             Freeze_From := First_Entity (Current_Scope);
1999          end if;
2000
2001          --  At the end of a declarative part, freeze remaining entities
2002          --  declared in it. The end of the visible declarations of package
2003          --  specification is not the end of a declarative part if private
2004          --  declarations are present. The end of a package declaration is a
2005          --  freezing point only if it a library package. A task definition or
2006          --  protected type definition is not a freeze point either. Finally,
2007          --  we do not freeze entities in generic scopes, because there is no
2008          --  code generated for them and freeze nodes will be generated for
2009          --  the instance.
2010
2011          --  The end of a package instantiation is not a freeze point, but
2012          --  for now we make it one, because the generic body is inserted
2013          --  (currently) immediately after. Generic instantiations will not
2014          --  be a freeze point once delayed freezing of bodies is implemented.
2015          --  (This is needed in any case for early instantiations ???).
2016
2017          if No (Next_Node) then
2018             if Nkind_In (Parent (L), N_Component_List,
2019                                      N_Task_Definition,
2020                                      N_Protected_Definition)
2021             then
2022                null;
2023
2024             elsif Nkind (Parent (L)) /= N_Package_Specification then
2025                if Nkind (Parent (L)) = N_Package_Body then
2026                   Freeze_From := First_Entity (Current_Scope);
2027                end if;
2028
2029                Adjust_D;
2030                Freeze_All (Freeze_From, D);
2031                Freeze_From := Last_Entity (Current_Scope);
2032
2033             elsif Scope (Current_Scope) /= Standard_Standard
2034               and then not Is_Child_Unit (Current_Scope)
2035               and then No (Generic_Parent (Parent (L)))
2036             then
2037                null;
2038
2039             elsif L /= Visible_Declarations (Parent (L))
2040                or else No (Private_Declarations (Parent (L)))
2041                or else Is_Empty_List (Private_Declarations (Parent (L)))
2042             then
2043                Adjust_D;
2044                Freeze_All (Freeze_From, D);
2045                Freeze_From := Last_Entity (Current_Scope);
2046             end if;
2047
2048          --  If next node is a body then freeze all types before the body.
2049          --  An exception occurs for some expander-generated bodies. If these
2050          --  are generated at places where in general language rules would not
2051          --  allow a freeze point, then we assume that the expander has
2052          --  explicitly checked that all required types are properly frozen,
2053          --  and we do not cause general freezing here. This special circuit
2054          --  is used when the encountered body is marked as having already
2055          --  been analyzed.
2056
2057          --  In all other cases (bodies that come from source, and expander
2058          --  generated bodies that have not been analyzed yet), freeze all
2059          --  types now. Note that in the latter case, the expander must take
2060          --  care to attach the bodies at a proper place in the tree so as to
2061          --  not cause unwanted freezing at that point.
2062
2063          elsif not Analyzed (Next_Node)
2064            and then (Nkind_In (Next_Node, N_Subprogram_Body,
2065                                           N_Entry_Body,
2066                                           N_Package_Body,
2067                                           N_Protected_Body,
2068                                           N_Task_Body)
2069                        or else
2070                      Nkind (Next_Node) in N_Body_Stub)
2071          then
2072             Adjust_D;
2073             Freeze_All (Freeze_From, D);
2074             Freeze_From := Last_Entity (Current_Scope);
2075          end if;
2076
2077          D := Next_Node;
2078       end loop;
2079
2080       --  One more thing to do, we need to scan the declarations to check
2081       --  for any precondition/postcondition pragmas (Pre/Post aspects have
2082       --  by this stage been converted into corresponding pragmas). It is
2083       --  at this point that we analyze the expressions in such pragmas,
2084       --  to implement the delayed visibility requirement.
2085
2086       declare
2087          Decl : Node_Id;
2088          Spec : Node_Id;
2089          Sent : Entity_Id;
2090          Prag : Node_Id;
2091
2092       begin
2093          Decl := First (L);
2094          while Present (Decl) loop
2095             if Nkind (Original_Node (Decl)) = N_Subprogram_Declaration then
2096                Spec := Specification (Original_Node (Decl));
2097                Sent := Defining_Unit_Name (Spec);
2098                Prag := Spec_PPC_List (Sent);
2099                while Present (Prag) loop
2100                   Analyze_PPC_In_Decl_Part (Prag, Sent);
2101                   Prag := Next_Pragma (Prag);
2102                end loop;
2103             end if;
2104
2105             Next (Decl);
2106          end loop;
2107       end;
2108    end Analyze_Declarations;
2109
2110    -----------------------------------
2111    -- Analyze_Full_Type_Declaration --
2112    -----------------------------------
2113
2114    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2115       Def    : constant Node_Id   := Type_Definition (N);
2116       Def_Id : constant Entity_Id := Defining_Identifier (N);
2117       T      : Entity_Id;
2118       Prev   : Entity_Id;
2119
2120       Is_Remote : constant Boolean :=
2121                     (Is_Remote_Types (Current_Scope)
2122                        or else Is_Remote_Call_Interface (Current_Scope))
2123                     and then not (In_Private_Part (Current_Scope)
2124                                     or else In_Package_Body (Current_Scope));
2125
2126       procedure Check_Ops_From_Incomplete_Type;
2127       --  If there is a tagged incomplete partial view of the type, transfer
2128       --  its operations to the full view, and indicate that the type of the
2129       --  controlling parameter (s) is this full view.
2130
2131       ------------------------------------
2132       -- Check_Ops_From_Incomplete_Type --
2133       ------------------------------------
2134
2135       procedure Check_Ops_From_Incomplete_Type is
2136          Elmt   : Elmt_Id;
2137          Formal : Entity_Id;
2138          Op     : Entity_Id;
2139
2140       begin
2141          if Prev /= T
2142            and then Ekind (Prev) = E_Incomplete_Type
2143            and then Is_Tagged_Type (Prev)
2144            and then Is_Tagged_Type (T)
2145          then
2146             Elmt := First_Elmt (Primitive_Operations (Prev));
2147             while Present (Elmt) loop
2148                Op := Node (Elmt);
2149                Prepend_Elmt (Op, Primitive_Operations (T));
2150
2151                Formal := First_Formal (Op);
2152                while Present (Formal) loop
2153                   if Etype (Formal) = Prev then
2154                      Set_Etype (Formal, T);
2155                   end if;
2156
2157                   Next_Formal (Formal);
2158                end loop;
2159
2160                if Etype (Op) = Prev then
2161                   Set_Etype (Op, T);
2162                end if;
2163
2164                Next_Elmt (Elmt);
2165             end loop;
2166          end if;
2167       end Check_Ops_From_Incomplete_Type;
2168
2169    --  Start of processing for Analyze_Full_Type_Declaration
2170
2171    begin
2172       Prev := Find_Type_Name (N);
2173
2174       --  The full view, if present, now points to the current type
2175
2176       --  Ada 2005 (AI-50217): If the type was previously decorated when
2177       --  imported through a LIMITED WITH clause, it appears as incomplete
2178       --  but has no full view.
2179
2180       if Ekind (Prev) = E_Incomplete_Type
2181         and then Present (Full_View (Prev))
2182       then
2183          T := Full_View (Prev);
2184       else
2185          T := Prev;
2186       end if;
2187
2188       Set_Is_Pure (T, Is_Pure (Current_Scope));
2189
2190       --  We set the flag Is_First_Subtype here. It is needed to set the
2191       --  corresponding flag for the Implicit class-wide-type created
2192       --  during tagged types processing.
2193
2194       Set_Is_First_Subtype (T, True);
2195
2196       --  Only composite types other than array types are allowed to have
2197       --  discriminants.
2198
2199       case Nkind (Def) is
2200
2201          --  For derived types, the rule will be checked once we've figured
2202          --  out the parent type.
2203
2204          when N_Derived_Type_Definition =>
2205             null;
2206
2207          --  For record types, discriminants are allowed
2208
2209          when N_Record_Definition =>
2210             null;
2211
2212          when others =>
2213             if Present (Discriminant_Specifications (N)) then
2214                Error_Msg_N
2215                  ("elementary or array type cannot have discriminants",
2216                   Defining_Identifier
2217                   (First (Discriminant_Specifications (N))));
2218             end if;
2219       end case;
2220
2221       --  Elaborate the type definition according to kind, and generate
2222       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2223       --  already done (this happens during the reanalysis that follows a call
2224       --  to the high level optimizer).
2225
2226       if not Analyzed (T) then
2227          Set_Analyzed (T);
2228
2229          case Nkind (Def) is
2230
2231             when N_Access_To_Subprogram_Definition =>
2232                Access_Subprogram_Declaration (T, Def);
2233
2234                --  If this is a remote access to subprogram, we must create the
2235                --  equivalent fat pointer type, and related subprograms.
2236
2237                if Is_Remote then
2238                   Process_Remote_AST_Declaration (N);
2239                end if;
2240
2241                --  Validate categorization rule against access type declaration
2242                --  usually a violation in Pure unit, Shared_Passive unit.
2243
2244                Validate_Access_Type_Declaration (T, N);
2245
2246             when N_Access_To_Object_Definition =>
2247                Access_Type_Declaration (T, Def);
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                --  If we are in a Remote_Call_Interface package and define a
2255                --  RACW, then calling stubs and specific stream attributes
2256                --  must be added.
2257
2258                if Is_Remote
2259                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2260                then
2261                   Add_RACW_Features (Def_Id);
2262                end if;
2263
2264                --  Set no strict aliasing flag if config pragma seen
2265
2266                if Opt.No_Strict_Aliasing then
2267                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
2268                end if;
2269
2270             when N_Array_Type_Definition =>
2271                Array_Type_Declaration (T, Def);
2272
2273             when N_Derived_Type_Definition =>
2274                Derived_Type_Declaration (T, N, T /= Def_Id);
2275
2276             when N_Enumeration_Type_Definition =>
2277                Enumeration_Type_Declaration (T, Def);
2278
2279             when N_Floating_Point_Definition =>
2280                Floating_Point_Type_Declaration (T, Def);
2281
2282             when N_Decimal_Fixed_Point_Definition =>
2283                Decimal_Fixed_Point_Type_Declaration (T, Def);
2284
2285             when N_Ordinary_Fixed_Point_Definition =>
2286                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2287
2288             when N_Signed_Integer_Type_Definition =>
2289                Signed_Integer_Type_Declaration (T, Def);
2290
2291             when N_Modular_Type_Definition =>
2292                Modular_Type_Declaration (T, Def);
2293
2294             when N_Record_Definition =>
2295                Record_Type_Declaration (T, N, Prev);
2296
2297             --  If declaration has a parse error, nothing to elaborate.
2298
2299             when N_Error =>
2300                null;
2301
2302             when others =>
2303                raise Program_Error;
2304
2305          end case;
2306       end if;
2307
2308       if Etype (T) = Any_Type then
2309          return;
2310       end if;
2311
2312       --  Some common processing for all types
2313
2314       Set_Depends_On_Private (T, Has_Private_Component (T));
2315       Check_Ops_From_Incomplete_Type;
2316
2317       --  Both the declared entity, and its anonymous base type if one
2318       --  was created, need freeze nodes allocated.
2319
2320       declare
2321          B : constant Entity_Id := Base_Type (T);
2322
2323       begin
2324          --  In the case where the base type differs from the first subtype, we
2325          --  pre-allocate a freeze node, and set the proper link to the first
2326          --  subtype. Freeze_Entity will use this preallocated freeze node when
2327          --  it freezes the entity.
2328
2329          --  This does not apply if the base type is a generic type, whose
2330          --  declaration is independent of the current derived definition.
2331
2332          if B /= T and then not Is_Generic_Type (B) then
2333             Ensure_Freeze_Node (B);
2334             Set_First_Subtype_Link (Freeze_Node (B), T);
2335          end if;
2336
2337          --  A type that is imported through a limited_with clause cannot
2338          --  generate any code, and thus need not be frozen. However, an access
2339          --  type with an imported designated type needs a finalization list,
2340          --  which may be referenced in some other package that has non-limited
2341          --  visibility on the designated type. Thus we must create the
2342          --  finalization list at the point the access type is frozen, to
2343          --  prevent unsatisfied references at link time.
2344
2345          if not From_With_Type (T) or else Is_Access_Type (T) then
2346             Set_Has_Delayed_Freeze (T);
2347          end if;
2348       end;
2349
2350       --  Case where T is the full declaration of some private type which has
2351       --  been swapped in Defining_Identifier (N).
2352
2353       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2354          Process_Full_View (N, T, Def_Id);
2355
2356          --  Record the reference. The form of this is a little strange, since
2357          --  the full declaration has been swapped in. So the first parameter
2358          --  here represents the entity to which a reference is made which is
2359          --  the "real" entity, i.e. the one swapped in, and the second
2360          --  parameter provides the reference location.
2361
2362          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2363          --  since we don't want a complaint about the full type being an
2364          --  unwanted reference to the private type
2365
2366          declare
2367             B : constant Boolean := Has_Pragma_Unreferenced (T);
2368          begin
2369             Set_Has_Pragma_Unreferenced (T, False);
2370             Generate_Reference (T, T, 'c');
2371             Set_Has_Pragma_Unreferenced (T, B);
2372          end;
2373
2374          Set_Completion_Referenced (Def_Id);
2375
2376       --  For completion of incomplete type, process incomplete dependents
2377       --  and always mark the full type as referenced (it is the incomplete
2378       --  type that we get for any real reference).
2379
2380       elsif Ekind (Prev) = E_Incomplete_Type then
2381          Process_Incomplete_Dependents (N, T, Prev);
2382          Generate_Reference (Prev, Def_Id, 'c');
2383          Set_Completion_Referenced (Def_Id);
2384
2385       --  If not private type or incomplete type completion, this is a real
2386       --  definition of a new entity, so record it.
2387
2388       else
2389          Generate_Definition (Def_Id);
2390       end if;
2391
2392       if Chars (Scope (Def_Id)) = Name_System
2393         and then Chars (Def_Id) = Name_Address
2394         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2395       then
2396          Set_Is_Descendent_Of_Address (Def_Id);
2397          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2398          Set_Is_Descendent_Of_Address (Prev);
2399       end if;
2400
2401       Set_Optimize_Alignment_Flags (Def_Id);
2402       Check_Eliminated (Def_Id);
2403
2404       if Nkind (N) = N_Full_Type_Declaration then
2405          Analyze_Aspect_Specifications (N, Def_Id, Aspect_Specifications (N));
2406       end if;
2407    end Analyze_Full_Type_Declaration;
2408
2409    ----------------------------------
2410    -- Analyze_Incomplete_Type_Decl --
2411    ----------------------------------
2412
2413    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2414       F : constant Boolean := Is_Pure (Current_Scope);
2415       T : Entity_Id;
2416
2417    begin
2418       Generate_Definition (Defining_Identifier (N));
2419
2420       --  Process an incomplete declaration. The identifier must not have been
2421       --  declared already in the scope. However, an incomplete declaration may
2422       --  appear in the private part of a package, for a private type that has
2423       --  already been declared.
2424
2425       --  In this case, the discriminants (if any) must match
2426
2427       T := Find_Type_Name (N);
2428
2429       Set_Ekind (T, E_Incomplete_Type);
2430       Init_Size_Align (T);
2431       Set_Is_First_Subtype (T, True);
2432       Set_Etype (T, T);
2433
2434       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2435       --  incomplete types.
2436
2437       if Tagged_Present (N) then
2438          Set_Is_Tagged_Type (T);
2439          Make_Class_Wide_Type (T);
2440          Set_Direct_Primitive_Operations (T, New_Elmt_List);
2441       end if;
2442
2443       Push_Scope (T);
2444
2445       Set_Stored_Constraint (T, No_Elist);
2446
2447       if Present (Discriminant_Specifications (N)) then
2448          Process_Discriminants (N);
2449       end if;
2450
2451       End_Scope;
2452
2453       --  If the type has discriminants, non-trivial subtypes may be
2454       --  declared before the full view of the type. The full views of those
2455       --  subtypes will be built after the full view of the type.
2456
2457       Set_Private_Dependents (T, New_Elmt_List);
2458       Set_Is_Pure (T, F);
2459    end Analyze_Incomplete_Type_Decl;
2460
2461    -----------------------------------
2462    -- Analyze_Interface_Declaration --
2463    -----------------------------------
2464
2465    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2466       CW : constant Entity_Id := Class_Wide_Type (T);
2467
2468    begin
2469       Set_Is_Tagged_Type (T);
2470
2471       Set_Is_Limited_Record (T, Limited_Present (Def)
2472                                   or else Task_Present (Def)
2473                                   or else Protected_Present (Def)
2474                                   or else Synchronized_Present (Def));
2475
2476       --  Type is abstract if full declaration carries keyword, or if previous
2477       --  partial view did.
2478
2479       Set_Is_Abstract_Type (T);
2480       Set_Is_Interface (T);
2481
2482       --  Type is a limited interface if it includes the keyword limited, task,
2483       --  protected, or synchronized.
2484
2485       Set_Is_Limited_Interface
2486         (T, Limited_Present (Def)
2487               or else Protected_Present (Def)
2488               or else Synchronized_Present (Def)
2489               or else Task_Present (Def));
2490
2491       Set_Interfaces (T, New_Elmt_List);
2492       Set_Direct_Primitive_Operations (T, New_Elmt_List);
2493
2494       --  Complete the decoration of the class-wide entity if it was already
2495       --  built (i.e. during the creation of the limited view)
2496
2497       if Present (CW) then
2498          Set_Is_Interface (CW);
2499          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2500       end if;
2501
2502       --  Check runtime support for synchronized interfaces
2503
2504       if VM_Target = No_VM
2505         and then (Is_Task_Interface (T)
2506                     or else Is_Protected_Interface (T)
2507                     or else Is_Synchronized_Interface (T))
2508         and then not RTE_Available (RE_Select_Specific_Data)
2509       then
2510          Error_Msg_CRT ("synchronized interfaces", T);
2511       end if;
2512    end Analyze_Interface_Declaration;
2513
2514    -----------------------------
2515    -- Analyze_Itype_Reference --
2516    -----------------------------
2517
2518    --  Nothing to do. This node is placed in the tree only for the benefit of
2519    --  back end processing, and has no effect on the semantic processing.
2520
2521    procedure Analyze_Itype_Reference (N : Node_Id) is
2522    begin
2523       pragma Assert (Is_Itype (Itype (N)));
2524       null;
2525    end Analyze_Itype_Reference;
2526
2527    --------------------------------
2528    -- Analyze_Number_Declaration --
2529    --------------------------------
2530
2531    procedure Analyze_Number_Declaration (N : Node_Id) is
2532       Id    : constant Entity_Id := Defining_Identifier (N);
2533       E     : constant Node_Id   := Expression (N);
2534       T     : Entity_Id;
2535       Index : Interp_Index;
2536       It    : Interp;
2537
2538    begin
2539       Generate_Definition (Id);
2540       Enter_Name (Id);
2541
2542       --  This is an optimization of a common case of an integer literal
2543
2544       if Nkind (E) = N_Integer_Literal then
2545          Set_Is_Static_Expression (E, True);
2546          Set_Etype                (E, Universal_Integer);
2547
2548          Set_Etype     (Id, Universal_Integer);
2549          Set_Ekind     (Id, E_Named_Integer);
2550          Set_Is_Frozen (Id, True);
2551          return;
2552       end if;
2553
2554       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2555
2556       --  Process expression, replacing error by integer zero, to avoid
2557       --  cascaded errors or aborts further along in the processing
2558
2559       --  Replace Error by integer zero, which seems least likely to
2560       --  cause cascaded errors.
2561
2562       if E = Error then
2563          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2564          Set_Error_Posted (E);
2565       end if;
2566
2567       Analyze (E);
2568
2569       --  Verify that the expression is static and numeric. If
2570       --  the expression is overloaded, we apply the preference
2571       --  rule that favors root numeric types.
2572
2573       if not Is_Overloaded (E) then
2574          T := Etype (E);
2575
2576       else
2577          T := Any_Type;
2578
2579          Get_First_Interp (E, Index, It);
2580          while Present (It.Typ) loop
2581             if (Is_Integer_Type (It.Typ)
2582                  or else Is_Real_Type (It.Typ))
2583               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2584             then
2585                if T = Any_Type then
2586                   T := It.Typ;
2587
2588                elsif It.Typ = Universal_Real
2589                  or else It.Typ = Universal_Integer
2590                then
2591                   --  Choose universal interpretation over any other
2592
2593                   T := It.Typ;
2594                   exit;
2595                end if;
2596             end if;
2597
2598             Get_Next_Interp (Index, It);
2599          end loop;
2600       end if;
2601
2602       if Is_Integer_Type (T)  then
2603          Resolve (E, T);
2604          Set_Etype (Id, Universal_Integer);
2605          Set_Ekind (Id, E_Named_Integer);
2606
2607       elsif Is_Real_Type (T) then
2608
2609          --  Because the real value is converted to universal_real, this is a
2610          --  legal context for a universal fixed expression.
2611
2612          if T = Universal_Fixed then
2613             declare
2614                Loc  : constant Source_Ptr := Sloc (N);
2615                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2616                         Subtype_Mark =>
2617                           New_Occurrence_Of (Universal_Real, Loc),
2618                         Expression => Relocate_Node (E));
2619
2620             begin
2621                Rewrite (E, Conv);
2622                Analyze (E);
2623             end;
2624
2625          elsif T = Any_Fixed then
2626             Error_Msg_N ("illegal context for mixed mode operation", E);
2627
2628             --  Expression is of the form : universal_fixed * integer. Try to
2629             --  resolve as universal_real.
2630
2631             T := Universal_Real;
2632             Set_Etype (E, T);
2633          end if;
2634
2635          Resolve (E, T);
2636          Set_Etype (Id, Universal_Real);
2637          Set_Ekind (Id, E_Named_Real);
2638
2639       else
2640          Wrong_Type (E, Any_Numeric);
2641          Resolve (E, T);
2642
2643          Set_Etype               (Id, T);
2644          Set_Ekind               (Id, E_Constant);
2645          Set_Never_Set_In_Source (Id, True);
2646          Set_Is_True_Constant    (Id, True);
2647          return;
2648       end if;
2649
2650       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2651          Set_Etype (E, Etype (Id));
2652       end if;
2653
2654       if not Is_OK_Static_Expression (E) then
2655          Flag_Non_Static_Expr
2656            ("non-static expression used in number declaration!", E);
2657          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2658          Set_Etype (E, Any_Type);
2659       end if;
2660    end Analyze_Number_Declaration;
2661
2662    --------------------------------
2663    -- Analyze_Object_Declaration --
2664    --------------------------------
2665
2666    procedure Analyze_Object_Declaration (N : Node_Id) is
2667       Loc   : constant Source_Ptr := Sloc (N);
2668       Id    : constant Entity_Id  := Defining_Identifier (N);
2669       T     : Entity_Id;
2670       Act_T : Entity_Id;
2671
2672       E : Node_Id := Expression (N);
2673       --  E is set to Expression (N) throughout this routine. When
2674       --  Expression (N) is modified, E is changed accordingly.
2675
2676       Prev_Entity : Entity_Id := Empty;
2677
2678       function Count_Tasks (T : Entity_Id) return Uint;
2679       --  This function is called when a non-generic library level object of a
2680       --  task type is declared. Its function is to count the static number of
2681       --  tasks declared within the type (it is only called if Has_Tasks is set
2682       --  for T). As a side effect, if an array of tasks with non-static bounds
2683       --  or a variant record type is encountered, Check_Restrictions is called
2684       --  indicating the count is unknown.
2685
2686       -----------------
2687       -- Count_Tasks --
2688       -----------------
2689
2690       function Count_Tasks (T : Entity_Id) return Uint is
2691          C : Entity_Id;
2692          X : Node_Id;
2693          V : Uint;
2694
2695       begin
2696          if Is_Task_Type (T) then
2697             return Uint_1;
2698
2699          elsif Is_Record_Type (T) then
2700             if Has_Discriminants (T) then
2701                Check_Restriction (Max_Tasks, N);
2702                return Uint_0;
2703
2704             else
2705                V := Uint_0;
2706                C := First_Component (T);
2707                while Present (C) loop
2708                   V := V + Count_Tasks (Etype (C));
2709                   Next_Component (C);
2710                end loop;
2711
2712                return V;
2713             end if;
2714
2715          elsif Is_Array_Type (T) then
2716             X := First_Index (T);
2717             V := Count_Tasks (Component_Type (T));
2718             while Present (X) loop
2719                C := Etype (X);
2720
2721                if not Is_Static_Subtype (C) then
2722                   Check_Restriction (Max_Tasks, N);
2723                   return Uint_0;
2724                else
2725                   V := V * (UI_Max (Uint_0,
2726                                     Expr_Value (Type_High_Bound (C)) -
2727                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2728                end if;
2729
2730                Next_Index (X);
2731             end loop;
2732
2733             return V;
2734
2735          else
2736             return Uint_0;
2737          end if;
2738       end Count_Tasks;
2739
2740    --  Start of processing for Analyze_Object_Declaration
2741
2742    begin
2743       --  There are three kinds of implicit types generated by an
2744       --  object declaration:
2745
2746       --   1. Those for generated by the original Object Definition
2747
2748       --   2. Those generated by the Expression
2749
2750       --   3. Those used to constrained the Object Definition with the
2751       --       expression constraints when it is unconstrained
2752
2753       --  They must be generated in this order to avoid order of elaboration
2754       --  issues. Thus the first step (after entering the name) is to analyze
2755       --  the object definition.
2756
2757       if Constant_Present (N) then
2758          Prev_Entity := Current_Entity_In_Scope (Id);
2759
2760          if Present (Prev_Entity)
2761            and then
2762              --  If the homograph is an implicit subprogram, it is overridden
2763              --  by the current declaration.
2764
2765              ((Is_Overloadable (Prev_Entity)
2766                 and then Is_Inherited_Operation (Prev_Entity))
2767
2768                --  The current object is a discriminal generated for an entry
2769                --  family index. Even though the index is a constant, in this
2770                --  particular context there is no true constant redeclaration.
2771                --  Enter_Name will handle the visibility.
2772
2773                or else
2774                 (Is_Discriminal (Id)
2775                    and then Ekind (Discriminal_Link (Id)) =
2776                               E_Entry_Index_Parameter)
2777
2778                --  The current object is the renaming for a generic declared
2779                --  within the instance.
2780
2781                or else
2782                 (Ekind (Prev_Entity) = E_Package
2783                   and then Nkind (Parent (Prev_Entity)) =
2784                                          N_Package_Renaming_Declaration
2785                   and then not Comes_From_Source (Prev_Entity)
2786                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
2787          then
2788             Prev_Entity := Empty;
2789          end if;
2790       end if;
2791
2792       if Present (Prev_Entity) then
2793          Constant_Redeclaration (Id, N, T);
2794
2795          Generate_Reference (Prev_Entity, Id, 'c');
2796          Set_Completion_Referenced (Id);
2797
2798          if Error_Posted (N) then
2799
2800             --  Type mismatch or illegal redeclaration, Do not analyze
2801             --  expression to avoid cascaded errors.
2802
2803             T := Find_Type_Of_Object (Object_Definition (N), N);
2804             Set_Etype (Id, T);
2805             Set_Ekind (Id, E_Variable);
2806             goto Leave;
2807          end if;
2808
2809       --  In the normal case, enter identifier at the start to catch premature
2810       --  usage in the initialization expression.
2811
2812       else
2813          Generate_Definition (Id);
2814          Enter_Name (Id);
2815
2816          Mark_Coextensions (N, Object_Definition (N));
2817
2818          T := Find_Type_Of_Object (Object_Definition (N), N);
2819
2820          if Nkind (Object_Definition (N)) = N_Access_Definition
2821            and then Present
2822              (Access_To_Subprogram_Definition (Object_Definition (N)))
2823            and then Protected_Present
2824              (Access_To_Subprogram_Definition (Object_Definition (N)))
2825          then
2826             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2827          end if;
2828
2829          if Error_Posted (Id) then
2830             Set_Etype (Id, T);
2831             Set_Ekind (Id, E_Variable);
2832             goto Leave;
2833          end if;
2834       end if;
2835
2836       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2837       --  out some static checks
2838
2839       if Ada_Version >= Ada_2005
2840         and then Can_Never_Be_Null (T)
2841       then
2842          --  In case of aggregates we must also take care of the correct
2843          --  initialization of nested aggregates bug this is done at the
2844          --  point of the analysis of the aggregate (see sem_aggr.adb)
2845
2846          if Present (Expression (N))
2847            and then Nkind (Expression (N)) = N_Aggregate
2848          then
2849             null;
2850
2851          else
2852             declare
2853                Save_Typ : constant Entity_Id := Etype (Id);
2854             begin
2855                Set_Etype (Id, T); --  Temp. decoration for static checks
2856                Null_Exclusion_Static_Checks (N);
2857                Set_Etype (Id, Save_Typ);
2858             end;
2859          end if;
2860       end if;
2861
2862       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2863
2864       --  If deferred constant, make sure context is appropriate. We detect
2865       --  a deferred constant as a constant declaration with no expression.
2866       --  A deferred constant can appear in a package body if its completion
2867       --  is by means of an interface pragma.
2868
2869       if Constant_Present (N)
2870         and then No (E)
2871       then
2872          --  A deferred constant may appear in the declarative part of the
2873          --  following constructs:
2874
2875          --     blocks
2876          --     entry bodies
2877          --     extended return statements
2878          --     package specs
2879          --     package bodies
2880          --     subprogram bodies
2881          --     task bodies
2882
2883          --  When declared inside a package spec, a deferred constant must be
2884          --  completed by a full constant declaration or pragma Import. In all
2885          --  other cases, the only proper completion is pragma Import. Extended
2886          --  return statements are flagged as invalid contexts because they do
2887          --  not have a declarative part and so cannot accommodate the pragma.
2888
2889          if Ekind (Current_Scope) = E_Return_Statement then
2890             Error_Msg_N
2891               ("invalid context for deferred constant declaration (RM 7.4)",
2892                N);
2893             Error_Msg_N
2894               ("\declaration requires an initialization expression",
2895                 N);
2896             Set_Constant_Present (N, False);
2897
2898          --  In Ada 83, deferred constant must be of private type
2899
2900          elsif not Is_Private_Type (T) then
2901             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
2902                Error_Msg_N
2903                  ("(Ada 83) deferred constant must be private type", N);
2904             end if;
2905          end if;
2906
2907       --  If not a deferred constant, then object declaration freezes its type
2908
2909       else
2910          Check_Fully_Declared (T, N);
2911          Freeze_Before (N, T);
2912       end if;
2913
2914       --  If the object was created by a constrained array definition, then
2915       --  set the link in both the anonymous base type and anonymous subtype
2916       --  that are built to represent the array type to point to the object.
2917
2918       if Nkind (Object_Definition (Declaration_Node (Id))) =
2919                         N_Constrained_Array_Definition
2920       then
2921          Set_Related_Array_Object (T, Id);
2922          Set_Related_Array_Object (Base_Type (T), Id);
2923       end if;
2924
2925       --  Special checks for protected objects not at library level
2926
2927       if Is_Protected_Type (T)
2928         and then not Is_Library_Level_Entity (Id)
2929       then
2930          Check_Restriction (No_Local_Protected_Objects, Id);
2931
2932          --  Protected objects with interrupt handlers must be at library level
2933
2934          --  Ada 2005: this test is not needed (and the corresponding clause
2935          --  in the RM is removed) because accessibility checks are sufficient
2936          --  to make handlers not at the library level illegal.
2937
2938          if Has_Interrupt_Handler (T)
2939            and then Ada_Version < Ada_2005
2940          then
2941             Error_Msg_N
2942               ("interrupt object can only be declared at library level", Id);
2943          end if;
2944       end if;
2945
2946       --  The actual subtype of the object is the nominal subtype, unless
2947       --  the nominal one is unconstrained and obtained from the expression.
2948
2949       Act_T := T;
2950
2951       --  Process initialization expression if present and not in error
2952
2953       if Present (E) and then E /= Error then
2954
2955          --  Generate an error in case of CPP class-wide object initialization.
2956          --  Required because otherwise the expansion of the class-wide
2957          --  assignment would try to use 'size to initialize the object
2958          --  (primitive that is not available in CPP tagged types).
2959
2960          if Is_Class_Wide_Type (Act_T)
2961            and then
2962              (Is_CPP_Class (Root_Type (Etype (Act_T)))
2963                or else
2964                  (Present (Full_View (Root_Type (Etype (Act_T))))
2965                     and then
2966                       Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
2967          then
2968             Error_Msg_N
2969               ("predefined assignment not available for 'C'P'P tagged types",
2970                E);
2971          end if;
2972
2973          Mark_Coextensions (N, E);
2974          Analyze (E);
2975
2976          --  In case of errors detected in the analysis of the expression,
2977          --  decorate it with the expected type to avoid cascaded errors
2978
2979          if No (Etype (E)) then
2980             Set_Etype (E, T);
2981          end if;
2982
2983          --  If an initialization expression is present, then we set the
2984          --  Is_True_Constant flag. It will be reset if this is a variable
2985          --  and it is indeed modified.
2986
2987          Set_Is_True_Constant (Id, True);
2988
2989          --  If we are analyzing a constant declaration, set its completion
2990          --  flag after analyzing and resolving the expression.
2991
2992          if Constant_Present (N) then
2993             Set_Has_Completion (Id);
2994          end if;
2995
2996          --  Set type and resolve (type may be overridden later on)
2997
2998          Set_Etype (Id, T);
2999          Resolve (E, T);
3000
3001          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3002          --  node (which was marked already-analyzed), we need to set the type
3003          --  to something other than Any_Access in order to keep gigi happy.
3004
3005          if Etype (E) = Any_Access then
3006             Set_Etype (E, T);
3007          end if;
3008
3009          --  If the object is an access to variable, the initialization
3010          --  expression cannot be an access to constant.
3011
3012          if Is_Access_Type (T)
3013            and then not Is_Access_Constant (T)
3014            and then Is_Access_Type (Etype (E))
3015            and then Is_Access_Constant (Etype (E))
3016          then
3017             Error_Msg_N
3018               ("access to variable cannot be initialized "
3019                & "with an access-to-constant expression", E);
3020          end if;
3021
3022          if not Assignment_OK (N) then
3023             Check_Initialization (T, E);
3024          end if;
3025
3026          Check_Unset_Reference (E);
3027
3028          --  If this is a variable, then set current value. If this is a
3029          --  declared constant of a scalar type with a static expression,
3030          --  indicate that it is always valid.
3031
3032          if not Constant_Present (N) then
3033             if Compile_Time_Known_Value (E) then
3034                Set_Current_Value (Id, E);
3035             end if;
3036
3037          elsif Is_Scalar_Type (T)
3038            and then Is_OK_Static_Expression (E)
3039          then
3040             Set_Is_Known_Valid (Id);
3041          end if;
3042
3043          --  Deal with setting of null flags
3044
3045          if Is_Access_Type (T) then
3046             if Known_Non_Null (E) then
3047                Set_Is_Known_Non_Null (Id, True);
3048             elsif Known_Null (E)
3049               and then not Can_Never_Be_Null (Id)
3050             then
3051                Set_Is_Known_Null (Id, True);
3052             end if;
3053          end if;
3054
3055          --  Check incorrect use of dynamically tagged expressions.
3056
3057          if Is_Tagged_Type (T) then
3058             Check_Dynamically_Tagged_Expression
3059               (Expr        => E,
3060                Typ         => T,
3061                Related_Nod => N);
3062          end if;
3063
3064          Apply_Scalar_Range_Check (E, T);
3065          Apply_Static_Length_Check (E, T);
3066       end if;
3067
3068       --  If the No_Streams restriction is set, check that the type of the
3069       --  object is not, and does not contain, any subtype derived from
3070       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3071       --  Has_Stream just for efficiency reasons. There is no point in
3072       --  spending time on a Has_Stream check if the restriction is not set.
3073
3074       if Restriction_Check_Required (No_Streams) then
3075          if Has_Stream (T) then
3076             Check_Restriction (No_Streams, N);
3077          end if;
3078       end if;
3079
3080       --  Case of unconstrained type
3081
3082       if Is_Indefinite_Subtype (T) then
3083
3084          --  Nothing to do in deferred constant case
3085
3086          if Constant_Present (N) and then No (E) then
3087             null;
3088
3089          --  Case of no initialization present
3090
3091          elsif No (E) then
3092             if No_Initialization (N) then
3093                null;
3094
3095             elsif Is_Class_Wide_Type (T) then
3096                Error_Msg_N
3097                  ("initialization required in class-wide declaration ", N);
3098
3099             else
3100                Error_Msg_N
3101                  ("unconstrained subtype not allowed (need initialization)",
3102                   Object_Definition (N));
3103
3104                if Is_Record_Type (T) and then Has_Discriminants (T) then
3105                   Error_Msg_N
3106                     ("\provide initial value or explicit discriminant values",
3107                      Object_Definition (N));
3108
3109                   Error_Msg_NE
3110                     ("\or give default discriminant values for type&",
3111                      Object_Definition (N), T);
3112
3113                elsif Is_Array_Type (T) then
3114                   Error_Msg_N
3115                     ("\provide initial value or explicit array bounds",
3116                      Object_Definition (N));
3117                end if;
3118             end if;
3119
3120          --  Case of initialization present but in error. Set initial
3121          --  expression as absent (but do not make above complaints)
3122
3123          elsif E = Error then
3124             Set_Expression (N, Empty);
3125             E := Empty;
3126
3127          --  Case of initialization present
3128
3129          else
3130             --  Not allowed in Ada 83
3131
3132             if not Constant_Present (N) then
3133                if Ada_Version = Ada_83
3134                  and then Comes_From_Source (Object_Definition (N))
3135                then
3136                   Error_Msg_N
3137                     ("(Ada 83) unconstrained variable not allowed",
3138                      Object_Definition (N));
3139                end if;
3140             end if;
3141
3142             --  Now we constrain the variable from the initializing expression
3143
3144             --  If the expression is an aggregate, it has been expanded into
3145             --  individual assignments. Retrieve the actual type from the
3146             --  expanded construct.
3147
3148             if Is_Array_Type (T)
3149               and then No_Initialization (N)
3150               and then Nkind (Original_Node (E)) = N_Aggregate
3151             then
3152                Act_T := Etype (E);
3153
3154             --  In case of class-wide interface object declarations we delay
3155             --  the generation of the equivalent record type declarations until
3156             --  its expansion because there are cases in they are not required.
3157
3158             elsif Is_Interface (T) then
3159                null;
3160
3161             else
3162                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3163                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3164             end if;
3165
3166             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3167
3168             if Aliased_Present (N) then
3169                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3170             end if;
3171
3172             Freeze_Before (N, Act_T);
3173             Freeze_Before (N, T);
3174          end if;
3175
3176       elsif Is_Array_Type (T)
3177         and then No_Initialization (N)
3178         and then Nkind (Original_Node (E)) = N_Aggregate
3179       then
3180          if not Is_Entity_Name (Object_Definition (N)) then
3181             Act_T := Etype (E);
3182             Check_Compile_Time_Size (Act_T);
3183
3184             if Aliased_Present (N) then
3185                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3186             end if;
3187          end if;
3188
3189          --  When the given object definition and the aggregate are specified
3190          --  independently, and their lengths might differ do a length check.
3191          --  This cannot happen if the aggregate is of the form (others =>...)
3192
3193          if not Is_Constrained (T) then
3194             null;
3195
3196          elsif Nkind (E) = N_Raise_Constraint_Error then
3197
3198             --  Aggregate is statically illegal. Place back in declaration
3199
3200             Set_Expression (N, E);
3201             Set_No_Initialization (N, False);
3202
3203          elsif T = Etype (E) then
3204             null;
3205
3206          elsif Nkind (E) = N_Aggregate
3207            and then Present (Component_Associations (E))
3208            and then Present (Choices (First (Component_Associations (E))))
3209            and then Nkind (First
3210             (Choices (First (Component_Associations (E))))) = N_Others_Choice
3211          then
3212             null;
3213
3214          else
3215             Apply_Length_Check (E, T);
3216          end if;
3217
3218       --  If the type is limited unconstrained with defaulted discriminants and
3219       --  there is no expression, then the object is constrained by the
3220       --  defaults, so it is worthwhile building the corresponding subtype.
3221
3222       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
3223         and then not Is_Constrained (T)
3224         and then Has_Discriminants (T)
3225       then
3226          if No (E) then
3227             Act_T := Build_Default_Subtype (T, N);
3228          else
3229             --  Ada 2005:  a limited object may be initialized by means of an
3230             --  aggregate. If the type has default discriminants it has an
3231             --  unconstrained nominal type, Its actual subtype will be obtained
3232             --  from the aggregate, and not from the default discriminants.
3233
3234             Act_T := Etype (E);
3235          end if;
3236
3237          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
3238
3239       elsif Present (Underlying_Type (T))
3240         and then not Is_Constrained (Underlying_Type (T))
3241         and then Has_Discriminants (Underlying_Type (T))
3242         and then Nkind (E) = N_Function_Call
3243         and then Constant_Present (N)
3244       then
3245          --  The back-end has problems with constants of a discriminated type
3246          --  with defaults, if the initial value is a function call. We
3247          --  generate an intermediate temporary for the result of the call.
3248          --  It is unclear why this should make it acceptable to gcc. ???
3249
3250          Remove_Side_Effects (E);
3251       end if;
3252
3253       --  Check No_Wide_Characters restriction
3254
3255       Check_Wide_Character_Restriction (T, Object_Definition (N));
3256
3257       --  Indicate this is not set in source. Certainly true for constants,
3258       --  and true for variables so far (will be reset for a variable if and
3259       --  when we encounter a modification in the source).
3260
3261       Set_Never_Set_In_Source (Id, True);
3262
3263       --  Now establish the proper kind and type of the object
3264
3265       if Constant_Present (N) then
3266          Set_Ekind            (Id, E_Constant);
3267          Set_Is_True_Constant (Id, True);
3268
3269       else
3270          Set_Ekind (Id, E_Variable);
3271
3272          --  A variable is set as shared passive if it appears in a shared
3273          --  passive package, and is at the outer level. This is not done
3274          --  for entities generated during expansion, because those are
3275          --  always manipulated locally.
3276
3277          if Is_Shared_Passive (Current_Scope)
3278            and then Is_Library_Level_Entity (Id)
3279            and then Comes_From_Source (Id)
3280          then
3281             Set_Is_Shared_Passive (Id);
3282             Check_Shared_Var (Id, T, N);
3283          end if;
3284
3285          --  Set Has_Initial_Value if initializing expression present. Note
3286          --  that if there is no initializing expression, we leave the state
3287          --  of this flag unchanged (usually it will be False, but notably in
3288          --  the case of exception choice variables, it will already be true).
3289
3290          if Present (E) then
3291             Set_Has_Initial_Value (Id, True);
3292          end if;
3293       end if;
3294
3295       --  Initialize alignment and size and capture alignment setting
3296
3297       Init_Alignment               (Id);
3298       Init_Esize                   (Id);
3299       Set_Optimize_Alignment_Flags (Id);
3300
3301       --  Deal with aliased case
3302
3303       if Aliased_Present (N) then
3304          Set_Is_Aliased (Id);
3305
3306          --  If the object is aliased and the type is unconstrained with
3307          --  defaulted discriminants and there is no expression, then the
3308          --  object is constrained by the defaults, so it is worthwhile
3309          --  building the corresponding subtype.
3310
3311          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3312          --  unconstrained, then only establish an actual subtype if the
3313          --  nominal subtype is indefinite. In definite cases the object is
3314          --  unconstrained in Ada 2005.
3315
3316          if No (E)
3317            and then Is_Record_Type (T)
3318            and then not Is_Constrained (T)
3319            and then Has_Discriminants (T)
3320            and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
3321          then
3322             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3323          end if;
3324       end if;
3325
3326       --  Now we can set the type of the object
3327
3328       Set_Etype (Id, Act_T);
3329
3330       --  Deal with controlled types
3331
3332       if Has_Controlled_Component (Etype (Id))
3333         or else Is_Controlled (Etype (Id))
3334       then
3335          if not Is_Library_Level_Entity (Id) then
3336             Check_Restriction (No_Nested_Finalization, N);
3337          else
3338             Validate_Controlled_Object (Id);
3339          end if;
3340
3341          --  Generate a warning when an initialization causes an obvious ABE
3342          --  violation. If the init expression is a simple aggregate there
3343          --  shouldn't be any initialize/adjust call generated. This will be
3344          --  true as soon as aggregates are built in place when possible.
3345
3346          --  ??? at the moment we do not generate warnings for temporaries
3347          --  created for those aggregates although Program_Error might be
3348          --  generated if compiled with -gnato.
3349
3350          if Is_Controlled (Etype (Id))
3351             and then Comes_From_Source (Id)
3352          then
3353             declare
3354                BT : constant Entity_Id := Base_Type (Etype (Id));
3355
3356                Implicit_Call : Entity_Id;
3357                pragma Warnings (Off, Implicit_Call);
3358                --  ??? what is this for (never referenced!)
3359
3360                function Is_Aggr (N : Node_Id) return Boolean;
3361                --  Check that N is an aggregate
3362
3363                -------------
3364                -- Is_Aggr --
3365                -------------
3366
3367                function Is_Aggr (N : Node_Id) return Boolean is
3368                begin
3369                   case Nkind (Original_Node (N)) is
3370                      when N_Aggregate | N_Extension_Aggregate =>
3371                         return True;
3372
3373                      when N_Qualified_Expression |
3374                           N_Type_Conversion      |
3375                           N_Unchecked_Type_Conversion =>
3376                         return Is_Aggr (Expression (Original_Node (N)));
3377
3378                      when others =>
3379                         return False;
3380                   end case;
3381                end Is_Aggr;
3382
3383             begin
3384                --  If no underlying type, we already are in an error situation.
3385                --  Do not try to add a warning since we do not have access to
3386                --  prim-op list.
3387
3388                if No (Underlying_Type (BT)) then
3389                   Implicit_Call := Empty;
3390
3391                --  A generic type does not have usable primitive operators.
3392                --  Initialization calls are built for instances.
3393
3394                elsif Is_Generic_Type (BT) then
3395                   Implicit_Call := Empty;
3396
3397                --  If the init expression is not an aggregate, an adjust call
3398                --  will be generated
3399
3400                elsif Present (E) and then not Is_Aggr (E) then
3401                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
3402
3403                --  If no init expression and we are not in the deferred
3404                --  constant case, an Initialize call will be generated
3405
3406                elsif No (E) and then not Constant_Present (N) then
3407                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
3408
3409                else
3410                   Implicit_Call := Empty;
3411                end if;
3412             end;
3413          end if;
3414       end if;
3415
3416       if Has_Task (Etype (Id)) then
3417          Check_Restriction (No_Tasking, N);
3418
3419          --  Deal with counting max tasks
3420
3421          --  Nothing to do if inside a generic
3422
3423          if Inside_A_Generic then
3424             null;
3425
3426          --  If library level entity, then count tasks
3427
3428          elsif Is_Library_Level_Entity (Id) then
3429             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3430
3431          --  If not library level entity, then indicate we don't know max
3432          --  tasks and also check task hierarchy restriction and blocking
3433          --  operation (since starting a task is definitely blocking!)
3434
3435          else
3436             Check_Restriction (Max_Tasks, N);
3437             Check_Restriction (No_Task_Hierarchy, N);
3438             Check_Potentially_Blocking_Operation (N);
3439          end if;
3440
3441          --  A rather specialized test. If we see two tasks being declared
3442          --  of the same type in the same object declaration, and the task
3443          --  has an entry with an address clause, we know that program error
3444          --  will be raised at run time since we can't have two tasks with
3445          --  entries at the same address.
3446
3447          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3448             declare
3449                E : Entity_Id;
3450
3451             begin
3452                E := First_Entity (Etype (Id));
3453                while Present (E) loop
3454                   if Ekind (E) = E_Entry
3455                     and then Present (Get_Attribute_Definition_Clause
3456                                         (E, Attribute_Address))
3457                   then
3458                      Error_Msg_N
3459                        ("?more than one task with same entry address", N);
3460                      Error_Msg_N
3461                        ("\?Program_Error will be raised at run time", N);
3462                      Insert_Action (N,
3463                        Make_Raise_Program_Error (Loc,
3464                          Reason => PE_Duplicated_Entry_Address));
3465                      exit;
3466                   end if;
3467
3468                   Next_Entity (E);
3469                end loop;
3470             end;
3471          end if;
3472       end if;
3473
3474       --  Some simple constant-propagation: if the expression is a constant
3475       --  string initialized with a literal, share the literal. This avoids
3476       --  a run-time copy.
3477
3478       if Present (E)
3479         and then Is_Entity_Name (E)
3480         and then Ekind (Entity (E)) = E_Constant
3481         and then Base_Type (Etype (E)) = Standard_String
3482       then
3483          declare
3484             Val : constant Node_Id := Constant_Value (Entity (E));
3485          begin
3486             if Present (Val)
3487               and then Nkind (Val) = N_String_Literal
3488             then
3489                Rewrite (E, New_Copy (Val));
3490             end if;
3491          end;
3492       end if;
3493
3494       --  Another optimization: if the nominal subtype is unconstrained and
3495       --  the expression is a function call that returns an unconstrained
3496       --  type, rewrite the declaration as a renaming of the result of the
3497       --  call. The exceptions below are cases where the copy is expected,
3498       --  either by the back end (Aliased case) or by the semantics, as for
3499       --  initializing controlled types or copying tags for classwide types.
3500
3501       if Present (E)
3502         and then Nkind (E) = N_Explicit_Dereference
3503         and then Nkind (Original_Node (E)) = N_Function_Call
3504         and then not Is_Library_Level_Entity (Id)
3505         and then not Is_Constrained (Underlying_Type (T))
3506         and then not Is_Aliased (Id)
3507         and then not Is_Class_Wide_Type (T)
3508         and then not Is_Controlled (T)
3509         and then not Has_Controlled_Component (Base_Type (T))
3510         and then Expander_Active
3511       then
3512          Rewrite (N,
3513            Make_Object_Renaming_Declaration (Loc,
3514              Defining_Identifier => Id,
3515              Access_Definition   => Empty,
3516              Subtype_Mark        => New_Occurrence_Of
3517                                       (Base_Type (Etype (Id)), Loc),
3518              Name                => E));
3519
3520          Set_Renamed_Object (Id, E);
3521
3522          --  Force generation of debugging information for the constant and for
3523          --  the renamed function call.
3524
3525          Set_Debug_Info_Needed (Id);
3526          Set_Debug_Info_Needed (Entity (Prefix (E)));
3527       end if;
3528
3529       if Present (Prev_Entity)
3530         and then Is_Frozen (Prev_Entity)
3531         and then not Error_Posted (Id)
3532       then
3533          Error_Msg_N ("full constant declaration appears too late", N);
3534       end if;
3535
3536       Check_Eliminated (Id);
3537
3538       --  Deal with setting In_Private_Part flag if in private part
3539
3540       if Ekind (Scope (Id)) = E_Package
3541         and then In_Private_Part (Scope (Id))
3542       then
3543          Set_In_Private_Part (Id);
3544       end if;
3545
3546       --  Check for violation of No_Local_Timing_Events
3547
3548       if Is_RTE (Etype (Id), RE_Timing_Event)
3549         and then not Is_Library_Level_Entity (Id)
3550       then
3551          Check_Restriction (No_Local_Timing_Events, N);
3552       end if;
3553
3554       <<Leave>>
3555          Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
3556    end Analyze_Object_Declaration;
3557
3558    ---------------------------
3559    -- Analyze_Others_Choice --
3560    ---------------------------
3561
3562    --  Nothing to do for the others choice node itself, the semantic analysis
3563    --  of the others choice will occur as part of the processing of the parent
3564
3565    procedure Analyze_Others_Choice (N : Node_Id) is
3566       pragma Warnings (Off, N);
3567    begin
3568       null;
3569    end Analyze_Others_Choice;
3570
3571    -------------------------------------------
3572    -- Analyze_Private_Extension_Declaration --
3573    -------------------------------------------
3574
3575    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3576       T           : constant Entity_Id := Defining_Identifier (N);
3577       Indic       : constant Node_Id   := Subtype_Indication (N);
3578       Parent_Type : Entity_Id;
3579       Parent_Base : Entity_Id;
3580
3581    begin
3582       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3583
3584       if Is_Non_Empty_List (Interface_List (N)) then
3585          declare
3586             Intf : Node_Id;
3587             T    : Entity_Id;
3588
3589          begin
3590             Intf := First (Interface_List (N));
3591             while Present (Intf) loop
3592                T := Find_Type_Of_Subtype_Indic (Intf);
3593
3594                Diagnose_Interface (Intf, T);
3595                Next (Intf);
3596             end loop;
3597          end;
3598       end if;
3599
3600       Generate_Definition (T);
3601
3602       --  For other than Ada 2012, just enter the name in the current scope
3603
3604       if Ada_Version < Ada_2012 then
3605          Enter_Name (T);
3606
3607       --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
3608       --  case of private type that completes an incomplete type.
3609
3610       else
3611          declare
3612             Prev : Entity_Id;
3613
3614          begin
3615             Prev := Find_Type_Name (N);
3616
3617             pragma Assert (Prev = T
3618               or else (Ekind (Prev) = E_Incomplete_Type
3619                          and then Present (Full_View (Prev))
3620                          and then Full_View (Prev) = T));
3621          end;
3622       end if;
3623
3624       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3625       Parent_Base := Base_Type (Parent_Type);
3626
3627       if Parent_Type = Any_Type
3628         or else Etype (Parent_Type) = Any_Type
3629       then
3630          Set_Ekind (T, Ekind (Parent_Type));
3631          Set_Etype (T, Any_Type);
3632          goto Leave;
3633
3634       elsif not Is_Tagged_Type (Parent_Type) then
3635          Error_Msg_N
3636            ("parent of type extension must be a tagged type ", Indic);
3637          goto Leave;
3638
3639       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3640          Error_Msg_N ("premature derivation of incomplete type", Indic);
3641          goto Leave;
3642
3643       elsif Is_Concurrent_Type (Parent_Type) then
3644          Error_Msg_N
3645            ("parent type of a private extension cannot be "
3646             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3647
3648          Set_Etype              (T, Any_Type);
3649          Set_Ekind              (T, E_Limited_Private_Type);
3650          Set_Private_Dependents (T, New_Elmt_List);
3651          Set_Error_Posted       (T);
3652          goto Leave;
3653       end if;
3654
3655       --  Perhaps the parent type should be changed to the class-wide type's
3656       --  specific type in this case to prevent cascading errors ???
3657
3658       if Is_Class_Wide_Type (Parent_Type) then
3659          Error_Msg_N
3660            ("parent of type extension must not be a class-wide type", Indic);
3661          goto Leave;
3662       end if;
3663
3664       if (not Is_Package_Or_Generic_Package (Current_Scope)
3665            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3666         or else In_Private_Part (Current_Scope)
3667
3668       then
3669          Error_Msg_N ("invalid context for private extension", N);
3670       end if;
3671
3672       --  Set common attributes
3673
3674       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3675       Set_Scope            (T, Current_Scope);
3676       Set_Ekind            (T, E_Record_Type_With_Private);
3677       Init_Size_Align      (T);
3678
3679       Set_Etype            (T,            Parent_Base);
3680       Set_Has_Task         (T, Has_Task  (Parent_Base));
3681
3682       Set_Convention       (T, Convention     (Parent_Type));
3683       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3684       Set_Is_First_Subtype (T);
3685       Make_Class_Wide_Type (T);
3686
3687       if Unknown_Discriminants_Present (N) then
3688          Set_Discriminant_Constraint (T, No_Elist);
3689       end if;
3690
3691       Build_Derived_Record_Type (N, Parent_Type, T);
3692
3693       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3694       --  synchronized formal derived type.
3695
3696       if Ada_Version >= Ada_2005
3697         and then Synchronized_Present (N)
3698       then
3699          Set_Is_Limited_Record (T);
3700
3701          --  Formal derived type case
3702
3703          if Is_Generic_Type (T) then
3704
3705             --  The parent must be a tagged limited type or a synchronized
3706             --  interface.
3707
3708             if (not Is_Tagged_Type (Parent_Type)
3709                   or else not Is_Limited_Type (Parent_Type))
3710               and then
3711                (not Is_Interface (Parent_Type)
3712                   or else not Is_Synchronized_Interface (Parent_Type))
3713             then
3714                Error_Msg_NE ("parent type of & must be tagged limited " &
3715                              "or synchronized", N, T);
3716             end if;
3717
3718             --  The progenitors (if any) must be limited or synchronized
3719             --  interfaces.
3720
3721             if Present (Interfaces (T)) then
3722                declare
3723                   Iface      : Entity_Id;
3724                   Iface_Elmt : Elmt_Id;
3725
3726                begin
3727                   Iface_Elmt := First_Elmt (Interfaces (T));
3728                   while Present (Iface_Elmt) loop
3729                      Iface := Node (Iface_Elmt);
3730
3731                      if not Is_Limited_Interface (Iface)
3732                        and then not Is_Synchronized_Interface (Iface)
3733                      then
3734                         Error_Msg_NE ("progenitor & must be limited " &
3735                                       "or synchronized", N, Iface);
3736                      end if;
3737
3738                      Next_Elmt (Iface_Elmt);
3739                   end loop;
3740                end;
3741             end if;
3742
3743          --  Regular derived extension, the parent must be a limited or
3744          --  synchronized interface.
3745
3746          else
3747             if not Is_Interface (Parent_Type)
3748               or else (not Is_Limited_Interface (Parent_Type)
3749                          and then
3750                        not Is_Synchronized_Interface (Parent_Type))
3751             then
3752                Error_Msg_NE
3753                  ("parent type of & must be limited interface", N, T);
3754             end if;
3755          end if;
3756
3757       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
3758       --  extension with a synchronized parent must be explicitly declared
3759       --  synchronized, because the full view will be a synchronized type.
3760       --  This must be checked before the check for limited types below,
3761       --  to ensure that types declared limited are not allowed to extend
3762       --  synchronized interfaces.
3763
3764       elsif Is_Interface (Parent_Type)
3765         and then Is_Synchronized_Interface (Parent_Type)
3766         and then not Synchronized_Present (N)
3767       then
3768          Error_Msg_NE
3769            ("private extension of& must be explicitly synchronized",
3770              N, Parent_Type);
3771
3772       elsif Limited_Present (N) then
3773          Set_Is_Limited_Record (T);
3774
3775          if not Is_Limited_Type (Parent_Type)
3776            and then
3777              (not Is_Interface (Parent_Type)
3778                or else not Is_Limited_Interface (Parent_Type))
3779          then
3780             Error_Msg_NE ("parent type& of limited extension must be limited",
3781               N, Parent_Type);
3782          end if;
3783       end if;
3784
3785       <<Leave>>
3786          Analyze_Aspect_Specifications (N, T, Aspect_Specifications (N));
3787    end Analyze_Private_Extension_Declaration;
3788
3789    ---------------------------------
3790    -- Analyze_Subtype_Declaration --
3791    ---------------------------------
3792
3793    procedure Analyze_Subtype_Declaration
3794      (N    : Node_Id;
3795       Skip : Boolean := False)
3796    is
3797       Id       : constant Entity_Id := Defining_Identifier (N);
3798       T        : Entity_Id;
3799       R_Checks : Check_Result;
3800
3801    begin
3802       Generate_Definition (Id);
3803       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3804       Init_Size_Align (Id);
3805
3806       --  The following guard condition on Enter_Name is to handle cases where
3807       --  the defining identifier has already been entered into the scope but
3808       --  the declaration as a whole needs to be analyzed.
3809
3810       --  This case in particular happens for derived enumeration types. The
3811       --  derived enumeration type is processed as an inserted enumeration type
3812       --  declaration followed by a rewritten subtype declaration. The defining
3813       --  identifier, however, is entered into the name scope very early in the
3814       --  processing of the original type declaration and therefore needs to be
3815       --  avoided here, when the created subtype declaration is analyzed. (See
3816       --  Build_Derived_Types)
3817
3818       --  This also happens when the full view of a private type is derived
3819       --  type with constraints. In this case the entity has been introduced
3820       --  in the private declaration.
3821
3822       if Skip
3823         or else (Present (Etype (Id))
3824                    and then (Is_Private_Type (Etype (Id))
3825                                or else Is_Task_Type (Etype (Id))
3826                                or else Is_Rewrite_Substitution (N)))
3827       then
3828          null;
3829
3830       else
3831          Enter_Name (Id);
3832       end if;
3833
3834       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
3835
3836       --  Inherit common attributes
3837
3838       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
3839       Set_Is_Volatile       (Id, Is_Volatile       (T));
3840       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
3841       Set_Is_Atomic         (Id, Is_Atomic         (T));
3842       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
3843       Set_Is_Ada_2012_Only  (Id, Is_Ada_2012_Only  (T));
3844       Set_Convention        (Id, Convention        (T));
3845       Set_Has_Predicates    (Id, Has_Predicates    (T));
3846
3847       --  In the case where there is no constraint given in the subtype
3848       --  indication, Process_Subtype just returns the Subtype_Mark, so its
3849       --  semantic attributes must be established here.
3850
3851       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
3852          Set_Etype (Id, Base_Type (T));
3853
3854          case Ekind (T) is
3855             when Array_Kind =>
3856                Set_Ekind                       (Id, E_Array_Subtype);
3857                Copy_Array_Subtype_Attributes   (Id, T);
3858
3859             when Decimal_Fixed_Point_Kind =>
3860                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
3861                Set_Digits_Value         (Id, Digits_Value       (T));
3862                Set_Delta_Value          (Id, Delta_Value        (T));
3863                Set_Scale_Value          (Id, Scale_Value        (T));
3864                Set_Small_Value          (Id, Small_Value        (T));
3865                Set_Scalar_Range         (Id, Scalar_Range       (T));
3866                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
3867                Set_Is_Constrained       (Id, Is_Constrained     (T));
3868                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3869                Set_RM_Size              (Id, RM_Size            (T));
3870
3871             when Enumeration_Kind =>
3872                Set_Ekind                (Id, E_Enumeration_Subtype);
3873                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
3874                Set_Scalar_Range         (Id, Scalar_Range       (T));
3875                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
3876                Set_Is_Constrained       (Id, Is_Constrained     (T));
3877                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3878                Set_RM_Size              (Id, RM_Size            (T));
3879
3880             when Ordinary_Fixed_Point_Kind =>
3881                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
3882                Set_Scalar_Range         (Id, Scalar_Range       (T));
3883                Set_Small_Value          (Id, Small_Value        (T));
3884                Set_Delta_Value          (Id, Delta_Value        (T));
3885                Set_Is_Constrained       (Id, Is_Constrained     (T));
3886                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3887                Set_RM_Size              (Id, RM_Size            (T));
3888
3889             when Float_Kind =>
3890                Set_Ekind                (Id, E_Floating_Point_Subtype);
3891                Set_Scalar_Range         (Id, Scalar_Range       (T));
3892                Set_Digits_Value         (Id, Digits_Value       (T));
3893                Set_Is_Constrained       (Id, Is_Constrained     (T));
3894
3895             when Signed_Integer_Kind =>
3896                Set_Ekind                (Id, E_Signed_Integer_Subtype);
3897                Set_Scalar_Range         (Id, Scalar_Range       (T));
3898                Set_Is_Constrained       (Id, Is_Constrained     (T));
3899                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3900                Set_RM_Size              (Id, RM_Size            (T));
3901
3902             when Modular_Integer_Kind =>
3903                Set_Ekind                (Id, E_Modular_Integer_Subtype);
3904                Set_Scalar_Range         (Id, Scalar_Range       (T));
3905                Set_Is_Constrained       (Id, Is_Constrained     (T));
3906                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3907                Set_RM_Size              (Id, RM_Size            (T));
3908
3909             when Class_Wide_Kind =>
3910                Set_Ekind                (Id, E_Class_Wide_Subtype);
3911                Set_First_Entity         (Id, First_Entity       (T));
3912                Set_Last_Entity          (Id, Last_Entity        (T));
3913                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
3914                Set_Cloned_Subtype       (Id, T);
3915                Set_Is_Tagged_Type       (Id, True);
3916                Set_Has_Unknown_Discriminants
3917                                         (Id, True);
3918
3919                if Ekind (T) = E_Class_Wide_Subtype then
3920                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
3921                end if;
3922
3923             when E_Record_Type | E_Record_Subtype =>
3924                Set_Ekind                (Id, E_Record_Subtype);
3925
3926                if Ekind (T) = E_Record_Subtype
3927                  and then Present (Cloned_Subtype (T))
3928                then
3929                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
3930                else
3931                   Set_Cloned_Subtype    (Id, T);
3932                end if;
3933
3934                Set_First_Entity         (Id, First_Entity       (T));
3935                Set_Last_Entity          (Id, Last_Entity        (T));
3936                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
3937                Set_Is_Constrained       (Id, Is_Constrained     (T));
3938                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
3939                Set_Has_Unknown_Discriminants
3940                                         (Id, Has_Unknown_Discriminants (T));
3941
3942                if Has_Discriminants (T) then
3943                   Set_Discriminant_Constraint
3944                                         (Id, Discriminant_Constraint (T));
3945                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3946
3947                elsif Has_Unknown_Discriminants (Id) then
3948                   Set_Discriminant_Constraint (Id, No_Elist);
3949                end if;
3950
3951                if Is_Tagged_Type (T) then
3952                   Set_Is_Tagged_Type    (Id);
3953                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
3954                   Set_Direct_Primitive_Operations
3955                                         (Id, Direct_Primitive_Operations (T));
3956                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
3957
3958                   if Is_Interface (T) then
3959                      Set_Is_Interface (Id);
3960                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
3961                   end if;
3962                end if;
3963
3964             when Private_Kind =>
3965                Set_Ekind              (Id, Subtype_Kind (Ekind   (T)));
3966                Set_Has_Discriminants  (Id, Has_Discriminants     (T));
3967                Set_Is_Constrained     (Id, Is_Constrained        (T));
3968                Set_First_Entity       (Id, First_Entity          (T));
3969                Set_Last_Entity        (Id, Last_Entity           (T));
3970                Set_Private_Dependents (Id, New_Elmt_List);
3971                Set_Is_Limited_Record  (Id, Is_Limited_Record     (T));
3972                Set_Has_Unknown_Discriminants
3973                                       (Id, Has_Unknown_Discriminants (T));
3974                Set_Known_To_Have_Preelab_Init
3975                                       (Id, Known_To_Have_Preelab_Init (T));
3976
3977                if Is_Tagged_Type (T) then
3978                   Set_Is_Tagged_Type              (Id);
3979                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
3980                   Set_Class_Wide_Type             (Id, Class_Wide_Type (T));
3981                   Set_Direct_Primitive_Operations (Id,
3982                     Direct_Primitive_Operations (T));
3983                end if;
3984
3985                --  In general the attributes of the subtype of a private type
3986                --  are the attributes of the partial view of parent. However,
3987                --  the full view may be a discriminated type, and the subtype
3988                --  must share the discriminant constraint to generate correct
3989                --  calls to initialization procedures.
3990
3991                if Has_Discriminants (T) then
3992                   Set_Discriminant_Constraint
3993                                      (Id, Discriminant_Constraint (T));
3994                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3995
3996                elsif Present (Full_View (T))
3997                  and then Has_Discriminants (Full_View (T))
3998                then
3999                   Set_Discriminant_Constraint
4000                                (Id, Discriminant_Constraint (Full_View (T)));
4001                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4002
4003                   --  This would seem semantically correct, but apparently
4004                   --  confuses the back-end. To be explained and checked with
4005                   --  current version ???
4006
4007                   --  Set_Has_Discriminants (Id);
4008                end if;
4009
4010                Prepare_Private_Subtype_Completion (Id, N);
4011
4012             when Access_Kind =>
4013                Set_Ekind             (Id, E_Access_Subtype);
4014                Set_Is_Constrained    (Id, Is_Constrained        (T));
4015                Set_Is_Access_Constant
4016                                      (Id, Is_Access_Constant    (T));
4017                Set_Directly_Designated_Type
4018                                      (Id, Designated_Type       (T));
4019                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4020
4021                --  A Pure library_item must not contain the declaration of a
4022                --  named access type, except within a subprogram, generic
4023                --  subprogram, task unit, or protected unit, or if it has
4024                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4025
4026                if Comes_From_Source (Id)
4027                  and then In_Pure_Unit
4028                  and then not In_Subprogram_Task_Protected_Unit
4029                  and then not No_Pool_Assigned (Id)
4030                then
4031                   Error_Msg_N
4032                     ("named access types not allowed in pure unit", N);
4033                end if;
4034
4035             when Concurrent_Kind =>
4036                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4037                Set_Corresponding_Record_Type (Id,
4038                                          Corresponding_Record_Type (T));
4039                Set_First_Entity         (Id, First_Entity          (T));
4040                Set_First_Private_Entity (Id, First_Private_Entity  (T));
4041                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4042                Set_Is_Constrained       (Id, Is_Constrained        (T));
4043                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4044                Set_Last_Entity          (Id, Last_Entity           (T));
4045
4046                if Has_Discriminants (T) then
4047                   Set_Discriminant_Constraint (Id,
4048                                            Discriminant_Constraint (T));
4049                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4050                end if;
4051
4052             when E_Incomplete_Type =>
4053                if Ada_Version >= Ada_2005 then
4054                   Set_Ekind (Id, E_Incomplete_Subtype);
4055
4056                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
4057                   --  of an incomplete type visible through a limited
4058                   --  with clause.
4059
4060                   if From_With_Type (T)
4061                     and then Present (Non_Limited_View (T))
4062                   then
4063                      Set_From_With_Type   (Id);
4064                      Set_Non_Limited_View (Id, Non_Limited_View (T));
4065
4066                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
4067                   --  to the private dependents of the original incomplete
4068                   --  type for future transformation.
4069
4070                   else
4071                      Append_Elmt (Id, Private_Dependents (T));
4072                   end if;
4073
4074                --  If the subtype name denotes an incomplete type an error
4075                --  was already reported by Process_Subtype.
4076
4077                else
4078                   Set_Etype (Id, Any_Type);
4079                end if;
4080
4081             when others =>
4082                raise Program_Error;
4083          end case;
4084       end if;
4085
4086       if Etype (Id) = Any_Type then
4087          goto Leave;
4088       end if;
4089
4090       --  Some common processing on all types
4091
4092       Set_Size_Info      (Id,                 T);
4093       Set_First_Rep_Item (Id, First_Rep_Item (T));
4094
4095       T := Etype (Id);
4096
4097       Set_Is_Immediately_Visible   (Id, True);
4098       Set_Depends_On_Private       (Id, Has_Private_Component (T));
4099       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
4100
4101       if Is_Interface (T) then
4102          Set_Is_Interface (Id);
4103       end if;
4104
4105       if Present (Generic_Parent_Type (N))
4106         and then
4107           (Nkind
4108             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
4109             or else Nkind
4110               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
4111                 /= N_Formal_Private_Type_Definition)
4112       then
4113          if Is_Tagged_Type (Id) then
4114
4115             --  If this is a generic actual subtype for a synchronized type,
4116             --  the primitive operations are those of the corresponding record
4117             --  for which there is a separate subtype declaration.
4118
4119             if Is_Concurrent_Type (Id) then
4120                null;
4121             elsif Is_Class_Wide_Type (Id) then
4122                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
4123             else
4124                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
4125             end if;
4126
4127          elsif Scope (Etype (Id)) /= Standard_Standard then
4128             Derive_Subprograms (Generic_Parent_Type (N), Id);
4129          end if;
4130       end if;
4131
4132       if Is_Private_Type (T)
4133         and then Present (Full_View (T))
4134       then
4135          Conditional_Delay (Id, Full_View (T));
4136
4137       --  The subtypes of components or subcomponents of protected types
4138       --  do not need freeze nodes, which would otherwise appear in the
4139       --  wrong scope (before the freeze node for the protected type). The
4140       --  proper subtypes are those of the subcomponents of the corresponding
4141       --  record.
4142
4143       elsif Ekind (Scope (Id)) /= E_Protected_Type
4144         and then Present (Scope (Scope (Id))) -- error defense!
4145         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
4146       then
4147          Conditional_Delay (Id, T);
4148       end if;
4149
4150       --  Check that constraint_error is raised for a scalar subtype
4151       --  indication when the lower or upper bound of a non-null range
4152       --  lies outside the range of the type mark.
4153
4154       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4155          if Is_Scalar_Type (Etype (Id))
4156             and then Scalar_Range (Id) /=
4157                      Scalar_Range (Etype (Subtype_Mark
4158                                            (Subtype_Indication (N))))
4159          then
4160             Apply_Range_Check
4161               (Scalar_Range (Id),
4162                Etype (Subtype_Mark (Subtype_Indication (N))));
4163
4164          elsif Is_Array_Type (Etype (Id))
4165            and then Present (First_Index (Id))
4166          then
4167             --  This really should be a subprogram that finds the indications
4168             --  to check???
4169
4170             if ((Nkind (First_Index (Id)) = N_Identifier
4171                    and then Ekind (Entity (First_Index (Id))) in Scalar_Kind)
4172                  or else Nkind (First_Index (Id)) = N_Subtype_Indication)
4173               and then
4174                 Nkind (Scalar_Range (Etype (First_Index (Id)))) = N_Range
4175             then
4176                declare
4177                   Target_Typ : constant Entity_Id :=
4178                                  Etype
4179                                    (First_Index (Etype
4180                                      (Subtype_Mark (Subtype_Indication (N)))));
4181                begin
4182                   R_Checks :=
4183                     Get_Range_Checks
4184                       (Scalar_Range (Etype (First_Index (Id))),
4185                        Target_Typ,
4186                        Etype (First_Index (Id)),
4187                        Defining_Identifier (N));
4188
4189                   Insert_Range_Checks
4190                     (R_Checks,
4191                      N,
4192                      Target_Typ,
4193                      Sloc (Defining_Identifier (N)));
4194                end;
4195             end if;
4196          end if;
4197       end if;
4198
4199       --  Make sure that generic actual types are properly frozen. The subtype
4200       --  is marked as a generic actual type when the enclosing instance is
4201       --  analyzed, so here we identify the subtype from the tree structure.
4202
4203       if Expander_Active
4204         and then Is_Generic_Actual_Type (Id)
4205         and then In_Instance
4206         and then not Comes_From_Source (N)
4207         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
4208         and then Is_Frozen (T)
4209       then
4210          Freeze_Before (N, Id);
4211       end if;
4212
4213       Set_Optimize_Alignment_Flags (Id);
4214       Check_Eliminated (Id);
4215
4216       <<Leave>>
4217          Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
4218    end Analyze_Subtype_Declaration;
4219
4220    --------------------------------
4221    -- Analyze_Subtype_Indication --
4222    --------------------------------
4223
4224    procedure Analyze_Subtype_Indication (N : Node_Id) is
4225       T : constant Entity_Id := Subtype_Mark (N);
4226       R : constant Node_Id   := Range_Expression (Constraint (N));
4227
4228    begin
4229       Analyze (T);
4230
4231       if R /= Error then
4232          Analyze (R);
4233          Set_Etype (N, Etype (R));
4234          Resolve (R, Entity (T));
4235       else
4236          Set_Error_Posted (R);
4237          Set_Error_Posted (T);
4238       end if;
4239    end Analyze_Subtype_Indication;
4240
4241    --------------------------
4242    -- Analyze_Variant_Part --
4243    --------------------------
4244
4245    procedure Analyze_Variant_Part (N : Node_Id) is
4246
4247       procedure Non_Static_Choice_Error (Choice : Node_Id);
4248       --  Error routine invoked by the generic instantiation below when the
4249       --  variant part has a non static choice.
4250
4251       procedure Process_Declarations (Variant : Node_Id);
4252       --  Analyzes all the declarations associated with a Variant. Needed by
4253       --  the generic instantiation below.
4254
4255       package Variant_Choices_Processing is new
4256         Generic_Choices_Processing
4257           (Get_Alternatives          => Variants,
4258            Get_Choices               => Discrete_Choices,
4259            Process_Empty_Choice      => No_OP,
4260            Process_Non_Static_Choice => Non_Static_Choice_Error,
4261            Process_Associated_Node   => Process_Declarations);
4262       use Variant_Choices_Processing;
4263       --  Instantiation of the generic choice processing package
4264
4265       -----------------------------
4266       -- Non_Static_Choice_Error --
4267       -----------------------------
4268
4269       procedure Non_Static_Choice_Error (Choice : Node_Id) is
4270       begin
4271          Flag_Non_Static_Expr
4272            ("choice given in variant part is not static!", Choice);
4273       end Non_Static_Choice_Error;
4274
4275       --------------------------
4276       -- Process_Declarations --
4277       --------------------------
4278
4279       procedure Process_Declarations (Variant : Node_Id) is
4280       begin
4281          if not Null_Present (Component_List (Variant)) then
4282             Analyze_Declarations (Component_Items (Component_List (Variant)));
4283
4284             if Present (Variant_Part (Component_List (Variant))) then
4285                Analyze (Variant_Part (Component_List (Variant)));
4286             end if;
4287          end if;
4288       end Process_Declarations;
4289
4290       --  Local Variables
4291
4292       Discr_Name : Node_Id;
4293       Discr_Type : Entity_Id;
4294
4295       Case_Table     : Choice_Table_Type (1 .. Number_Of_Choices (N));
4296       Last_Choice    : Nat;
4297       Dont_Care      : Boolean;
4298       Others_Present : Boolean := False;
4299
4300       pragma Warnings (Off, Case_Table);
4301       pragma Warnings (Off, Last_Choice);
4302       pragma Warnings (Off, Dont_Care);
4303       pragma Warnings (Off, Others_Present);
4304       --  We don't care about the assigned values of any of these
4305
4306    --  Start of processing for Analyze_Variant_Part
4307
4308    begin
4309       Discr_Name := Name (N);
4310       Analyze (Discr_Name);
4311
4312       --  If Discr_Name bad, get out (prevent cascaded errors)
4313
4314       if Etype (Discr_Name) = Any_Type then
4315          return;
4316       end if;
4317
4318       --  Check invalid discriminant in variant part
4319
4320       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4321          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4322       end if;
4323
4324       Discr_Type := Etype (Entity (Discr_Name));
4325
4326       if not Is_Discrete_Type (Discr_Type) then
4327          Error_Msg_N
4328            ("discriminant in a variant part must be of a discrete type",
4329              Name (N));
4330          return;
4331       end if;
4332
4333       --  Call the instantiated Analyze_Choices which does the rest of the work
4334
4335       Analyze_Choices
4336         (N, Discr_Type, Case_Table, Last_Choice, Dont_Care, Others_Present);
4337    end Analyze_Variant_Part;
4338
4339    ----------------------------
4340    -- Array_Type_Declaration --
4341    ----------------------------
4342
4343    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4344       Component_Def : constant Node_Id := Component_Definition (Def);
4345       Element_Type  : Entity_Id;
4346       Implicit_Base : Entity_Id;
4347       Index         : Node_Id;
4348       Related_Id    : Entity_Id := Empty;
4349       Nb_Index      : Nat;
4350       P             : constant Node_Id := Parent (Def);
4351       Priv          : Entity_Id;
4352
4353    begin
4354       if Nkind (Def) = N_Constrained_Array_Definition then
4355          Index := First (Discrete_Subtype_Definitions (Def));
4356       else
4357          Index := First (Subtype_Marks (Def));
4358       end if;
4359
4360       --  Find proper names for the implicit types which may be public. In case
4361       --  of anonymous arrays we use the name of the first object of that type
4362       --  as prefix.
4363
4364       if No (T) then
4365          Related_Id :=  Defining_Identifier (P);
4366       else
4367          Related_Id := T;
4368       end if;
4369
4370       Nb_Index := 1;
4371       while Present (Index) loop
4372          Analyze (Index);
4373
4374          --  Add a subtype declaration for each index of private array type
4375          --  declaration whose etype is also private. For example:
4376
4377          --     package Pkg is
4378          --        type Index is private;
4379          --     private
4380          --        type Table is array (Index) of ...
4381          --     end;
4382
4383          --  This is currently required by the expander for the internally
4384          --  generated equality subprogram of records with variant parts in
4385          --  which the etype of some component is such private type.
4386
4387          if Ekind (Current_Scope) = E_Package
4388            and then In_Private_Part (Current_Scope)
4389            and then Has_Private_Declaration (Etype (Index))
4390          then
4391             declare
4392                Loc   : constant Source_Ptr := Sloc (Def);
4393                New_E : Entity_Id;
4394                Decl  : Entity_Id;
4395
4396             begin
4397                New_E := Make_Temporary (Loc, 'T');
4398                Set_Is_Internal (New_E);
4399
4400                Decl :=
4401                  Make_Subtype_Declaration (Loc,
4402                    Defining_Identifier => New_E,
4403                    Subtype_Indication  =>
4404                      New_Occurrence_Of (Etype (Index), Loc));
4405
4406                Insert_Before (Parent (Def), Decl);
4407                Analyze (Decl);
4408                Set_Etype (Index, New_E);
4409
4410                --  If the index is a range the Entity attribute is not
4411                --  available. Example:
4412
4413                --     package Pkg is
4414                --        type T is private;
4415                --     private
4416                --        type T is new Natural;
4417                --        Table : array (T(1) .. T(10)) of Boolean;
4418                --     end Pkg;
4419
4420                if Nkind (Index) /= N_Range then
4421                   Set_Entity (Index, New_E);
4422                end if;
4423             end;
4424          end if;
4425
4426          Make_Index (Index, P, Related_Id, Nb_Index);
4427          Next_Index (Index);
4428          Nb_Index := Nb_Index + 1;
4429       end loop;
4430
4431       --  Process subtype indication if one is present
4432
4433       if Present (Subtype_Indication (Component_Def)) then
4434          Element_Type :=
4435            Process_Subtype
4436              (Subtype_Indication (Component_Def), P, Related_Id, 'C');
4437
4438       --  Ada 2005 (AI-230): Access Definition case
4439
4440       else pragma Assert (Present (Access_Definition (Component_Def)));
4441
4442          --  Indicate that the anonymous access type is created by the
4443          --  array type declaration.
4444
4445          Element_Type := Access_Definition
4446                            (Related_Nod => P,
4447                             N           => Access_Definition (Component_Def));
4448          Set_Is_Local_Anonymous_Access (Element_Type);
4449
4450          --  Propagate the parent. This field is needed if we have to generate
4451          --  the master_id associated with an anonymous access to task type
4452          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4453
4454          Set_Parent (Element_Type, Parent (T));
4455
4456          --  Ada 2005 (AI-230): In case of components that are anonymous access
4457          --  types the level of accessibility depends on the enclosing type
4458          --  declaration
4459
4460          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4461
4462          --  Ada 2005 (AI-254)
4463
4464          declare
4465             CD : constant Node_Id :=
4466                    Access_To_Subprogram_Definition
4467                      (Access_Definition (Component_Def));
4468          begin
4469             if Present (CD) and then Protected_Present (CD) then
4470                Element_Type :=
4471                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4472             end if;
4473          end;
4474       end if;
4475
4476       --  Constrained array case
4477
4478       if No (T) then
4479          T := Create_Itype (E_Void, P, Related_Id, 'T');
4480       end if;
4481
4482       if Nkind (Def) = N_Constrained_Array_Definition then
4483
4484          --  Establish Implicit_Base as unconstrained base type
4485
4486          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4487
4488          Set_Etype              (Implicit_Base, Implicit_Base);
4489          Set_Scope              (Implicit_Base, Current_Scope);
4490          Set_Has_Delayed_Freeze (Implicit_Base);
4491
4492          --  The constrained array type is a subtype of the unconstrained one
4493
4494          Set_Ekind          (T, E_Array_Subtype);
4495          Init_Size_Align    (T);
4496          Set_Etype          (T, Implicit_Base);
4497          Set_Scope          (T, Current_Scope);
4498          Set_Is_Constrained (T, True);
4499          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4500          Set_Has_Delayed_Freeze (T);
4501
4502          --  Complete setup of implicit base type
4503
4504          Set_First_Index       (Implicit_Base, First_Index (T));
4505          Set_Component_Type    (Implicit_Base, Element_Type);
4506          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4507          Set_Component_Size    (Implicit_Base, Uint_0);
4508          Set_Packed_Array_Type (Implicit_Base, Empty);
4509          Set_Has_Controlled_Component
4510                                (Implicit_Base, Has_Controlled_Component
4511                                                         (Element_Type)
4512                                                  or else Is_Controlled
4513                                                         (Element_Type));
4514          Set_Finalize_Storage_Only
4515                                (Implicit_Base, Finalize_Storage_Only
4516                                                         (Element_Type));
4517
4518       --  Unconstrained array case
4519
4520       else
4521          Set_Ekind                    (T, E_Array_Type);
4522          Init_Size_Align              (T);
4523          Set_Etype                    (T, T);
4524          Set_Scope                    (T, Current_Scope);
4525          Set_Component_Size           (T, Uint_0);
4526          Set_Is_Constrained           (T, False);
4527          Set_First_Index              (T, First (Subtype_Marks (Def)));
4528          Set_Has_Delayed_Freeze       (T, True);
4529          Set_Has_Task                 (T, Has_Task      (Element_Type));
4530          Set_Has_Controlled_Component (T, Has_Controlled_Component
4531                                                         (Element_Type)
4532                                             or else
4533                                           Is_Controlled (Element_Type));
4534          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4535                                                         (Element_Type));
4536       end if;
4537
4538       --  Common attributes for both cases
4539
4540       Set_Component_Type (Base_Type (T), Element_Type);
4541       Set_Packed_Array_Type (T, Empty);
4542
4543       if Aliased_Present (Component_Definition (Def)) then
4544          Set_Has_Aliased_Components (Etype (T));
4545       end if;
4546
4547       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4548       --  array type to ensure that objects of this type are initialized.
4549
4550       if Ada_Version >= Ada_2005
4551         and then Can_Never_Be_Null (Element_Type)
4552       then
4553          Set_Can_Never_Be_Null (T);
4554
4555          if Null_Exclusion_Present (Component_Definition (Def))
4556
4557             --  No need to check itypes because in their case this check was
4558             --  done at their point of creation
4559
4560            and then not Is_Itype (Element_Type)
4561          then
4562             Error_Msg_N
4563               ("`NOT NULL` not allowed (null already excluded)",
4564                Subtype_Indication (Component_Definition (Def)));
4565          end if;
4566       end if;
4567
4568       Priv := Private_Component (Element_Type);
4569
4570       if Present (Priv) then
4571
4572          --  Check for circular definitions
4573
4574          if Priv = Any_Type then
4575             Set_Component_Type (Etype (T), Any_Type);
4576
4577          --  There is a gap in the visibility of operations on the composite
4578          --  type only if the component type is defined in a different scope.
4579
4580          elsif Scope (Priv) = Current_Scope then
4581             null;
4582
4583          elsif Is_Limited_Type (Priv) then
4584             Set_Is_Limited_Composite (Etype (T));
4585             Set_Is_Limited_Composite (T);
4586          else
4587             Set_Is_Private_Composite (Etype (T));
4588             Set_Is_Private_Composite (T);
4589          end if;
4590       end if;
4591
4592       --  A syntax error in the declaration itself may lead to an empty index
4593       --  list, in which case do a minimal patch.
4594
4595       if No (First_Index (T)) then
4596          Error_Msg_N ("missing index definition in array type declaration", T);
4597
4598          declare
4599             Indexes : constant List_Id :=
4600                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4601          begin
4602             Set_Discrete_Subtype_Definitions (Def, Indexes);
4603             Set_First_Index (T, First (Indexes));
4604             return;
4605          end;
4606       end if;
4607
4608       --  Create a concatenation operator for the new type. Internal array
4609       --  types created for packed entities do not need such, they are
4610       --  compatible with the user-defined type.
4611
4612       if Number_Dimensions (T) = 1
4613          and then not Is_Packed_Array_Type (T)
4614       then
4615          New_Concatenation_Op (T);
4616       end if;
4617
4618       --  In the case of an unconstrained array the parser has already verified
4619       --  that all the indexes are unconstrained but we still need to make sure
4620       --  that the element type is constrained.
4621
4622       if Is_Indefinite_Subtype (Element_Type) then
4623          Error_Msg_N
4624            ("unconstrained element type in array declaration",
4625             Subtype_Indication (Component_Def));
4626
4627       elsif Is_Abstract_Type (Element_Type) then
4628          Error_Msg_N
4629            ("the type of a component cannot be abstract",
4630             Subtype_Indication (Component_Def));
4631       end if;
4632    end Array_Type_Declaration;
4633
4634    ------------------------------------------------------
4635    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4636    ------------------------------------------------------
4637
4638    function Replace_Anonymous_Access_To_Protected_Subprogram
4639      (N : Node_Id) return Entity_Id
4640    is
4641       Loc : constant Source_Ptr := Sloc (N);
4642
4643       Curr_Scope : constant Scope_Stack_Entry :=
4644                      Scope_Stack.Table (Scope_Stack.Last);
4645
4646       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
4647       Acc  : Node_Id;
4648       Comp : Node_Id;
4649       Decl : Node_Id;
4650       P    : Node_Id;
4651
4652    begin
4653       Set_Is_Internal (Anon);
4654
4655       case Nkind (N) is
4656          when N_Component_Declaration       |
4657            N_Unconstrained_Array_Definition |
4658            N_Constrained_Array_Definition   =>
4659             Comp := Component_Definition (N);
4660             Acc  := Access_Definition (Comp);
4661
4662          when N_Discriminant_Specification =>
4663             Comp := Discriminant_Type (N);
4664             Acc  := Comp;
4665
4666          when N_Parameter_Specification =>
4667             Comp := Parameter_Type (N);
4668             Acc  := Comp;
4669
4670          when N_Access_Function_Definition  =>
4671             Comp := Result_Definition (N);
4672             Acc  := Comp;
4673
4674          when N_Object_Declaration  =>
4675             Comp := Object_Definition (N);
4676             Acc  := Comp;
4677
4678          when N_Function_Specification =>
4679             Comp := Result_Definition (N);
4680             Acc  := Comp;
4681
4682          when others =>
4683             raise Program_Error;
4684       end case;
4685
4686       Decl := Make_Full_Type_Declaration (Loc,
4687                 Defining_Identifier => Anon,
4688                 Type_Definition   =>
4689                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
4690
4691       Mark_Rewrite_Insertion (Decl);
4692
4693       --  Insert the new declaration in the nearest enclosing scope. If the
4694       --  node is a body and N is its return type, the declaration belongs in
4695       --  the enclosing scope.
4696
4697       P := Parent (N);
4698
4699       if Nkind (P) = N_Subprogram_Body
4700         and then Nkind (N) = N_Function_Specification
4701       then
4702          P := Parent (P);
4703       end if;
4704
4705       while Present (P) and then not Has_Declarations (P) loop
4706          P := Parent (P);
4707       end loop;
4708
4709       pragma Assert (Present (P));
4710
4711       if Nkind (P) = N_Package_Specification then
4712          Prepend (Decl, Visible_Declarations (P));
4713       else
4714          Prepend (Decl, Declarations (P));
4715       end if;
4716
4717       --  Replace the anonymous type with an occurrence of the new declaration.
4718       --  In all cases the rewritten node does not have the null-exclusion
4719       --  attribute because (if present) it was already inherited by the
4720       --  anonymous entity (Anon). Thus, in case of components we do not
4721       --  inherit this attribute.
4722
4723       if Nkind (N) = N_Parameter_Specification then
4724          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4725          Set_Etype (Defining_Identifier (N), Anon);
4726          Set_Null_Exclusion_Present (N, False);
4727
4728       elsif Nkind (N) = N_Object_Declaration then
4729          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4730          Set_Etype (Defining_Identifier (N), Anon);
4731
4732       elsif Nkind (N) = N_Access_Function_Definition then
4733          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4734
4735       elsif Nkind (N) = N_Function_Specification then
4736          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4737          Set_Etype (Defining_Unit_Name (N), Anon);
4738
4739       else
4740          Rewrite (Comp,
4741            Make_Component_Definition (Loc,
4742              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
4743       end if;
4744
4745       Mark_Rewrite_Insertion (Comp);
4746
4747       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
4748          Analyze (Decl);
4749
4750       else
4751          --  Temporarily remove the current scope (record or subprogram) from
4752          --  the stack to add the new declarations to the enclosing scope.
4753
4754          Scope_Stack.Decrement_Last;
4755          Analyze (Decl);
4756          Set_Is_Itype (Anon);
4757          Scope_Stack.Append (Curr_Scope);
4758       end if;
4759
4760       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
4761       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
4762       return Anon;
4763    end Replace_Anonymous_Access_To_Protected_Subprogram;
4764
4765    -------------------------------
4766    -- Build_Derived_Access_Type --
4767    -------------------------------
4768
4769    procedure Build_Derived_Access_Type
4770      (N            : Node_Id;
4771       Parent_Type  : Entity_Id;
4772       Derived_Type : Entity_Id)
4773    is
4774       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
4775
4776       Desig_Type      : Entity_Id;
4777       Discr           : Entity_Id;
4778       Discr_Con_Elist : Elist_Id;
4779       Discr_Con_El    : Elmt_Id;
4780       Subt            : Entity_Id;
4781
4782    begin
4783       --  Set the designated type so it is available in case this is an access
4784       --  to a self-referential type, e.g. a standard list type with a next
4785       --  pointer. Will be reset after subtype is built.
4786
4787       Set_Directly_Designated_Type
4788         (Derived_Type, Designated_Type (Parent_Type));
4789
4790       Subt := Process_Subtype (S, N);
4791
4792       if Nkind (S) /= N_Subtype_Indication
4793         and then Subt /= Base_Type (Subt)
4794       then
4795          Set_Ekind (Derived_Type, E_Access_Subtype);
4796       end if;
4797
4798       if Ekind (Derived_Type) = E_Access_Subtype then
4799          declare
4800             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
4801             Ibase      : constant Entity_Id :=
4802                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
4803             Svg_Chars  : constant Name_Id   := Chars (Ibase);
4804             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
4805
4806          begin
4807             Copy_Node (Pbase, Ibase);
4808
4809             Set_Chars             (Ibase, Svg_Chars);
4810             Set_Next_Entity       (Ibase, Svg_Next_E);
4811             Set_Sloc              (Ibase, Sloc (Derived_Type));
4812             Set_Scope             (Ibase, Scope (Derived_Type));
4813             Set_Freeze_Node       (Ibase, Empty);
4814             Set_Is_Frozen         (Ibase, False);
4815             Set_Comes_From_Source (Ibase, False);
4816             Set_Is_First_Subtype  (Ibase, False);
4817
4818             Set_Etype (Ibase, Pbase);
4819             Set_Etype (Derived_Type, Ibase);
4820          end;
4821       end if;
4822
4823       Set_Directly_Designated_Type
4824         (Derived_Type, Designated_Type (Subt));
4825
4826       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
4827       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
4828       Set_Size_Info          (Derived_Type,                     Parent_Type);
4829       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
4830       Set_Depends_On_Private (Derived_Type,
4831                               Has_Private_Component (Derived_Type));
4832       Conditional_Delay      (Derived_Type, Subt);
4833
4834       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
4835       --  that it is not redundant.
4836
4837       if Null_Exclusion_Present (Type_Definition (N)) then
4838          Set_Can_Never_Be_Null (Derived_Type);
4839
4840          if Can_Never_Be_Null (Parent_Type)
4841            and then False
4842          then
4843             Error_Msg_NE
4844               ("`NOT NULL` not allowed (& already excludes null)",
4845                 N, Parent_Type);
4846          end if;
4847
4848       elsif Can_Never_Be_Null (Parent_Type) then
4849          Set_Can_Never_Be_Null (Derived_Type);
4850       end if;
4851
4852       --  Note: we do not copy the Storage_Size_Variable, since we always go to
4853       --  the root type for this information.
4854
4855       --  Apply range checks to discriminants for derived record case
4856       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
4857
4858       Desig_Type := Designated_Type (Derived_Type);
4859       if Is_Composite_Type (Desig_Type)
4860         and then (not Is_Array_Type (Desig_Type))
4861         and then Has_Discriminants (Desig_Type)
4862         and then Base_Type (Desig_Type) /= Desig_Type
4863       then
4864          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
4865          Discr_Con_El := First_Elmt (Discr_Con_Elist);
4866
4867          Discr := First_Discriminant (Base_Type (Desig_Type));
4868          while Present (Discr_Con_El) loop
4869             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
4870             Next_Elmt (Discr_Con_El);
4871             Next_Discriminant (Discr);
4872          end loop;
4873       end if;
4874    end Build_Derived_Access_Type;
4875
4876    ------------------------------
4877    -- Build_Derived_Array_Type --
4878    ------------------------------
4879
4880    procedure Build_Derived_Array_Type
4881      (N            : Node_Id;
4882       Parent_Type  : Entity_Id;
4883       Derived_Type : Entity_Id)
4884    is
4885       Loc           : constant Source_Ptr := Sloc (N);
4886       Tdef          : constant Node_Id    := Type_Definition (N);
4887       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
4888       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
4889       Implicit_Base : Entity_Id;
4890       New_Indic     : Node_Id;
4891
4892       procedure Make_Implicit_Base;
4893       --  If the parent subtype is constrained, the derived type is a subtype
4894       --  of an implicit base type derived from the parent base.
4895
4896       ------------------------
4897       -- Make_Implicit_Base --
4898       ------------------------
4899
4900       procedure Make_Implicit_Base is
4901       begin
4902          Implicit_Base :=
4903            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
4904
4905          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
4906          Set_Etype (Implicit_Base, Parent_Base);
4907
4908          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
4909          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
4910
4911          Set_Has_Delayed_Freeze (Implicit_Base, True);
4912       end Make_Implicit_Base;
4913
4914    --  Start of processing for Build_Derived_Array_Type
4915
4916    begin
4917       if not Is_Constrained (Parent_Type) then
4918          if Nkind (Indic) /= N_Subtype_Indication then
4919             Set_Ekind (Derived_Type, E_Array_Type);
4920
4921             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
4922             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
4923
4924             Set_Has_Delayed_Freeze (Derived_Type, True);
4925
4926          else
4927             Make_Implicit_Base;
4928             Set_Etype (Derived_Type, Implicit_Base);
4929
4930             New_Indic :=
4931               Make_Subtype_Declaration (Loc,
4932                 Defining_Identifier => Derived_Type,
4933                 Subtype_Indication  =>
4934                   Make_Subtype_Indication (Loc,
4935                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
4936                     Constraint => Constraint (Indic)));
4937
4938             Rewrite (N, New_Indic);
4939             Analyze (N);
4940          end if;
4941
4942       else
4943          if Nkind (Indic) /= N_Subtype_Indication then
4944             Make_Implicit_Base;
4945
4946             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
4947             Set_Etype             (Derived_Type, Implicit_Base);
4948             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
4949
4950          else
4951             Error_Msg_N ("illegal constraint on constrained type", Indic);
4952          end if;
4953       end if;
4954
4955       --  If parent type is not a derived type itself, and is declared in
4956       --  closed scope (e.g. a subprogram), then we must explicitly introduce
4957       --  the new type's concatenation operator since Derive_Subprograms
4958       --  will not inherit the parent's operator. If the parent type is
4959       --  unconstrained, the operator is of the unconstrained base type.
4960
4961       if Number_Dimensions (Parent_Type) = 1
4962         and then not Is_Limited_Type (Parent_Type)
4963         and then not Is_Derived_Type (Parent_Type)
4964         and then not Is_Package_Or_Generic_Package
4965                        (Scope (Base_Type (Parent_Type)))
4966       then
4967          if not Is_Constrained (Parent_Type)
4968            and then Is_Constrained (Derived_Type)
4969          then
4970             New_Concatenation_Op (Implicit_Base);
4971          else
4972             New_Concatenation_Op (Derived_Type);
4973          end if;
4974       end if;
4975    end Build_Derived_Array_Type;
4976
4977    -----------------------------------
4978    -- Build_Derived_Concurrent_Type --
4979    -----------------------------------
4980
4981    procedure Build_Derived_Concurrent_Type
4982      (N            : Node_Id;
4983       Parent_Type  : Entity_Id;
4984       Derived_Type : Entity_Id)
4985    is
4986       Loc : constant Source_Ptr := Sloc (N);
4987
4988       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
4989       Corr_Decl        : Node_Id;
4990       Corr_Decl_Needed : Boolean;
4991       --  If the derived type has fewer discriminants than its parent, the
4992       --  corresponding record is also a derived type, in order to account for
4993       --  the bound discriminants. We create a full type declaration for it in
4994       --  this case.
4995
4996       Constraint_Present : constant Boolean :=
4997                              Nkind (Subtype_Indication (Type_Definition (N))) =
4998                                                           N_Subtype_Indication;
4999
5000       D_Constraint   : Node_Id;
5001       New_Constraint : Elist_Id;
5002       Old_Disc       : Entity_Id;
5003       New_Disc       : Entity_Id;
5004       New_N          : Node_Id;
5005
5006    begin
5007       Set_Stored_Constraint (Derived_Type, No_Elist);
5008       Corr_Decl_Needed := False;
5009       Old_Disc := Empty;
5010
5011       if Present (Discriminant_Specifications (N))
5012         and then Constraint_Present
5013       then
5014          Old_Disc := First_Discriminant (Parent_Type);
5015          New_Disc := First (Discriminant_Specifications (N));
5016          while Present (New_Disc) and then Present (Old_Disc) loop
5017             Next_Discriminant (Old_Disc);
5018             Next (New_Disc);
5019          end loop;
5020       end if;
5021
5022       if Present (Old_Disc) then
5023
5024          --  The new type has fewer discriminants, so we need to create a new
5025          --  corresponding record, which is derived from the corresponding
5026          --  record of the parent, and has a stored constraint that captures
5027          --  the values of the discriminant constraints.
5028
5029          --  The type declaration for the derived corresponding record has
5030          --  the same discriminant part and constraints as the current
5031          --  declaration. Copy the unanalyzed tree to build declaration.
5032
5033          Corr_Decl_Needed := True;
5034          New_N := Copy_Separate_Tree (N);
5035
5036          Corr_Decl :=
5037            Make_Full_Type_Declaration (Loc,
5038              Defining_Identifier => Corr_Record,
5039              Discriminant_Specifications =>
5040                 Discriminant_Specifications (New_N),
5041              Type_Definition =>
5042                Make_Derived_Type_Definition (Loc,
5043                  Subtype_Indication =>
5044                    Make_Subtype_Indication (Loc,
5045                      Subtype_Mark =>
5046                         New_Occurrence_Of
5047                           (Corresponding_Record_Type (Parent_Type), Loc),
5048                      Constraint =>
5049                        Constraint
5050                          (Subtype_Indication (Type_Definition (New_N))))));
5051       end if;
5052
5053       --  Copy Storage_Size and Relative_Deadline variables if task case
5054
5055       if Is_Task_Type (Parent_Type) then
5056          Set_Storage_Size_Variable (Derived_Type,
5057            Storage_Size_Variable (Parent_Type));
5058          Set_Relative_Deadline_Variable (Derived_Type,
5059            Relative_Deadline_Variable (Parent_Type));
5060       end if;
5061
5062       if Present (Discriminant_Specifications (N)) then
5063          Push_Scope (Derived_Type);
5064          Check_Or_Process_Discriminants (N, Derived_Type);
5065
5066          if Constraint_Present then
5067             New_Constraint :=
5068               Expand_To_Stored_Constraint
5069                 (Parent_Type,
5070                  Build_Discriminant_Constraints
5071                    (Parent_Type,
5072                     Subtype_Indication (Type_Definition (N)), True));
5073          end if;
5074
5075          End_Scope;
5076
5077       elsif Constraint_Present then
5078
5079          --  Build constrained subtype and derive from it
5080
5081          declare
5082             Loc  : constant Source_Ptr := Sloc (N);
5083             Anon : constant Entity_Id :=
5084                      Make_Defining_Identifier (Loc,
5085                        New_External_Name (Chars (Derived_Type), 'T'));
5086             Decl : Node_Id;
5087
5088          begin
5089             Decl :=
5090               Make_Subtype_Declaration (Loc,
5091                 Defining_Identifier => Anon,
5092                 Subtype_Indication =>
5093                   Subtype_Indication (Type_Definition (N)));
5094             Insert_Before (N, Decl);
5095             Analyze (Decl);
5096
5097             Rewrite (Subtype_Indication (Type_Definition (N)),
5098               New_Occurrence_Of (Anon, Loc));
5099             Set_Analyzed (Derived_Type, False);
5100             Analyze (N);
5101             return;
5102          end;
5103       end if;
5104
5105       --  By default, operations and private data are inherited from parent.
5106       --  However, in the presence of bound discriminants, a new corresponding
5107       --  record will be created, see below.
5108
5109       Set_Has_Discriminants
5110         (Derived_Type, Has_Discriminants         (Parent_Type));
5111       Set_Corresponding_Record_Type
5112         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5113
5114       --  Is_Constrained is set according the parent subtype, but is set to
5115       --  False if the derived type is declared with new discriminants.
5116
5117       Set_Is_Constrained
5118         (Derived_Type,
5119          (Is_Constrained (Parent_Type) or else Constraint_Present)
5120            and then not Present (Discriminant_Specifications (N)));
5121
5122       if Constraint_Present then
5123          if not Has_Discriminants (Parent_Type) then
5124             Error_Msg_N ("untagged parent must have discriminants", N);
5125
5126          elsif Present (Discriminant_Specifications (N)) then
5127
5128             --  Verify that new discriminants are used to constrain old ones
5129
5130             D_Constraint :=
5131               First
5132                 (Constraints
5133                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5134
5135             Old_Disc := First_Discriminant (Parent_Type);
5136
5137             while Present (D_Constraint) loop
5138                if Nkind (D_Constraint) /= N_Discriminant_Association then
5139
5140                   --  Positional constraint. If it is a reference to a new
5141                   --  discriminant, it constrains the corresponding old one.
5142
5143                   if Nkind (D_Constraint) = N_Identifier then
5144                      New_Disc := First_Discriminant (Derived_Type);
5145                      while Present (New_Disc) loop
5146                         exit when Chars (New_Disc) = Chars (D_Constraint);
5147                         Next_Discriminant (New_Disc);
5148                      end loop;
5149
5150                      if Present (New_Disc) then
5151                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5152                      end if;
5153                   end if;
5154
5155                   Next_Discriminant (Old_Disc);
5156
5157                   --  if this is a named constraint, search by name for the old
5158                   --  discriminants constrained by the new one.
5159
5160                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5161
5162                   --  Find new discriminant with that name
5163
5164                   New_Disc := First_Discriminant (Derived_Type);
5165                   while Present (New_Disc) loop
5166                      exit when
5167                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5168                      Next_Discriminant (New_Disc);
5169                   end loop;
5170
5171                   if Present (New_Disc) then
5172
5173                      --  Verify that new discriminant renames some discriminant
5174                      --  of the parent type, and associate the new discriminant
5175                      --  with one or more old ones that it renames.
5176
5177                      declare
5178                         Selector : Node_Id;
5179
5180                      begin
5181                         Selector := First (Selector_Names (D_Constraint));
5182                         while Present (Selector) loop
5183                            Old_Disc := First_Discriminant (Parent_Type);
5184                            while Present (Old_Disc) loop
5185                               exit when Chars (Old_Disc) = Chars (Selector);
5186                               Next_Discriminant (Old_Disc);
5187                            end loop;
5188
5189                            if Present (Old_Disc) then
5190                               Set_Corresponding_Discriminant
5191                                 (New_Disc, Old_Disc);
5192                            end if;
5193
5194                            Next (Selector);
5195                         end loop;
5196                      end;
5197                   end if;
5198                end if;
5199
5200                Next (D_Constraint);
5201             end loop;
5202
5203             New_Disc := First_Discriminant (Derived_Type);
5204             while Present (New_Disc) loop
5205                if No (Corresponding_Discriminant (New_Disc)) then
5206                   Error_Msg_NE
5207                     ("new discriminant& must constrain old one", N, New_Disc);
5208
5209                elsif not
5210                  Subtypes_Statically_Compatible
5211                    (Etype (New_Disc),
5212                     Etype (Corresponding_Discriminant (New_Disc)))
5213                then
5214                   Error_Msg_NE
5215                     ("& not statically compatible with parent discriminant",
5216                       N, New_Disc);
5217                end if;
5218
5219                Next_Discriminant (New_Disc);
5220             end loop;
5221          end if;
5222
5223       elsif Present (Discriminant_Specifications (N)) then
5224          Error_Msg_N
5225            ("missing discriminant constraint in untagged derivation", N);
5226       end if;
5227
5228       --  The entity chain of the derived type includes the new discriminants
5229       --  but shares operations with the parent.
5230
5231       if Present (Discriminant_Specifications (N)) then
5232          Old_Disc := First_Discriminant (Parent_Type);
5233          while Present (Old_Disc) loop
5234             if No (Next_Entity (Old_Disc))
5235               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5236             then
5237                Set_Next_Entity
5238                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5239                exit;
5240             end if;
5241
5242             Next_Discriminant (Old_Disc);
5243          end loop;
5244
5245       else
5246          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5247          if Has_Discriminants (Parent_Type) then
5248             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5249             Set_Discriminant_Constraint (
5250               Derived_Type, Discriminant_Constraint (Parent_Type));
5251          end if;
5252       end if;
5253
5254       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5255
5256       Set_Has_Completion (Derived_Type);
5257
5258       if Corr_Decl_Needed then
5259          Set_Stored_Constraint (Derived_Type, New_Constraint);
5260          Insert_After (N, Corr_Decl);
5261          Analyze (Corr_Decl);
5262          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5263       end if;
5264    end Build_Derived_Concurrent_Type;
5265
5266    ------------------------------------
5267    -- Build_Derived_Enumeration_Type --
5268    ------------------------------------
5269
5270    procedure Build_Derived_Enumeration_Type
5271      (N            : Node_Id;
5272       Parent_Type  : Entity_Id;
5273       Derived_Type : Entity_Id)
5274    is
5275       Loc           : constant Source_Ptr := Sloc (N);
5276       Def           : constant Node_Id    := Type_Definition (N);
5277       Indic         : constant Node_Id    := Subtype_Indication (Def);
5278       Implicit_Base : Entity_Id;
5279       Literal       : Entity_Id;
5280       New_Lit       : Entity_Id;
5281       Literals_List : List_Id;
5282       Type_Decl     : Node_Id;
5283       Hi, Lo        : Node_Id;
5284       Rang_Expr     : Node_Id;
5285
5286    begin
5287       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5288       --  not have explicit literals lists we need to process types derived
5289       --  from them specially. This is handled by Derived_Standard_Character.
5290       --  If the parent type is a generic type, there are no literals either,
5291       --  and we construct the same skeletal representation as for the generic
5292       --  parent type.
5293
5294       if Is_Standard_Character_Type (Parent_Type) then
5295          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5296
5297       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5298          declare
5299             Lo : Node_Id;
5300             Hi : Node_Id;
5301
5302          begin
5303             if Nkind (Indic) /= N_Subtype_Indication then
5304                Lo :=
5305                   Make_Attribute_Reference (Loc,
5306                     Attribute_Name => Name_First,
5307                     Prefix         => New_Reference_To (Derived_Type, Loc));
5308                Set_Etype (Lo, Derived_Type);
5309
5310                Hi :=
5311                   Make_Attribute_Reference (Loc,
5312                     Attribute_Name => Name_Last,
5313                     Prefix         => New_Reference_To (Derived_Type, Loc));
5314                Set_Etype (Hi, Derived_Type);
5315
5316                Set_Scalar_Range (Derived_Type,
5317                   Make_Range (Loc,
5318                     Low_Bound  => Lo,
5319                     High_Bound => Hi));
5320             else
5321
5322                --   Analyze subtype indication and verify compatibility
5323                --   with parent type.
5324
5325                if Base_Type (Process_Subtype (Indic, N)) /=
5326                   Base_Type (Parent_Type)
5327                then
5328                   Error_Msg_N
5329                     ("illegal constraint for formal discrete type", N);
5330                end if;
5331             end if;
5332          end;
5333
5334       else
5335          --  If a constraint is present, analyze the bounds to catch
5336          --  premature usage of the derived literals.
5337
5338          if Nkind (Indic) = N_Subtype_Indication
5339            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5340          then
5341             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5342             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5343          end if;
5344
5345          --  Introduce an implicit base type for the derived type even if there
5346          --  is no constraint attached to it, since this seems closer to the
5347          --  Ada semantics. Build a full type declaration tree for the derived
5348          --  type using the implicit base type as the defining identifier. The
5349          --  build a subtype declaration tree which applies the constraint (if
5350          --  any) have it replace the derived type declaration.
5351
5352          Literal := First_Literal (Parent_Type);
5353          Literals_List := New_List;
5354          while Present (Literal)
5355            and then Ekind (Literal) = E_Enumeration_Literal
5356          loop
5357             --  Literals of the derived type have the same representation as
5358             --  those of the parent type, but this representation can be
5359             --  overridden by an explicit representation clause. Indicate
5360             --  that there is no explicit representation given yet. These
5361             --  derived literals are implicit operations of the new type,
5362             --  and can be overridden by explicit ones.
5363
5364             if Nkind (Literal) = N_Defining_Character_Literal then
5365                New_Lit :=
5366                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5367             else
5368                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5369             end if;
5370
5371             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5372             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5373             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5374             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5375             Set_Alias                (New_Lit, Literal);
5376             Set_Is_Known_Valid       (New_Lit, True);
5377
5378             Append (New_Lit, Literals_List);
5379             Next_Literal (Literal);
5380          end loop;
5381
5382          Implicit_Base :=
5383            Make_Defining_Identifier (Sloc (Derived_Type),
5384              New_External_Name (Chars (Derived_Type), 'B'));
5385
5386          --  Indicate the proper nature of the derived type. This must be done
5387          --  before analysis of the literals, to recognize cases when a literal
5388          --  may be hidden by a previous explicit function definition (cf.
5389          --  c83031a).
5390
5391          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5392          Set_Etype (Derived_Type, Implicit_Base);
5393
5394          Type_Decl :=
5395            Make_Full_Type_Declaration (Loc,
5396              Defining_Identifier => Implicit_Base,
5397              Discriminant_Specifications => No_List,
5398              Type_Definition =>
5399                Make_Enumeration_Type_Definition (Loc, Literals_List));
5400
5401          Mark_Rewrite_Insertion (Type_Decl);
5402          Insert_Before (N, Type_Decl);
5403          Analyze (Type_Decl);
5404
5405          --  After the implicit base is analyzed its Etype needs to be changed
5406          --  to reflect the fact that it is derived from the parent type which
5407          --  was ignored during analysis. We also set the size at this point.
5408
5409          Set_Etype (Implicit_Base, Parent_Type);
5410
5411          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5412          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5413          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5414
5415          --  Copy other flags from parent type
5416
5417          Set_Has_Non_Standard_Rep
5418                             (Implicit_Base, Has_Non_Standard_Rep
5419                                                            (Parent_Type));
5420          Set_Has_Pragma_Ordered
5421                             (Implicit_Base, Has_Pragma_Ordered
5422                                                            (Parent_Type));
5423          Set_Has_Delayed_Freeze (Implicit_Base);
5424
5425          --  Process the subtype indication including a validation check on the
5426          --  constraint, if any. If a constraint is given, its bounds must be
5427          --  implicitly converted to the new type.
5428
5429          if Nkind (Indic) = N_Subtype_Indication then
5430             declare
5431                R : constant Node_Id :=
5432                      Range_Expression (Constraint (Indic));
5433
5434             begin
5435                if Nkind (R) = N_Range then
5436                   Hi := Build_Scalar_Bound
5437                           (High_Bound (R), Parent_Type, Implicit_Base);
5438                   Lo := Build_Scalar_Bound
5439                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5440
5441                else
5442                   --  Constraint is a Range attribute. Replace with explicit
5443                   --  mention of the bounds of the prefix, which must be a
5444                   --  subtype.
5445
5446                   Analyze (Prefix (R));
5447                   Hi :=
5448                     Convert_To (Implicit_Base,
5449                       Make_Attribute_Reference (Loc,
5450                         Attribute_Name => Name_Last,
5451                         Prefix =>
5452                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5453
5454                   Lo :=
5455                     Convert_To (Implicit_Base,
5456                       Make_Attribute_Reference (Loc,
5457                         Attribute_Name => Name_First,
5458                         Prefix =>
5459                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5460                end if;
5461             end;
5462
5463          else
5464             Hi :=
5465               Build_Scalar_Bound
5466                 (Type_High_Bound (Parent_Type),
5467                  Parent_Type, Implicit_Base);
5468             Lo :=
5469                Build_Scalar_Bound
5470                  (Type_Low_Bound (Parent_Type),
5471                   Parent_Type, Implicit_Base);
5472          end if;
5473
5474          Rang_Expr :=
5475            Make_Range (Loc,
5476              Low_Bound  => Lo,
5477              High_Bound => Hi);
5478
5479          --  If we constructed a default range for the case where no range
5480          --  was given, then the expressions in the range must not freeze
5481          --  since they do not correspond to expressions in the source.
5482
5483          if Nkind (Indic) /= N_Subtype_Indication then
5484             Set_Must_Not_Freeze (Lo);
5485             Set_Must_Not_Freeze (Hi);
5486             Set_Must_Not_Freeze (Rang_Expr);
5487          end if;
5488
5489          Rewrite (N,
5490            Make_Subtype_Declaration (Loc,
5491              Defining_Identifier => Derived_Type,
5492              Subtype_Indication =>
5493                Make_Subtype_Indication (Loc,
5494                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
5495                  Constraint =>
5496                    Make_Range_Constraint (Loc,
5497                      Range_Expression => Rang_Expr))));
5498
5499          Analyze (N);
5500
5501          --  If pragma Discard_Names applies on the first subtype of the parent
5502          --  type, then it must be applied on this subtype as well.
5503
5504          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
5505             Set_Discard_Names (Derived_Type);
5506          end if;
5507
5508          --  Apply a range check. Since this range expression doesn't have an
5509          --  Etype, we have to specifically pass the Source_Typ parameter. Is
5510          --  this right???
5511
5512          if Nkind (Indic) = N_Subtype_Indication then
5513             Apply_Range_Check (Range_Expression (Constraint (Indic)),
5514                                Parent_Type,
5515                                Source_Typ => Entity (Subtype_Mark (Indic)));
5516          end if;
5517       end if;
5518    end Build_Derived_Enumeration_Type;
5519
5520    --------------------------------
5521    -- Build_Derived_Numeric_Type --
5522    --------------------------------
5523
5524    procedure Build_Derived_Numeric_Type
5525      (N            : Node_Id;
5526       Parent_Type  : Entity_Id;
5527       Derived_Type : Entity_Id)
5528    is
5529       Loc           : constant Source_Ptr := Sloc (N);
5530       Tdef          : constant Node_Id    := Type_Definition (N);
5531       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5532       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5533       No_Constraint : constant Boolean    := Nkind (Indic) /=
5534                                                   N_Subtype_Indication;
5535       Implicit_Base : Entity_Id;
5536
5537       Lo : Node_Id;
5538       Hi : Node_Id;
5539
5540    begin
5541       --  Process the subtype indication including a validation check on
5542       --  the constraint if any.
5543
5544       Discard_Node (Process_Subtype (Indic, N));
5545
5546       --  Introduce an implicit base type for the derived type even if there
5547       --  is no constraint attached to it, since this seems closer to the Ada
5548       --  semantics.
5549
5550       Implicit_Base :=
5551         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5552
5553       Set_Etype          (Implicit_Base, Parent_Base);
5554       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
5555       Set_Size_Info      (Implicit_Base,                 Parent_Base);
5556       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
5557       Set_Parent         (Implicit_Base, Parent (Derived_Type));
5558       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
5559
5560       --  Set RM Size for discrete type or decimal fixed-point type
5561       --  Ordinary fixed-point is excluded, why???
5562
5563       if Is_Discrete_Type (Parent_Base)
5564         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
5565       then
5566          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
5567       end if;
5568
5569       Set_Has_Delayed_Freeze (Implicit_Base);
5570
5571       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
5572       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
5573
5574       Set_Scalar_Range (Implicit_Base,
5575         Make_Range (Loc,
5576           Low_Bound  => Lo,
5577           High_Bound => Hi));
5578
5579       if Has_Infinities (Parent_Base) then
5580          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
5581       end if;
5582
5583       --  The Derived_Type, which is the entity of the declaration, is a
5584       --  subtype of the implicit base. Its Ekind is a subtype, even in the
5585       --  absence of an explicit constraint.
5586
5587       Set_Etype (Derived_Type, Implicit_Base);
5588
5589       --  If we did not have a constraint, then the Ekind is set from the
5590       --  parent type (otherwise Process_Subtype has set the bounds)
5591
5592       if No_Constraint then
5593          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
5594       end if;
5595
5596       --  If we did not have a range constraint, then set the range from the
5597       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
5598
5599       if No_Constraint
5600         or else not Has_Range_Constraint (Indic)
5601       then
5602          Set_Scalar_Range (Derived_Type,
5603            Make_Range (Loc,
5604              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
5605              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
5606          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5607
5608          if Has_Infinities (Parent_Type) then
5609             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5610          end if;
5611
5612          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
5613       end if;
5614
5615       Set_Is_Descendent_Of_Address (Derived_Type,
5616         Is_Descendent_Of_Address (Parent_Type));
5617       Set_Is_Descendent_Of_Address (Implicit_Base,
5618         Is_Descendent_Of_Address (Parent_Type));
5619
5620       --  Set remaining type-specific fields, depending on numeric type
5621
5622       if Is_Modular_Integer_Type (Parent_Type) then
5623          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5624
5625          Set_Non_Binary_Modulus
5626            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5627
5628          Set_Is_Known_Valid
5629            (Implicit_Base, Is_Known_Valid (Parent_Base));
5630
5631       elsif Is_Floating_Point_Type (Parent_Type) then
5632
5633          --  Digits of base type is always copied from the digits value of
5634          --  the parent base type, but the digits of the derived type will
5635          --  already have been set if there was a constraint present.
5636
5637          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5638          Set_Vax_Float    (Implicit_Base, Vax_Float    (Parent_Base));
5639
5640          if No_Constraint then
5641             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5642          end if;
5643
5644       elsif Is_Fixed_Point_Type (Parent_Type) then
5645
5646          --  Small of base type and derived type are always copied from the
5647          --  parent base type, since smalls never change. The delta of the
5648          --  base type is also copied from the parent base type. However the
5649          --  delta of the derived type will have been set already if a
5650          --  constraint was present.
5651
5652          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5653          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5654          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5655
5656          if No_Constraint then
5657             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5658          end if;
5659
5660          --  The scale and machine radix in the decimal case are always
5661          --  copied from the parent base type.
5662
5663          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
5664             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
5665             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
5666
5667             Set_Machine_Radix_10
5668               (Derived_Type,  Machine_Radix_10 (Parent_Base));
5669             Set_Machine_Radix_10
5670               (Implicit_Base, Machine_Radix_10 (Parent_Base));
5671
5672             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5673
5674             if No_Constraint then
5675                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
5676
5677             else
5678                --  the analysis of the subtype_indication sets the
5679                --  digits value of the derived type.
5680
5681                null;
5682             end if;
5683          end if;
5684       end if;
5685
5686       --  The type of the bounds is that of the parent type, and they
5687       --  must be converted to the derived type.
5688
5689       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
5690
5691       --  The implicit_base should be frozen when the derived type is frozen,
5692       --  but note that it is used in the conversions of the bounds. For fixed
5693       --  types we delay the determination of the bounds until the proper
5694       --  freezing point. For other numeric types this is rejected by GCC, for
5695       --  reasons that are currently unclear (???), so we choose to freeze the
5696       --  implicit base now. In the case of integers and floating point types
5697       --  this is harmless because subsequent representation clauses cannot
5698       --  affect anything, but it is still baffling that we cannot use the
5699       --  same mechanism for all derived numeric types.
5700
5701       --  There is a further complication: actually *some* representation
5702       --  clauses can affect the implicit base type. Namely, attribute
5703       --  definition clauses for stream-oriented attributes need to set the
5704       --  corresponding TSS entries on the base type, and this normally cannot
5705       --  be done after the base type is frozen, so the circuitry in
5706       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
5707       --  not use Set_TSS in this case.
5708
5709       if Is_Fixed_Point_Type (Parent_Type) then
5710          Conditional_Delay (Implicit_Base, Parent_Type);
5711       else
5712          Freeze_Before (N, Implicit_Base);
5713       end if;
5714    end Build_Derived_Numeric_Type;
5715
5716    --------------------------------
5717    -- Build_Derived_Private_Type --
5718    --------------------------------
5719
5720    procedure Build_Derived_Private_Type
5721      (N             : Node_Id;
5722       Parent_Type   : Entity_Id;
5723       Derived_Type  : Entity_Id;
5724       Is_Completion : Boolean;
5725       Derive_Subps  : Boolean := True)
5726    is
5727       Loc         : constant Source_Ptr := Sloc (N);
5728       Der_Base    : Entity_Id;
5729       Discr       : Entity_Id;
5730       Full_Decl   : Node_Id := Empty;
5731       Full_Der    : Entity_Id;
5732       Full_P      : Entity_Id;
5733       Last_Discr  : Entity_Id;
5734       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
5735       Swapped     : Boolean := False;
5736
5737       procedure Copy_And_Build;
5738       --  Copy derived type declaration, replace parent with its full view,
5739       --  and analyze new declaration.
5740
5741       --------------------
5742       -- Copy_And_Build --
5743       --------------------
5744
5745       procedure Copy_And_Build is
5746          Full_N : Node_Id;
5747
5748       begin
5749          if Ekind (Parent_Type) in Record_Kind
5750            or else
5751              (Ekind (Parent_Type) in Enumeration_Kind
5752                and then not Is_Standard_Character_Type (Parent_Type)
5753                and then not Is_Generic_Type (Root_Type (Parent_Type)))
5754          then
5755             Full_N := New_Copy_Tree (N);
5756             Insert_After (N, Full_N);
5757             Build_Derived_Type (
5758               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
5759
5760          else
5761             Build_Derived_Type (
5762               N, Parent_Type, Full_Der, True, Derive_Subps => False);
5763          end if;
5764       end Copy_And_Build;
5765
5766    --  Start of processing for Build_Derived_Private_Type
5767
5768    begin
5769       if Is_Tagged_Type (Parent_Type) then
5770          Full_P := Full_View (Parent_Type);
5771
5772          --  A type extension of a type with unknown discriminants is an
5773          --  indefinite type that the back-end cannot handle directly.
5774          --  We treat it as a private type, and build a completion that is
5775          --  derived from the full view of the parent, and hopefully has
5776          --  known discriminants.
5777
5778          --  If the full view of the parent type has an underlying record view,
5779          --  use it to generate the underlying record view of this derived type
5780          --  (required for chains of derivations with unknown discriminants).
5781
5782          --  Minor optimization: we avoid the generation of useless underlying
5783          --  record view entities if the private type declaration has unknown
5784          --  discriminants but its corresponding full view has no
5785          --  discriminants.
5786
5787          if Has_Unknown_Discriminants (Parent_Type)
5788            and then Present (Full_P)
5789            and then (Has_Discriminants (Full_P)
5790                       or else Present (Underlying_Record_View (Full_P)))
5791            and then not In_Open_Scopes (Par_Scope)
5792            and then Expander_Active
5793          then
5794             declare
5795                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
5796                New_Ext  : constant Node_Id :=
5797                             Copy_Separate_Tree
5798                               (Record_Extension_Part (Type_Definition (N)));
5799                Decl     : Node_Id;
5800
5801             begin
5802                Build_Derived_Record_Type
5803                  (N, Parent_Type, Derived_Type, Derive_Subps);
5804
5805                --  Build anonymous completion, as a derivation from the full
5806                --  view of the parent. This is not a completion in the usual
5807                --  sense, because the current type is not private.
5808
5809                Decl :=
5810                  Make_Full_Type_Declaration (Loc,
5811                    Defining_Identifier => Full_Der,
5812                    Type_Definition     =>
5813                      Make_Derived_Type_Definition (Loc,
5814                        Subtype_Indication =>
5815                          New_Copy_Tree
5816                            (Subtype_Indication (Type_Definition (N))),
5817                        Record_Extension_Part => New_Ext));
5818
5819                --  If the parent type has an underlying record view, use it
5820                --  here to build the new underlying record view.
5821
5822                if Present (Underlying_Record_View (Full_P)) then
5823                   pragma Assert
5824                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
5825                        = N_Identifier);
5826                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
5827                     Underlying_Record_View (Full_P));
5828                end if;
5829
5830                Install_Private_Declarations (Par_Scope);
5831                Install_Visible_Declarations (Par_Scope);
5832                Insert_Before (N, Decl);
5833
5834                --  Mark entity as an underlying record view before analysis,
5835                --  to avoid generating the list of its primitive operations
5836                --  (which is not really required for this entity) and thus
5837                --  prevent spurious errors associated with missing overriding
5838                --  of abstract primitives (overridden only for Derived_Type).
5839
5840                Set_Ekind (Full_Der, E_Record_Type);
5841                Set_Is_Underlying_Record_View (Full_Der);
5842
5843                Analyze (Decl);
5844
5845                pragma Assert (Has_Discriminants (Full_Der)
5846                  and then not Has_Unknown_Discriminants (Full_Der));
5847
5848                Uninstall_Declarations (Par_Scope);
5849
5850                --  Freeze the underlying record view, to prevent generation of
5851                --  useless dispatching information, which is simply shared with
5852                --  the real derived type.
5853
5854                Set_Is_Frozen (Full_Der);
5855
5856                --  Set up links between real entity and underlying record view
5857
5858                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
5859                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
5860             end;
5861
5862          --  If discriminants are known, build derived record
5863
5864          else
5865             Build_Derived_Record_Type
5866               (N, Parent_Type, Derived_Type, Derive_Subps);
5867          end if;
5868
5869          return;
5870
5871       elsif Has_Discriminants (Parent_Type) then
5872          if Present (Full_View (Parent_Type)) then
5873             if not Is_Completion then
5874
5875                --  Copy declaration for subsequent analysis, to provide a
5876                --  completion for what is a private declaration. Indicate that
5877                --  the full type is internally generated.
5878
5879                Full_Decl := New_Copy_Tree (N);
5880                Full_Der  := New_Copy (Derived_Type);
5881                Set_Comes_From_Source (Full_Decl, False);
5882                Set_Comes_From_Source (Full_Der, False);
5883                Set_Parent (Full_Der, Full_Decl);
5884
5885                Insert_After (N, Full_Decl);
5886
5887             else
5888                --  If this is a completion, the full view being built is itself
5889                --  private. We build a subtype of the parent with the same
5890                --  constraints as this full view, to convey to the back end the
5891                --  constrained components and the size of this subtype. If the
5892                --  parent is constrained, its full view can serve as the
5893                --  underlying full view of the derived type.
5894
5895                if No (Discriminant_Specifications (N)) then
5896                   if Nkind (Subtype_Indication (Type_Definition (N))) =
5897                                                         N_Subtype_Indication
5898                   then
5899                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
5900
5901                   elsif Is_Constrained (Full_View (Parent_Type)) then
5902                      Set_Underlying_Full_View
5903                        (Derived_Type, Full_View (Parent_Type));
5904                   end if;
5905
5906                else
5907                   --  If there are new discriminants, the parent subtype is
5908                   --  constrained by them, but it is not clear how to build
5909                   --  the Underlying_Full_View in this case???
5910
5911                   null;
5912                end if;
5913             end if;
5914          end if;
5915
5916          --  Build partial view of derived type from partial view of parent
5917
5918          Build_Derived_Record_Type
5919            (N, Parent_Type, Derived_Type, Derive_Subps);
5920
5921          if Present (Full_View (Parent_Type)) and then not Is_Completion then
5922             if not In_Open_Scopes (Par_Scope)
5923               or else not In_Same_Source_Unit (N, Parent_Type)
5924             then
5925                --  Swap partial and full views temporarily
5926
5927                Install_Private_Declarations (Par_Scope);
5928                Install_Visible_Declarations (Par_Scope);
5929                Swapped := True;
5930             end if;
5931
5932             --  Build full view of derived type from full view of parent which
5933             --  is now installed. Subprograms have been derived on the partial
5934             --  view, the completion does not derive them anew.
5935
5936             if not Is_Tagged_Type (Parent_Type) then
5937
5938                --  If the parent is itself derived from another private type,
5939                --  installing the private declarations has not affected its
5940                --  privacy status, so use its own full view explicitly.
5941
5942                if Is_Private_Type (Parent_Type) then
5943                   Build_Derived_Record_Type
5944                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
5945                else
5946                   Build_Derived_Record_Type
5947                     (Full_Decl, Parent_Type, Full_Der, False);
5948                end if;
5949
5950             else
5951                --  If full view of parent is tagged, the completion inherits
5952                --  the proper primitive operations.
5953
5954                Set_Defining_Identifier (Full_Decl, Full_Der);
5955                Build_Derived_Record_Type
5956                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
5957             end if;
5958
5959             --  The full declaration has been introduced into the tree and
5960             --  processed in the step above. It should not be analyzed again
5961             --  (when encountered later in the current list of declarations)
5962             --  to prevent spurious name conflicts. The full entity remains
5963             --  invisible.
5964
5965             Set_Analyzed (Full_Decl);
5966
5967             if Swapped then
5968                Uninstall_Declarations (Par_Scope);
5969
5970                if In_Open_Scopes (Par_Scope) then
5971                   Install_Visible_Declarations (Par_Scope);
5972                end if;
5973             end if;
5974
5975             Der_Base := Base_Type (Derived_Type);
5976             Set_Full_View (Derived_Type, Full_Der);
5977             Set_Full_View (Der_Base, Base_Type (Full_Der));
5978
5979             --  Copy the discriminant list from full view to the partial views
5980             --  (base type and its subtype). Gigi requires that the partial and
5981             --  full views have the same discriminants.
5982
5983             --  Note that since the partial view is pointing to discriminants
5984             --  in the full view, their scope will be that of the full view.
5985             --  This might cause some front end problems and need adjustment???
5986
5987             Discr := First_Discriminant (Base_Type (Full_Der));
5988             Set_First_Entity (Der_Base, Discr);
5989
5990             loop
5991                Last_Discr := Discr;
5992                Next_Discriminant (Discr);
5993                exit when No (Discr);
5994             end loop;
5995
5996             Set_Last_Entity (Der_Base, Last_Discr);
5997
5998             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
5999             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
6000             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
6001
6002          else
6003             --  If this is a completion, the derived type stays private and
6004             --  there is no need to create a further full view, except in the
6005             --  unusual case when the derivation is nested within a child unit,
6006             --  see below.
6007
6008             null;
6009          end if;
6010
6011       elsif Present (Full_View (Parent_Type))
6012         and then  Has_Discriminants (Full_View (Parent_Type))
6013       then
6014          if Has_Unknown_Discriminants (Parent_Type)
6015            and then Nkind (Subtype_Indication (Type_Definition (N))) =
6016                                                          N_Subtype_Indication
6017          then
6018             Error_Msg_N
6019               ("cannot constrain type with unknown discriminants",
6020                Subtype_Indication (Type_Definition (N)));
6021             return;
6022          end if;
6023
6024          --  If full view of parent is a record type, build full view as a
6025          --  derivation from the parent's full view. Partial view remains
6026          --  private. For code generation and linking, the full view must have
6027          --  the same public status as the partial one. This full view is only
6028          --  needed if the parent type is in an enclosing scope, so that the
6029          --  full view may actually become visible, e.g. in a child unit. This
6030          --  is both more efficient, and avoids order of freezing problems with
6031          --  the added entities.
6032
6033          if not Is_Private_Type (Full_View (Parent_Type))
6034            and then (In_Open_Scopes (Scope (Parent_Type)))
6035          then
6036             Full_Der := Make_Defining_Identifier (Sloc (Derived_Type),
6037                                               Chars (Derived_Type));
6038             Set_Is_Itype (Full_Der);
6039             Set_Has_Private_Declaration (Full_Der);
6040             Set_Has_Private_Declaration (Derived_Type);
6041             Set_Associated_Node_For_Itype (Full_Der, N);
6042             Set_Parent (Full_Der, Parent (Derived_Type));
6043             Set_Full_View (Derived_Type, Full_Der);
6044             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6045             Full_P := Full_View (Parent_Type);
6046             Exchange_Declarations (Parent_Type);
6047             Copy_And_Build;
6048             Exchange_Declarations (Full_P);
6049
6050          else
6051             Build_Derived_Record_Type
6052               (N, Full_View (Parent_Type), Derived_Type,
6053                 Derive_Subps => False);
6054          end if;
6055
6056          --  In any case, the primitive operations are inherited from the
6057          --  parent type, not from the internal full view.
6058
6059          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6060
6061          if Derive_Subps then
6062             Derive_Subprograms (Parent_Type, Derived_Type);
6063          end if;
6064
6065       else
6066          --  Untagged type, No discriminants on either view
6067
6068          if Nkind (Subtype_Indication (Type_Definition (N))) =
6069                                                    N_Subtype_Indication
6070          then
6071             Error_Msg_N
6072               ("illegal constraint on type without discriminants", N);
6073          end if;
6074
6075          if Present (Discriminant_Specifications (N))
6076            and then Present (Full_View (Parent_Type))
6077            and then not Is_Tagged_Type (Full_View (Parent_Type))
6078          then
6079             Error_Msg_N ("cannot add discriminants to untagged type", N);
6080          end if;
6081
6082          Set_Stored_Constraint (Derived_Type, No_Elist);
6083          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6084          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6085          Set_Has_Controlled_Component
6086                                (Derived_Type, Has_Controlled_Component
6087                                                              (Parent_Type));
6088
6089          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6090
6091          if not Is_Controlled  (Parent_Type) then
6092             Set_Finalize_Storage_Only
6093               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6094          end if;
6095
6096          --  Construct the implicit full view by deriving from full view of the
6097          --  parent type. In order to get proper visibility, we install the
6098          --  parent scope and its declarations.
6099
6100          --  ??? If the parent is untagged private and its completion is
6101          --  tagged, this mechanism will not work because we cannot derive from
6102          --  the tagged full view unless we have an extension.
6103
6104          if Present (Full_View (Parent_Type))
6105            and then not Is_Tagged_Type (Full_View (Parent_Type))
6106            and then not Is_Completion
6107          then
6108             Full_Der :=
6109               Make_Defining_Identifier (Sloc (Derived_Type),
6110                 Chars => Chars (Derived_Type));
6111             Set_Is_Itype (Full_Der);
6112             Set_Has_Private_Declaration (Full_Der);
6113             Set_Has_Private_Declaration (Derived_Type);
6114             Set_Associated_Node_For_Itype (Full_Der, N);
6115             Set_Parent (Full_Der, Parent (Derived_Type));
6116             Set_Full_View (Derived_Type, Full_Der);
6117
6118             if not In_Open_Scopes (Par_Scope) then
6119                Install_Private_Declarations (Par_Scope);
6120                Install_Visible_Declarations (Par_Scope);
6121                Copy_And_Build;
6122                Uninstall_Declarations (Par_Scope);
6123
6124             --  If parent scope is open and in another unit, and parent has a
6125             --  completion, then the derivation is taking place in the visible
6126             --  part of a child unit. In that case retrieve the full view of
6127             --  the parent momentarily.
6128
6129             elsif not In_Same_Source_Unit (N, Parent_Type) then
6130                Full_P := Full_View (Parent_Type);
6131                Exchange_Declarations (Parent_Type);
6132                Copy_And_Build;
6133                Exchange_Declarations (Full_P);
6134
6135             --  Otherwise it is a local derivation
6136
6137             else
6138                Copy_And_Build;
6139             end if;
6140
6141             Set_Scope                (Full_Der, Current_Scope);
6142             Set_Is_First_Subtype     (Full_Der,
6143                                        Is_First_Subtype (Derived_Type));
6144             Set_Has_Size_Clause      (Full_Der, False);
6145             Set_Has_Alignment_Clause (Full_Der, False);
6146             Set_Next_Entity          (Full_Der, Empty);
6147             Set_Has_Delayed_Freeze   (Full_Der);
6148             Set_Is_Frozen            (Full_Der, False);
6149             Set_Freeze_Node          (Full_Der, Empty);
6150             Set_Depends_On_Private   (Full_Der,
6151                                        Has_Private_Component (Full_Der));
6152             Set_Public_Status        (Full_Der);
6153          end if;
6154       end if;
6155
6156       Set_Has_Unknown_Discriminants (Derived_Type,
6157         Has_Unknown_Discriminants (Parent_Type));
6158
6159       if Is_Private_Type (Derived_Type) then
6160          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6161       end if;
6162
6163       if Is_Private_Type (Parent_Type)
6164         and then Base_Type (Parent_Type) = Parent_Type
6165         and then In_Open_Scopes (Scope (Parent_Type))
6166       then
6167          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6168
6169          if Is_Child_Unit (Scope (Current_Scope))
6170            and then Is_Completion
6171            and then In_Private_Part (Current_Scope)
6172            and then Scope (Parent_Type) /= Current_Scope
6173          then
6174             --  This is the unusual case where a type completed by a private
6175             --  derivation occurs within a package nested in a child unit, and
6176             --  the parent is declared in an ancestor. In this case, the full
6177             --  view of the parent type will become visible in the body of
6178             --  the enclosing child, and only then will the current type be
6179             --  possibly non-private. We build a underlying full view that
6180             --  will be installed when the enclosing child body is compiled.
6181
6182             Full_Der :=
6183               Make_Defining_Identifier (Sloc (Derived_Type),
6184                 Chars => Chars (Derived_Type));
6185             Set_Is_Itype (Full_Der);
6186             Build_Itype_Reference (Full_Der, N);
6187
6188             --  The full view will be used to swap entities on entry/exit to
6189             --  the body, and must appear in the entity list for the package.
6190
6191             Append_Entity (Full_Der, Scope (Derived_Type));
6192             Set_Has_Private_Declaration (Full_Der);
6193             Set_Has_Private_Declaration (Derived_Type);
6194             Set_Associated_Node_For_Itype (Full_Der, N);
6195             Set_Parent (Full_Der, Parent (Derived_Type));
6196             Full_P := Full_View (Parent_Type);
6197             Exchange_Declarations (Parent_Type);
6198             Copy_And_Build;
6199             Exchange_Declarations (Full_P);
6200             Set_Underlying_Full_View (Derived_Type, Full_Der);
6201          end if;
6202       end if;
6203    end Build_Derived_Private_Type;
6204
6205    -------------------------------
6206    -- Build_Derived_Record_Type --
6207    -------------------------------
6208
6209    --  1. INTRODUCTION
6210
6211    --  Ideally we would like to use the same model of type derivation for
6212    --  tagged and untagged record types. Unfortunately this is not quite
6213    --  possible because the semantics of representation clauses is different
6214    --  for tagged and untagged records under inheritance. Consider the
6215    --  following:
6216
6217    --     type R (...) is [tagged] record ... end record;
6218    --     type T (...) is new R (...) [with ...];
6219
6220    --  The representation clauses for T can specify a completely different
6221    --  record layout from R's. Hence the same component can be placed in two
6222    --  very different positions in objects of type T and R. If R and T are
6223    --  tagged types, representation clauses for T can only specify the layout
6224    --  of non inherited components, thus components that are common in R and T
6225    --  have the same position in objects of type R and T.
6226
6227    --  This has two implications. The first is that the entire tree for R's
6228    --  declaration needs to be copied for T in the untagged case, so that T
6229    --  can be viewed as a record type of its own with its own representation
6230    --  clauses. The second implication is the way we handle discriminants.
6231    --  Specifically, in the untagged case we need a way to communicate to Gigi
6232    --  what are the real discriminants in the record, while for the semantics
6233    --  we need to consider those introduced by the user to rename the
6234    --  discriminants in the parent type. This is handled by introducing the
6235    --  notion of stored discriminants. See below for more.
6236
6237    --  Fortunately the way regular components are inherited can be handled in
6238    --  the same way in tagged and untagged types.
6239
6240    --  To complicate things a bit more the private view of a private extension
6241    --  cannot be handled in the same way as the full view (for one thing the
6242    --  semantic rules are somewhat different). We will explain what differs
6243    --  below.
6244
6245    --  2. DISCRIMINANTS UNDER INHERITANCE
6246
6247    --  The semantic rules governing the discriminants of derived types are
6248    --  quite subtle.
6249
6250    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6251    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6252
6253    --  If parent type has discriminants, then the discriminants that are
6254    --  declared in the derived type are [3.4 (11)]:
6255
6256    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6257    --    there is one;
6258
6259    --  o Otherwise, each discriminant of the parent type (implicitly declared
6260    --    in the same order with the same specifications). In this case, the
6261    --    discriminants are said to be "inherited", or if unknown in the parent
6262    --    are also unknown in the derived type.
6263
6264    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6265
6266    --  o The parent subtype shall be constrained;
6267
6268    --  o If the parent type is not a tagged type, then each discriminant of
6269    --    the derived type shall be used in the constraint defining a parent
6270    --    subtype. [Implementation note: This ensures that the new discriminant
6271    --    can share storage with an existing discriminant.]
6272
6273    --  For the derived type each discriminant of the parent type is either
6274    --  inherited, constrained to equal some new discriminant of the derived
6275    --  type, or constrained to the value of an expression.
6276
6277    --  When inherited or constrained to equal some new discriminant, the
6278    --  parent discriminant and the discriminant of the derived type are said
6279    --  to "correspond".
6280
6281    --  If a discriminant of the parent type is constrained to a specific value
6282    --  in the derived type definition, then the discriminant is said to be
6283    --  "specified" by that derived type definition.
6284
6285    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6286
6287    --  We have spoken about stored discriminants in point 1 (introduction)
6288    --  above. There are two sort of stored discriminants: implicit and
6289    --  explicit. As long as the derived type inherits the same discriminants as
6290    --  the root record type, stored discriminants are the same as regular
6291    --  discriminants, and are said to be implicit. However, if any discriminant
6292    --  in the root type was renamed in the derived type, then the derived
6293    --  type will contain explicit stored discriminants. Explicit stored
6294    --  discriminants are discriminants in addition to the semantically visible
6295    --  discriminants defined for the derived type. Stored discriminants are
6296    --  used by Gigi to figure out what are the physical discriminants in
6297    --  objects of the derived type (see precise definition in einfo.ads).
6298    --  As an example, consider the following:
6299
6300    --           type R  (D1, D2, D3 : Int) is record ... end record;
6301    --           type T1 is new R;
6302    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6303    --           type T3 is new T2;
6304    --           type T4 (Y : Int) is new T3 (Y, 99);
6305
6306    --  The following table summarizes the discriminants and stored
6307    --  discriminants in R and T1 through T4.
6308
6309    --   Type      Discrim     Stored Discrim  Comment
6310    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6311    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6312    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6313    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6314    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6315
6316    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6317    --  find the corresponding discriminant in the parent type, while
6318    --  Original_Record_Component (abbreviated ORC below), the actual physical
6319    --  component that is renamed. Finally the field Is_Completely_Hidden
6320    --  (abbreviated ICH below) is set for all explicit stored discriminants
6321    --  (see einfo.ads for more info). For the above example this gives:
6322
6323    --                 Discrim     CD        ORC     ICH
6324    --                 ^^^^^^^     ^^        ^^^     ^^^
6325    --                 D1 in R    empty     itself    no
6326    --                 D2 in R    empty     itself    no
6327    --                 D3 in R    empty     itself    no
6328
6329    --                 D1 in T1  D1 in R    itself    no
6330    --                 D2 in T1  D2 in R    itself    no
6331    --                 D3 in T1  D3 in R    itself    no
6332
6333    --                 X1 in T2  D3 in T1  D3 in T2   no
6334    --                 X2 in T2  D1 in T1  D1 in T2   no
6335    --                 D1 in T2   empty    itself    yes
6336    --                 D2 in T2   empty    itself    yes
6337    --                 D3 in T2   empty    itself    yes
6338
6339    --                 X1 in T3  X1 in T2  D3 in T3   no
6340    --                 X2 in T3  X2 in T2  D1 in T3   no
6341    --                 D1 in T3   empty    itself    yes
6342    --                 D2 in T3   empty    itself    yes
6343    --                 D3 in T3   empty    itself    yes
6344
6345    --                 Y  in T4  X1 in T3  D3 in T3   no
6346    --                 D1 in T3   empty    itself    yes
6347    --                 D2 in T3   empty    itself    yes
6348    --                 D3 in T3   empty    itself    yes
6349
6350    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6351
6352    --  Type derivation for tagged types is fairly straightforward. If no
6353    --  discriminants are specified by the derived type, these are inherited
6354    --  from the parent. No explicit stored discriminants are ever necessary.
6355    --  The only manipulation that is done to the tree is that of adding a
6356    --  _parent field with parent type and constrained to the same constraint
6357    --  specified for the parent in the derived type definition. For instance:
6358
6359    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6360    --           type T1 is new R with null record;
6361    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6362
6363    --  are changed into:
6364
6365    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6366    --              _parent : R (D1, D2, D3);
6367    --           end record;
6368
6369    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6370    --              _parent : T1 (X2, 88, X1);
6371    --           end record;
6372
6373    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6374    --  ORC and ICH fields are:
6375
6376    --                 Discrim     CD        ORC     ICH
6377    --                 ^^^^^^^     ^^        ^^^     ^^^
6378    --                 D1 in R    empty     itself    no
6379    --                 D2 in R    empty     itself    no
6380    --                 D3 in R    empty     itself    no
6381
6382    --                 D1 in T1  D1 in R    D1 in R   no
6383    --                 D2 in T1  D2 in R    D2 in R   no
6384    --                 D3 in T1  D3 in R    D3 in R   no
6385
6386    --                 X1 in T2  D3 in T1   D3 in R   no
6387    --                 X2 in T2  D1 in T1   D1 in R   no
6388
6389    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6390    --
6391    --  Regardless of whether we dealing with a tagged or untagged type
6392    --  we will transform all derived type declarations of the form
6393    --
6394    --               type T is new R (...) [with ...];
6395    --  or
6396    --               subtype S is R (...);
6397    --               type T is new S [with ...];
6398    --  into
6399    --               type BT is new R [with ...];
6400    --               subtype T is BT (...);
6401    --
6402    --  That is, the base derived type is constrained only if it has no
6403    --  discriminants. The reason for doing this is that GNAT's semantic model
6404    --  assumes that a base type with discriminants is unconstrained.
6405    --
6406    --  Note that, strictly speaking, the above transformation is not always
6407    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6408    --
6409    --       procedure B34011A is
6410    --          type REC (D : integer := 0) is record
6411    --             I : Integer;
6412    --          end record;
6413
6414    --          package P is
6415    --             type T6 is new Rec;
6416    --             function F return T6;
6417    --          end P;
6418
6419    --          use P;
6420    --          package Q6 is
6421    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6422    --          end Q6;
6423    --
6424    --  The definition of Q6.U is illegal. However transforming Q6.U into
6425
6426    --             type BaseU is new T6;
6427    --             subtype U is BaseU (Q6.F.I)
6428
6429    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6430    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6431    --  the transformation described above.
6432
6433    --  There is another instance where the above transformation is incorrect.
6434    --  Consider:
6435
6436    --          package Pack is
6437    --             type Base (D : Integer) is tagged null record;
6438    --             procedure P (X : Base);
6439
6440    --             type Der is new Base (2) with null record;
6441    --             procedure P (X : Der);
6442    --          end Pack;
6443
6444    --  Then the above transformation turns this into
6445
6446    --             type Der_Base is new Base with null record;
6447    --             --  procedure P (X : Base) is implicitly inherited here
6448    --             --  as procedure P (X : Der_Base).
6449
6450    --             subtype Der is Der_Base (2);
6451    --             procedure P (X : Der);
6452    --             --  The overriding of P (X : Der_Base) is illegal since we
6453    --             --  have a parameter conformance problem.
6454
6455    --  To get around this problem, after having semantically processed Der_Base
6456    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6457    --  Discriminant_Constraint from Der so that when parameter conformance is
6458    --  checked when P is overridden, no semantic errors are flagged.
6459
6460    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6461
6462    --  Regardless of whether we are dealing with a tagged or untagged type
6463    --  we will transform all derived type declarations of the form
6464
6465    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6466    --               type T is new R [with ...];
6467    --  into
6468    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6469
6470    --  The reason for such transformation is that it allows us to implement a
6471    --  very clean form of component inheritance as explained below.
6472
6473    --  Note that this transformation is not achieved by direct tree rewriting
6474    --  and manipulation, but rather by redoing the semantic actions that the
6475    --  above transformation will entail. This is done directly in routine
6476    --  Inherit_Components.
6477
6478    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
6479
6480    --  In both tagged and untagged derived types, regular non discriminant
6481    --  components are inherited in the derived type from the parent type. In
6482    --  the absence of discriminants component, inheritance is straightforward
6483    --  as components can simply be copied from the parent.
6484
6485    --  If the parent has discriminants, inheriting components constrained with
6486    --  these discriminants requires caution. Consider the following example:
6487
6488    --      type R  (D1, D2 : Positive) is [tagged] record
6489    --         S : String (D1 .. D2);
6490    --      end record;
6491
6492    --      type T1                is new R        [with null record];
6493    --      type T2 (X : positive) is new R (1, X) [with null record];
6494
6495    --  As explained in 6. above, T1 is rewritten as
6496    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
6497    --  which makes the treatment for T1 and T2 identical.
6498
6499    --  What we want when inheriting S, is that references to D1 and D2 in R are
6500    --  replaced with references to their correct constraints, i.e. D1 and D2 in
6501    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
6502    --  with either discriminant references in the derived type or expressions.
6503    --  This replacement is achieved as follows: before inheriting R's
6504    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
6505    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
6506    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
6507    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
6508    --  by String (1 .. X).
6509
6510    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
6511
6512    --  We explain here the rules governing private type extensions relevant to
6513    --  type derivation. These rules are explained on the following example:
6514
6515    --      type D [(...)] is new A [(...)] with private;      <-- partial view
6516    --      type D [(...)] is new P [(...)] with null record;  <-- full view
6517
6518    --  Type A is called the ancestor subtype of the private extension.
6519    --  Type P is the parent type of the full view of the private extension. It
6520    --  must be A or a type derived from A.
6521
6522    --  The rules concerning the discriminants of private type extensions are
6523    --  [7.3(10-13)]:
6524
6525    --  o If a private extension inherits known discriminants from the ancestor
6526    --    subtype, then the full view shall also inherit its discriminants from
6527    --    the ancestor subtype and the parent subtype of the full view shall be
6528    --    constrained if and only if the ancestor subtype is constrained.
6529
6530    --  o If a partial view has unknown discriminants, then the full view may
6531    --    define a definite or an indefinite subtype, with or without
6532    --    discriminants.
6533
6534    --  o If a partial view has neither known nor unknown discriminants, then
6535    --    the full view shall define a definite subtype.
6536
6537    --  o If the ancestor subtype of a private extension has constrained
6538    --    discriminants, then the parent subtype of the full view shall impose a
6539    --    statically matching constraint on those discriminants.
6540
6541    --  This means that only the following forms of private extensions are
6542    --  allowed:
6543
6544    --      type D is new A with private;      <-- partial view
6545    --      type D is new P with null record;  <-- full view
6546
6547    --  If A has no discriminants than P has no discriminants, otherwise P must
6548    --  inherit A's discriminants.
6549
6550    --      type D is new A (...) with private;      <-- partial view
6551    --      type D is new P (:::) with null record;  <-- full view
6552
6553    --  P must inherit A's discriminants and (...) and (:::) must statically
6554    --  match.
6555
6556    --      subtype A is R (...);
6557    --      type D is new A with private;      <-- partial view
6558    --      type D is new P with null record;  <-- full view
6559
6560    --  P must have inherited R's discriminants and must be derived from A or
6561    --  any of its subtypes.
6562
6563    --      type D (..) is new A with private;              <-- partial view
6564    --      type D (..) is new P [(:::)] with null record;  <-- full view
6565
6566    --  No specific constraints on P's discriminants or constraint (:::).
6567    --  Note that A can be unconstrained, but the parent subtype P must either
6568    --  be constrained or (:::) must be present.
6569
6570    --      type D (..) is new A [(...)] with private;      <-- partial view
6571    --      type D (..) is new P [(:::)] with null record;  <-- full view
6572
6573    --  P's constraints on A's discriminants must statically match those
6574    --  imposed by (...).
6575
6576    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
6577
6578    --  The full view of a private extension is handled exactly as described
6579    --  above. The model chose for the private view of a private extension is
6580    --  the same for what concerns discriminants (i.e. they receive the same
6581    --  treatment as in the tagged case). However, the private view of the
6582    --  private extension always inherits the components of the parent base,
6583    --  without replacing any discriminant reference. Strictly speaking this is
6584    --  incorrect. However, Gigi never uses this view to generate code so this
6585    --  is a purely semantic issue. In theory, a set of transformations similar
6586    --  to those given in 5. and 6. above could be applied to private views of
6587    --  private extensions to have the same model of component inheritance as
6588    --  for non private extensions. However, this is not done because it would
6589    --  further complicate private type processing. Semantically speaking, this
6590    --  leaves us in an uncomfortable situation. As an example consider:
6591
6592    --          package Pack is
6593    --             type R (D : integer) is tagged record
6594    --                S : String (1 .. D);
6595    --             end record;
6596    --             procedure P (X : R);
6597    --             type T is new R (1) with private;
6598    --          private
6599    --             type T is new R (1) with null record;
6600    --          end;
6601
6602    --  This is transformed into:
6603
6604    --          package Pack is
6605    --             type R (D : integer) is tagged record
6606    --                S : String (1 .. D);
6607    --             end record;
6608    --             procedure P (X : R);
6609    --             type T is new R (1) with private;
6610    --          private
6611    --             type BaseT is new R with null record;
6612    --             subtype  T is BaseT (1);
6613    --          end;
6614
6615    --  (strictly speaking the above is incorrect Ada)
6616
6617    --  From the semantic standpoint the private view of private extension T
6618    --  should be flagged as constrained since one can clearly have
6619    --
6620    --             Obj : T;
6621    --
6622    --  in a unit withing Pack. However, when deriving subprograms for the
6623    --  private view of private extension T, T must be seen as unconstrained
6624    --  since T has discriminants (this is a constraint of the current
6625    --  subprogram derivation model). Thus, when processing the private view of
6626    --  a private extension such as T, we first mark T as unconstrained, we
6627    --  process it, we perform program derivation and just before returning from
6628    --  Build_Derived_Record_Type we mark T as constrained.
6629
6630    --  ??? Are there are other uncomfortable cases that we will have to
6631    --      deal with.
6632
6633    --  10. RECORD_TYPE_WITH_PRIVATE complications
6634
6635    --  Types that are derived from a visible record type and have a private
6636    --  extension present other peculiarities. They behave mostly like private
6637    --  types, but if they have primitive operations defined, these will not
6638    --  have the proper signatures for further inheritance, because other
6639    --  primitive operations will use the implicit base that we define for
6640    --  private derivations below. This affect subprogram inheritance (see
6641    --  Derive_Subprograms for details). We also derive the implicit base from
6642    --  the base type of the full view, so that the implicit base is a record
6643    --  type and not another private type, This avoids infinite loops.
6644
6645    procedure Build_Derived_Record_Type
6646      (N            : Node_Id;
6647       Parent_Type  : Entity_Id;
6648       Derived_Type : Entity_Id;
6649       Derive_Subps : Boolean := True)
6650    is
6651       Loc          : constant Source_Ptr := Sloc (N);
6652       Parent_Base  : Entity_Id;
6653       Type_Def     : Node_Id;
6654       Indic        : Node_Id;
6655       Discrim      : Entity_Id;
6656       Last_Discrim : Entity_Id;
6657       Constrs      : Elist_Id;
6658
6659       Discs : Elist_Id := New_Elmt_List;
6660       --  An empty Discs list means that there were no constraints in the
6661       --  subtype indication or that there was an error processing it.
6662
6663       Assoc_List : Elist_Id;
6664       New_Discrs : Elist_Id;
6665       New_Base   : Entity_Id;
6666       New_Decl   : Node_Id;
6667       New_Indic  : Node_Id;
6668
6669       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
6670       Discriminant_Specs : constant Boolean :=
6671                              Present (Discriminant_Specifications (N));
6672       Private_Extension  : constant Boolean :=
6673                              Nkind (N) = N_Private_Extension_Declaration;
6674
6675       Constraint_Present : Boolean;
6676       Inherit_Discrims   : Boolean := False;
6677       Save_Etype         : Entity_Id;
6678       Save_Discr_Constr  : Elist_Id;
6679       Save_Next_Entity   : Entity_Id;
6680
6681    begin
6682       if Ekind (Parent_Type) = E_Record_Type_With_Private
6683         and then Present (Full_View (Parent_Type))
6684         and then Has_Discriminants (Parent_Type)
6685       then
6686          Parent_Base := Base_Type (Full_View (Parent_Type));
6687       else
6688          Parent_Base := Base_Type (Parent_Type);
6689       end if;
6690
6691       --  Before we start the previously documented transformations, here is
6692       --  little fix for size and alignment of tagged types. Normally when we
6693       --  derive type D from type P, we copy the size and alignment of P as the
6694       --  default for D, and in the absence of explicit representation clauses
6695       --  for D, the size and alignment are indeed the same as the parent.
6696
6697       --  But this is wrong for tagged types, since fields may be added, and
6698       --  the default size may need to be larger, and the default alignment may
6699       --  need to be larger.
6700
6701       --  We therefore reset the size and alignment fields in the tagged case.
6702       --  Note that the size and alignment will in any case be at least as
6703       --  large as the parent type (since the derived type has a copy of the
6704       --  parent type in the _parent field)
6705
6706       --  The type is also marked as being tagged here, which is needed when
6707       --  processing components with a self-referential anonymous access type
6708       --  in the call to Check_Anonymous_Access_Components below. Note that
6709       --  this flag is also set later on for completeness.
6710
6711       if Is_Tagged then
6712          Set_Is_Tagged_Type (Derived_Type);
6713          Init_Size_Align    (Derived_Type);
6714       end if;
6715
6716       --  STEP 0a: figure out what kind of derived type declaration we have
6717
6718       if Private_Extension then
6719          Type_Def := N;
6720          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
6721
6722       else
6723          Type_Def := Type_Definition (N);
6724
6725          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
6726          --  Parent_Base can be a private type or private extension. However,
6727          --  for tagged types with an extension the newly added fields are
6728          --  visible and hence the Derived_Type is always an E_Record_Type.
6729          --  (except that the parent may have its own private fields).
6730          --  For untagged types we preserve the Ekind of the Parent_Base.
6731
6732          if Present (Record_Extension_Part (Type_Def)) then
6733             Set_Ekind (Derived_Type, E_Record_Type);
6734
6735             --  Create internal access types for components with anonymous
6736             --  access types.
6737
6738             if Ada_Version >= Ada_2005 then
6739                Check_Anonymous_Access_Components
6740                  (N, Derived_Type, Derived_Type,
6741                    Component_List (Record_Extension_Part (Type_Def)));
6742             end if;
6743
6744          else
6745             Set_Ekind (Derived_Type, Ekind (Parent_Base));
6746          end if;
6747       end if;
6748
6749       --  Indic can either be an N_Identifier if the subtype indication
6750       --  contains no constraint or an N_Subtype_Indication if the subtype
6751       --  indication has a constraint.
6752
6753       Indic := Subtype_Indication (Type_Def);
6754       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
6755
6756       --  Check that the type has visible discriminants. The type may be
6757       --  a private type with unknown discriminants whose full view has
6758       --  discriminants which are invisible.
6759
6760       if Constraint_Present then
6761          if not Has_Discriminants (Parent_Base)
6762            or else
6763              (Has_Unknown_Discriminants (Parent_Base)
6764                 and then Is_Private_Type (Parent_Base))
6765          then
6766             Error_Msg_N
6767               ("invalid constraint: type has no discriminant",
6768                  Constraint (Indic));
6769
6770             Constraint_Present := False;
6771             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6772
6773          elsif Is_Constrained (Parent_Type) then
6774             Error_Msg_N
6775                ("invalid constraint: parent type is already constrained",
6776                   Constraint (Indic));
6777
6778             Constraint_Present := False;
6779             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6780          end if;
6781       end if;
6782
6783       --  STEP 0b: If needed, apply transformation given in point 5. above
6784
6785       if not Private_Extension
6786         and then Has_Discriminants (Parent_Type)
6787         and then not Discriminant_Specs
6788         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
6789       then
6790          --  First, we must analyze the constraint (see comment in point 5.)
6791
6792          if Constraint_Present then
6793             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
6794
6795             if Has_Discriminants (Derived_Type)
6796               and then Has_Private_Declaration (Derived_Type)
6797               and then Present (Discriminant_Constraint (Derived_Type))
6798             then
6799                --  Verify that constraints of the full view statically match
6800                --  those given in the partial view.
6801
6802                declare
6803                   C1, C2 : Elmt_Id;
6804
6805                begin
6806                   C1 := First_Elmt (New_Discrs);
6807                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
6808                   while Present (C1) and then Present (C2) loop
6809                      if Fully_Conformant_Expressions (Node (C1), Node (C2))
6810                        or else
6811                          (Is_OK_Static_Expression (Node (C1))
6812                             and then
6813                           Is_OK_Static_Expression (Node (C2))
6814                             and then
6815                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
6816                      then
6817                         null;
6818
6819                      else
6820                         Error_Msg_N (
6821                           "constraint not conformant to previous declaration",
6822                              Node (C1));
6823                      end if;
6824
6825                      Next_Elmt (C1);
6826                      Next_Elmt (C2);
6827                   end loop;
6828                end;
6829             end if;
6830          end if;
6831
6832          --  Insert and analyze the declaration for the unconstrained base type
6833
6834          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
6835
6836          New_Decl :=
6837            Make_Full_Type_Declaration (Loc,
6838               Defining_Identifier => New_Base,
6839               Type_Definition     =>
6840                 Make_Derived_Type_Definition (Loc,
6841                   Abstract_Present      => Abstract_Present (Type_Def),
6842                   Limited_Present       => Limited_Present (Type_Def),
6843                   Subtype_Indication    =>
6844                     New_Occurrence_Of (Parent_Base, Loc),
6845                   Record_Extension_Part =>
6846                     Relocate_Node (Record_Extension_Part (Type_Def)),
6847                   Interface_List        => Interface_List (Type_Def)));
6848
6849          Set_Parent (New_Decl, Parent (N));
6850          Mark_Rewrite_Insertion (New_Decl);
6851          Insert_Before (N, New_Decl);
6852
6853          --  In the extension case, make sure ancestor is frozen appropriately
6854          --  (see also non-discriminated case below).
6855
6856          if Present (Record_Extension_Part (Type_Def))
6857            or else Is_Interface (Parent_Base)
6858          then
6859             Freeze_Before (New_Decl, Parent_Type);
6860          end if;
6861
6862          --  Note that this call passes False for the Derive_Subps parameter
6863          --  because subprogram derivation is deferred until after creating
6864          --  the subtype (see below).
6865
6866          Build_Derived_Type
6867            (New_Decl, Parent_Base, New_Base,
6868             Is_Completion => True, Derive_Subps => False);
6869
6870          --  ??? This needs re-examination to determine whether the
6871          --  above call can simply be replaced by a call to Analyze.
6872
6873          Set_Analyzed (New_Decl);
6874
6875          --  Insert and analyze the declaration for the constrained subtype
6876
6877          if Constraint_Present then
6878             New_Indic :=
6879               Make_Subtype_Indication (Loc,
6880                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6881                 Constraint   => Relocate_Node (Constraint (Indic)));
6882
6883          else
6884             declare
6885                Constr_List : constant List_Id := New_List;
6886                C           : Elmt_Id;
6887                Expr        : Node_Id;
6888
6889             begin
6890                C := First_Elmt (Discriminant_Constraint (Parent_Type));
6891                while Present (C) loop
6892                   Expr := Node (C);
6893
6894                   --  It is safe here to call New_Copy_Tree since
6895                   --  Force_Evaluation was called on each constraint in
6896                   --  Build_Discriminant_Constraints.
6897
6898                   Append (New_Copy_Tree (Expr), To => Constr_List);
6899
6900                   Next_Elmt (C);
6901                end loop;
6902
6903                New_Indic :=
6904                  Make_Subtype_Indication (Loc,
6905                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6906                    Constraint   =>
6907                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
6908             end;
6909          end if;
6910
6911          Rewrite (N,
6912            Make_Subtype_Declaration (Loc,
6913              Defining_Identifier => Derived_Type,
6914              Subtype_Indication  => New_Indic));
6915
6916          Analyze (N);
6917
6918          --  Derivation of subprograms must be delayed until the full subtype
6919          --  has been established to ensure proper overriding of subprograms
6920          --  inherited by full types. If the derivations occurred as part of
6921          --  the call to Build_Derived_Type above, then the check for type
6922          --  conformance would fail because earlier primitive subprograms
6923          --  could still refer to the full type prior the change to the new
6924          --  subtype and hence would not match the new base type created here.
6925
6926          Derive_Subprograms (Parent_Type, Derived_Type);
6927
6928          --  For tagged types the Discriminant_Constraint of the new base itype
6929          --  is inherited from the first subtype so that no subtype conformance
6930          --  problem arise when the first subtype overrides primitive
6931          --  operations inherited by the implicit base type.
6932
6933          if Is_Tagged then
6934             Set_Discriminant_Constraint
6935               (New_Base, Discriminant_Constraint (Derived_Type));
6936          end if;
6937
6938          return;
6939       end if;
6940
6941       --  If we get here Derived_Type will have no discriminants or it will be
6942       --  a discriminated unconstrained base type.
6943
6944       --  STEP 1a: perform preliminary actions/checks for derived tagged types
6945
6946       if Is_Tagged then
6947
6948          --  The parent type is frozen for non-private extensions (RM 13.14(7))
6949          --  The declaration of a specific descendant of an interface type
6950          --  freezes the interface type (RM 13.14).
6951
6952          if not Private_Extension or else Is_Interface (Parent_Base) then
6953             Freeze_Before (N, Parent_Type);
6954          end if;
6955
6956          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
6957          --  cannot be declared at a deeper level than its parent type is
6958          --  removed. The check on derivation within a generic body is also
6959          --  relaxed, but there's a restriction that a derived tagged type
6960          --  cannot be declared in a generic body if it's derived directly
6961          --  or indirectly from a formal type of that generic.
6962
6963          if Ada_Version >= Ada_2005 then
6964             if Present (Enclosing_Generic_Body (Derived_Type)) then
6965                declare
6966                   Ancestor_Type : Entity_Id;
6967
6968                begin
6969                   --  Check to see if any ancestor of the derived type is a
6970                   --  formal type.
6971
6972                   Ancestor_Type := Parent_Type;
6973                   while not Is_Generic_Type (Ancestor_Type)
6974                     and then Etype (Ancestor_Type) /= Ancestor_Type
6975                   loop
6976                      Ancestor_Type := Etype (Ancestor_Type);
6977                   end loop;
6978
6979                   --  If the derived type does have a formal type as an
6980                   --  ancestor, then it's an error if the derived type is
6981                   --  declared within the body of the generic unit that
6982                   --  declares the formal type in its generic formal part. It's
6983                   --  sufficient to check whether the ancestor type is declared
6984                   --  inside the same generic body as the derived type (such as
6985                   --  within a nested generic spec), in which case the
6986                   --  derivation is legal. If the formal type is declared
6987                   --  outside of that generic body, then it's guaranteed that
6988                   --  the derived type is declared within the generic body of
6989                   --  the generic unit declaring the formal type.
6990
6991                   if Is_Generic_Type (Ancestor_Type)
6992                     and then Enclosing_Generic_Body (Ancestor_Type) /=
6993                                Enclosing_Generic_Body (Derived_Type)
6994                   then
6995                      Error_Msg_NE
6996                        ("parent type of& must not be descendant of formal type"
6997                           & " of an enclosing generic body",
6998                             Indic, Derived_Type);
6999                   end if;
7000                end;
7001             end if;
7002
7003          elsif Type_Access_Level (Derived_Type) /=
7004                  Type_Access_Level (Parent_Type)
7005            and then not Is_Generic_Type (Derived_Type)
7006          then
7007             if Is_Controlled (Parent_Type) then
7008                Error_Msg_N
7009                  ("controlled type must be declared at the library level",
7010                   Indic);
7011             else
7012                Error_Msg_N
7013                  ("type extension at deeper accessibility level than parent",
7014                   Indic);
7015             end if;
7016
7017          else
7018             declare
7019                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
7020
7021             begin
7022                if Present (GB)
7023                  and then GB /= Enclosing_Generic_Body (Parent_Base)
7024                then
7025                   Error_Msg_NE
7026                     ("parent type of& must not be outside generic body"
7027                        & " (RM 3.9.1(4))",
7028                          Indic, Derived_Type);
7029                end if;
7030             end;
7031          end if;
7032       end if;
7033
7034       --  Ada 2005 (AI-251)
7035
7036       if Ada_Version >= Ada_2005 and then Is_Tagged then
7037
7038          --  "The declaration of a specific descendant of an interface type
7039          --  freezes the interface type" (RM 13.14).
7040
7041          declare
7042             Iface : Node_Id;
7043          begin
7044             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7045                Iface := First (Interface_List (Type_Def));
7046                while Present (Iface) loop
7047                   Freeze_Before (N, Etype (Iface));
7048                   Next (Iface);
7049                end loop;
7050             end if;
7051          end;
7052       end if;
7053
7054       --  STEP 1b : preliminary cleanup of the full view of private types
7055
7056       --  If the type is already marked as having discriminants, then it's the
7057       --  completion of a private type or private extension and we need to
7058       --  retain the discriminants from the partial view if the current
7059       --  declaration has Discriminant_Specifications so that we can verify
7060       --  conformance. However, we must remove any existing components that
7061       --  were inherited from the parent (and attached in Copy_And_Swap)
7062       --  because the full type inherits all appropriate components anyway, and
7063       --  we do not want the partial view's components interfering.
7064
7065       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7066          Discrim := First_Discriminant (Derived_Type);
7067          loop
7068             Last_Discrim := Discrim;
7069             Next_Discriminant (Discrim);
7070             exit when No (Discrim);
7071          end loop;
7072
7073          Set_Last_Entity (Derived_Type, Last_Discrim);
7074
7075       --  In all other cases wipe out the list of inherited components (even
7076       --  inherited discriminants), it will be properly rebuilt here.
7077
7078       else
7079          Set_First_Entity (Derived_Type, Empty);
7080          Set_Last_Entity  (Derived_Type, Empty);
7081       end if;
7082
7083       --  STEP 1c: Initialize some flags for the Derived_Type
7084
7085       --  The following flags must be initialized here so that
7086       --  Process_Discriminants can check that discriminants of tagged types do
7087       --  not have a default initial value and that access discriminants are
7088       --  only specified for limited records. For completeness, these flags are
7089       --  also initialized along with all the other flags below.
7090
7091       --  AI-419: Limitedness is not inherited from an interface parent, so to
7092       --  be limited in that case the type must be explicitly declared as
7093       --  limited. However, task and protected interfaces are always limited.
7094
7095       if Limited_Present (Type_Def) then
7096          Set_Is_Limited_Record (Derived_Type);
7097
7098       elsif Is_Limited_Record (Parent_Type)
7099         or else (Present (Full_View (Parent_Type))
7100                    and then Is_Limited_Record (Full_View (Parent_Type)))
7101       then
7102          if not Is_Interface (Parent_Type)
7103            or else Is_Synchronized_Interface (Parent_Type)
7104            or else Is_Protected_Interface (Parent_Type)
7105            or else Is_Task_Interface (Parent_Type)
7106          then
7107             Set_Is_Limited_Record (Derived_Type);
7108          end if;
7109       end if;
7110
7111       --  STEP 2a: process discriminants of derived type if any
7112
7113       Push_Scope (Derived_Type);
7114
7115       if Discriminant_Specs then
7116          Set_Has_Unknown_Discriminants (Derived_Type, False);
7117
7118          --  The following call initializes fields Has_Discriminants and
7119          --  Discriminant_Constraint, unless we are processing the completion
7120          --  of a private type declaration.
7121
7122          Check_Or_Process_Discriminants (N, Derived_Type);
7123
7124          --  For untagged types, the constraint on the Parent_Type must be
7125          --  present and is used to rename the discriminants.
7126
7127          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7128             Error_Msg_N ("untagged parent must have discriminants", Indic);
7129
7130          elsif not Is_Tagged and then not Constraint_Present then
7131             Error_Msg_N
7132               ("discriminant constraint needed for derived untagged records",
7133                Indic);
7134
7135          --  Otherwise the parent subtype must be constrained unless we have a
7136          --  private extension.
7137
7138          elsif not Constraint_Present
7139            and then not Private_Extension
7140            and then not Is_Constrained (Parent_Type)
7141          then
7142             Error_Msg_N
7143               ("unconstrained type not allowed in this context", Indic);
7144
7145          elsif Constraint_Present then
7146             --  The following call sets the field Corresponding_Discriminant
7147             --  for the discriminants in the Derived_Type.
7148
7149             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7150
7151             --  For untagged types all new discriminants must rename
7152             --  discriminants in the parent. For private extensions new
7153             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7154
7155             Discrim := First_Discriminant (Derived_Type);
7156             while Present (Discrim) loop
7157                if not Is_Tagged
7158                  and then No (Corresponding_Discriminant (Discrim))
7159                then
7160                   Error_Msg_N
7161                     ("new discriminants must constrain old ones", Discrim);
7162
7163                elsif Private_Extension
7164                  and then Present (Corresponding_Discriminant (Discrim))
7165                then
7166                   Error_Msg_N
7167                     ("only static constraints allowed for parent"
7168                      & " discriminants in the partial view", Indic);
7169                   exit;
7170                end if;
7171
7172                --  If a new discriminant is used in the constraint, then its
7173                --  subtype must be statically compatible with the parent
7174                --  discriminant's subtype (3.7(15)).
7175
7176                if Present (Corresponding_Discriminant (Discrim))
7177                  and then
7178                    not Subtypes_Statically_Compatible
7179                          (Etype (Discrim),
7180                           Etype (Corresponding_Discriminant (Discrim)))
7181                then
7182                   Error_Msg_N
7183                     ("subtype must be compatible with parent discriminant",
7184                      Discrim);
7185                end if;
7186
7187                Next_Discriminant (Discrim);
7188             end loop;
7189
7190             --  Check whether the constraints of the full view statically
7191             --  match those imposed by the parent subtype [7.3(13)].
7192
7193             if Present (Stored_Constraint (Derived_Type)) then
7194                declare
7195                   C1, C2 : Elmt_Id;
7196
7197                begin
7198                   C1 := First_Elmt (Discs);
7199                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7200                   while Present (C1) and then Present (C2) loop
7201                      if not
7202                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7203                      then
7204                         Error_Msg_N
7205                           ("not conformant with previous declaration",
7206                            Node (C1));
7207                      end if;
7208
7209                      Next_Elmt (C1);
7210                      Next_Elmt (C2);
7211                   end loop;
7212                end;
7213             end if;
7214          end if;
7215
7216       --  STEP 2b: No new discriminants, inherit discriminants if any
7217
7218       else
7219          if Private_Extension then
7220             Set_Has_Unknown_Discriminants
7221               (Derived_Type,
7222                Has_Unknown_Discriminants (Parent_Type)
7223                  or else Unknown_Discriminants_Present (N));
7224
7225          --  The partial view of the parent may have unknown discriminants,
7226          --  but if the full view has discriminants and the parent type is
7227          --  in scope they must be inherited.
7228
7229          elsif Has_Unknown_Discriminants (Parent_Type)
7230            and then
7231             (not Has_Discriminants (Parent_Type)
7232               or else not In_Open_Scopes (Scope (Parent_Type)))
7233          then
7234             Set_Has_Unknown_Discriminants (Derived_Type);
7235          end if;
7236
7237          if not Has_Unknown_Discriminants (Derived_Type)
7238            and then not Has_Unknown_Discriminants (Parent_Base)
7239            and then Has_Discriminants (Parent_Type)
7240          then
7241             Inherit_Discrims := True;
7242             Set_Has_Discriminants
7243               (Derived_Type, True);
7244             Set_Discriminant_Constraint
7245               (Derived_Type, Discriminant_Constraint (Parent_Base));
7246          end if;
7247
7248          --  The following test is true for private types (remember
7249          --  transformation 5. is not applied to those) and in an error
7250          --  situation.
7251
7252          if Constraint_Present then
7253             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7254          end if;
7255
7256          --  For now mark a new derived type as constrained only if it has no
7257          --  discriminants. At the end of Build_Derived_Record_Type we properly
7258          --  set this flag in the case of private extensions. See comments in
7259          --  point 9. just before body of Build_Derived_Record_Type.
7260
7261          Set_Is_Constrained
7262            (Derived_Type,
7263             not (Inherit_Discrims
7264                    or else Has_Unknown_Discriminants (Derived_Type)));
7265       end if;
7266
7267       --  STEP 3: initialize fields of derived type
7268
7269       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7270       Set_Stored_Constraint (Derived_Type, No_Elist);
7271
7272       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7273       --  but cannot be interfaces
7274
7275       if not Private_Extension
7276          and then Ekind (Derived_Type) /= E_Private_Type
7277          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7278       then
7279          if Interface_Present (Type_Def) then
7280             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7281          end if;
7282
7283          Set_Interfaces (Derived_Type, No_Elist);
7284       end if;
7285
7286       --  Fields inherited from the Parent_Type
7287
7288       Set_Discard_Names
7289         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
7290       Set_Has_Specified_Layout
7291         (Derived_Type, Has_Specified_Layout (Parent_Type));
7292       Set_Is_Limited_Composite
7293         (Derived_Type, Is_Limited_Composite (Parent_Type));
7294       Set_Is_Private_Composite
7295         (Derived_Type, Is_Private_Composite (Parent_Type));
7296
7297       --  Fields inherited from the Parent_Base
7298
7299       Set_Has_Controlled_Component
7300         (Derived_Type, Has_Controlled_Component (Parent_Base));
7301       Set_Has_Non_Standard_Rep
7302         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7303       Set_Has_Primitive_Operations
7304         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7305
7306       --  Fields inherited from the Parent_Base in the non-private case
7307
7308       if Ekind (Derived_Type) = E_Record_Type then
7309          Set_Has_Complex_Representation
7310            (Derived_Type, Has_Complex_Representation (Parent_Base));
7311       end if;
7312
7313       --  Fields inherited from the Parent_Base for record types
7314
7315       if Is_Record_Type (Derived_Type) then
7316
7317          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7318          --  Parent_Base can be a private type or private extension.
7319
7320          if Present (Full_View (Parent_Base)) then
7321             Set_OK_To_Reorder_Components
7322               (Derived_Type,
7323                OK_To_Reorder_Components (Full_View (Parent_Base)));
7324             Set_Reverse_Bit_Order
7325               (Derived_Type, Reverse_Bit_Order (Full_View (Parent_Base)));
7326          else
7327             Set_OK_To_Reorder_Components
7328               (Derived_Type, OK_To_Reorder_Components (Parent_Base));
7329             Set_Reverse_Bit_Order
7330               (Derived_Type, Reverse_Bit_Order (Parent_Base));
7331          end if;
7332       end if;
7333
7334       --  Direct controlled types do not inherit Finalize_Storage_Only flag
7335
7336       if not Is_Controlled (Parent_Type) then
7337          Set_Finalize_Storage_Only
7338            (Derived_Type, Finalize_Storage_Only (Parent_Type));
7339       end if;
7340
7341       --  Set fields for private derived types
7342
7343       if Is_Private_Type (Derived_Type) then
7344          Set_Depends_On_Private (Derived_Type, True);
7345          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7346
7347       --  Inherit fields from non private record types. If this is the
7348       --  completion of a derivation from a private type, the parent itself
7349       --  is private, and the attributes come from its full view, which must
7350       --  be present.
7351
7352       else
7353          if Is_Private_Type (Parent_Base)
7354            and then not Is_Record_Type (Parent_Base)
7355          then
7356             Set_Component_Alignment
7357               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7358             Set_C_Pass_By_Copy
7359               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7360          else
7361             Set_Component_Alignment
7362               (Derived_Type, Component_Alignment (Parent_Base));
7363             Set_C_Pass_By_Copy
7364               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7365          end if;
7366       end if;
7367
7368       --  Set fields for tagged types
7369
7370       if Is_Tagged then
7371          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
7372
7373          --  All tagged types defined in Ada.Finalization are controlled
7374
7375          if Chars (Scope (Derived_Type)) = Name_Finalization
7376            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7377            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7378          then
7379             Set_Is_Controlled (Derived_Type);
7380          else
7381             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7382          end if;
7383
7384          --  Minor optimization: there is no need to generate the class-wide
7385          --  entity associated with an underlying record view.
7386
7387          if not Is_Underlying_Record_View (Derived_Type) then
7388             Make_Class_Wide_Type (Derived_Type);
7389          end if;
7390
7391          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7392
7393          if Has_Discriminants (Derived_Type)
7394            and then Constraint_Present
7395          then
7396             Set_Stored_Constraint
7397               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7398          end if;
7399
7400          if Ada_Version >= Ada_2005 then
7401             declare
7402                Ifaces_List : Elist_Id;
7403
7404             begin
7405                --  Checks rules 3.9.4 (13/2 and 14/2)
7406
7407                if Comes_From_Source (Derived_Type)
7408                  and then not Is_Private_Type (Derived_Type)
7409                  and then Is_Interface (Parent_Type)
7410                  and then not Is_Interface (Derived_Type)
7411                then
7412                   if Is_Task_Interface (Parent_Type) then
7413                      Error_Msg_N
7414                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
7415                         Derived_Type);
7416
7417                   elsif Is_Protected_Interface (Parent_Type) then
7418                      Error_Msg_N
7419                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
7420                         Derived_Type);
7421                   end if;
7422                end if;
7423
7424                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
7425
7426                Check_Interfaces (N, Type_Def);
7427
7428                --  Ada 2005 (AI-251): Collect the list of progenitors that are
7429                --  not already in the parents.
7430
7431                Collect_Interfaces
7432                  (T               => Derived_Type,
7433                   Ifaces_List     => Ifaces_List,
7434                   Exclude_Parents => True);
7435
7436                Set_Interfaces (Derived_Type, Ifaces_List);
7437
7438                --  If the derived type is the anonymous type created for
7439                --  a declaration whose parent has a constraint, propagate
7440                --  the interface list to the source type. This must be done
7441                --  prior to the completion of the analysis of the source type
7442                --  because the components in the extension may contain current
7443                --  instances whose legality depends on some ancestor.
7444
7445                if Is_Itype (Derived_Type) then
7446                   declare
7447                      Def : constant Node_Id :=
7448                        Associated_Node_For_Itype (Derived_Type);
7449                   begin
7450                      if Present (Def)
7451                        and then Nkind (Def) = N_Full_Type_Declaration
7452                      then
7453                         Set_Interfaces
7454                           (Defining_Identifier (Def), Ifaces_List);
7455                      end if;
7456                   end;
7457                end if;
7458             end;
7459          end if;
7460
7461       else
7462          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
7463          Set_Has_Non_Standard_Rep
7464                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
7465       end if;
7466
7467       --  STEP 4: Inherit components from the parent base and constrain them.
7468       --          Apply the second transformation described in point 6. above.
7469
7470       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
7471         or else not Has_Discriminants (Parent_Type)
7472         or else not Is_Constrained (Parent_Type)
7473       then
7474          Constrs := Discs;
7475       else
7476          Constrs := Discriminant_Constraint (Parent_Type);
7477       end if;
7478
7479       Assoc_List :=
7480         Inherit_Components
7481           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
7482
7483       --  STEP 5a: Copy the parent record declaration for untagged types
7484
7485       if not Is_Tagged then
7486
7487          --  Discriminant_Constraint (Derived_Type) has been properly
7488          --  constructed. Save it and temporarily set it to Empty because we
7489          --  do not want the call to New_Copy_Tree below to mess this list.
7490
7491          if Has_Discriminants (Derived_Type) then
7492             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
7493             Set_Discriminant_Constraint (Derived_Type, No_Elist);
7494          else
7495             Save_Discr_Constr := No_Elist;
7496          end if;
7497
7498          --  Save the Etype field of Derived_Type. It is correctly set now,
7499          --  but the call to New_Copy tree may remap it to point to itself,
7500          --  which is not what we want. Ditto for the Next_Entity field.
7501
7502          Save_Etype       := Etype (Derived_Type);
7503          Save_Next_Entity := Next_Entity (Derived_Type);
7504
7505          --  Assoc_List maps all stored discriminants in the Parent_Base to
7506          --  stored discriminants in the Derived_Type. It is fundamental that
7507          --  no types or itypes with discriminants other than the stored
7508          --  discriminants appear in the entities declared inside
7509          --  Derived_Type, since the back end cannot deal with it.
7510
7511          New_Decl :=
7512            New_Copy_Tree
7513              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
7514
7515          --  Restore the fields saved prior to the New_Copy_Tree call
7516          --  and compute the stored constraint.
7517
7518          Set_Etype       (Derived_Type, Save_Etype);
7519          Set_Next_Entity (Derived_Type, Save_Next_Entity);
7520
7521          if Has_Discriminants (Derived_Type) then
7522             Set_Discriminant_Constraint
7523               (Derived_Type, Save_Discr_Constr);
7524             Set_Stored_Constraint
7525               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
7526             Replace_Components (Derived_Type, New_Decl);
7527          end if;
7528
7529          --  Insert the new derived type declaration
7530
7531          Rewrite (N, New_Decl);
7532
7533       --  STEP 5b: Complete the processing for record extensions in generics
7534
7535       --  There is no completion for record extensions declared in the
7536       --  parameter part of a generic, so we need to complete processing for
7537       --  these generic record extensions here. The Record_Type_Definition call
7538       --  will change the Ekind of the components from E_Void to E_Component.
7539
7540       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
7541          Record_Type_Definition (Empty, Derived_Type);
7542
7543       --  STEP 5c: Process the record extension for non private tagged types
7544
7545       elsif not Private_Extension then
7546
7547          --  Add the _parent field in the derived type
7548
7549          Expand_Record_Extension (Derived_Type, Type_Def);
7550
7551          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
7552          --  implemented interfaces if we are in expansion mode
7553
7554          if Expander_Active
7555            and then Has_Interfaces (Derived_Type)
7556          then
7557             Add_Interface_Tag_Components (N, Derived_Type);
7558          end if;
7559
7560          --  Analyze the record extension
7561
7562          Record_Type_Definition
7563            (Record_Extension_Part (Type_Def), Derived_Type);
7564       end if;
7565
7566       End_Scope;
7567
7568       --  Nothing else to do if there is an error in the derivation.
7569       --  An unusual case: the full view may be derived from a type in an
7570       --  instance, when the partial view was used illegally as an actual
7571       --  in that instance, leading to a circular definition.
7572
7573       if Etype (Derived_Type) = Any_Type
7574         or else Etype (Parent_Type) = Derived_Type
7575       then
7576          return;
7577       end if;
7578
7579       --  Set delayed freeze and then derive subprograms, we need to do
7580       --  this in this order so that derived subprograms inherit the
7581       --  derived freeze if necessary.
7582
7583       Set_Has_Delayed_Freeze (Derived_Type);
7584
7585       if Derive_Subps then
7586          Derive_Subprograms (Parent_Type, Derived_Type);
7587       end if;
7588
7589       --  If we have a private extension which defines a constrained derived
7590       --  type mark as constrained here after we have derived subprograms. See
7591       --  comment on point 9. just above the body of Build_Derived_Record_Type.
7592
7593       if Private_Extension and then Inherit_Discrims then
7594          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
7595             Set_Is_Constrained          (Derived_Type, True);
7596             Set_Discriminant_Constraint (Derived_Type, Discs);
7597
7598          elsif Is_Constrained (Parent_Type) then
7599             Set_Is_Constrained
7600               (Derived_Type, True);
7601             Set_Discriminant_Constraint
7602               (Derived_Type, Discriminant_Constraint (Parent_Type));
7603          end if;
7604       end if;
7605
7606       --  Update the class-wide type, which shares the now-completed entity
7607       --  list with its specific type. In case of underlying record views,
7608       --  we do not generate the corresponding class wide entity.
7609
7610       if Is_Tagged
7611         and then not Is_Underlying_Record_View (Derived_Type)
7612       then
7613          Set_First_Entity
7614            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
7615          Set_Last_Entity
7616            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
7617       end if;
7618
7619       --  Update the scope of anonymous access types of discriminants and other
7620       --  components, to prevent scope anomalies in gigi, when the derivation
7621       --  appears in a scope nested within that of the parent.
7622
7623       declare
7624          D : Entity_Id;
7625
7626       begin
7627          D := First_Entity (Derived_Type);
7628          while Present (D) loop
7629             if Ekind_In (D, E_Discriminant, E_Component) then
7630                if Is_Itype (Etype (D))
7631                   and then Ekind (Etype (D)) = E_Anonymous_Access_Type
7632                then
7633                   Set_Scope (Etype (D), Current_Scope);
7634                end if;
7635             end if;
7636
7637             Next_Entity (D);
7638          end loop;
7639       end;
7640    end Build_Derived_Record_Type;
7641
7642    ------------------------
7643    -- Build_Derived_Type --
7644    ------------------------
7645
7646    procedure Build_Derived_Type
7647      (N             : Node_Id;
7648       Parent_Type   : Entity_Id;
7649       Derived_Type  : Entity_Id;
7650       Is_Completion : Boolean;
7651       Derive_Subps  : Boolean := True)
7652    is
7653       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
7654
7655    begin
7656       --  Set common attributes
7657
7658       Set_Scope         (Derived_Type, Current_Scope);
7659
7660       Set_Ekind         (Derived_Type, Ekind    (Parent_Base));
7661       Set_Etype         (Derived_Type,           Parent_Base);
7662       Set_Has_Task      (Derived_Type, Has_Task (Parent_Base));
7663
7664       Set_Size_Info      (Derived_Type,                 Parent_Type);
7665       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
7666       Set_Convention     (Derived_Type, Convention     (Parent_Type));
7667       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
7668       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
7669
7670       --  Propagate invariant information. The new type has invariants if
7671       --  they are inherited from the parent type, and these invariants can
7672       --  be further inherited, so both flags are set.
7673
7674       if Has_Inheritable_Invariants (Parent_Type) then
7675          Set_Has_Inheritable_Invariants (Derived_Type);
7676          Set_Has_Invariants (Derived_Type);
7677       end if;
7678
7679       --  We similarly inherit predicates
7680
7681       if Has_Predicates (Parent_Type) then
7682          Set_Has_Predicates (Derived_Type);
7683       end if;
7684
7685       --  The derived type inherits the representation clauses of the parent.
7686       --  However, for a private type that is completed by a derivation, there
7687       --  may be operation attributes that have been specified already (stream
7688       --  attributes and External_Tag) and those must be provided. Finally,
7689       --  if the partial view is a private extension, the representation items
7690       --  of the parent have been inherited already, and should not be chained
7691       --  twice to the derived type.
7692
7693       if Is_Tagged_Type (Parent_Type)
7694         and then Present (First_Rep_Item (Derived_Type))
7695       then
7696          --  The existing items are either operational items or items inherited
7697          --  from a private extension declaration.
7698
7699          declare
7700             Rep : Node_Id;
7701             --  Used to iterate over representation items of the derived type
7702
7703             Last_Rep : Node_Id;
7704             --  Last representation item of the (non-empty) representation
7705             --  item list of the derived type.
7706
7707             Found : Boolean := False;
7708
7709          begin
7710             Rep      := First_Rep_Item (Derived_Type);
7711             Last_Rep := Rep;
7712             while Present (Rep) loop
7713                if Rep = First_Rep_Item (Parent_Type) then
7714                   Found := True;
7715                   exit;
7716
7717                else
7718                   Rep := Next_Rep_Item (Rep);
7719
7720                   if Present (Rep) then
7721                      Last_Rep := Rep;
7722                   end if;
7723                end if;
7724             end loop;
7725
7726             --  Here if we either encountered the parent type's first rep
7727             --  item on the derived type's rep item list (in which case
7728             --  Found is True, and we have nothing else to do), or if we
7729             --  reached the last rep item of the derived type, which is
7730             --  Last_Rep, in which case we further chain the parent type's
7731             --  rep items to those of the derived type.
7732
7733             if not Found then
7734                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
7735             end if;
7736          end;
7737
7738       else
7739          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
7740       end if;
7741
7742       case Ekind (Parent_Type) is
7743          when Numeric_Kind =>
7744             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
7745
7746          when Array_Kind =>
7747             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
7748
7749          when E_Record_Type
7750             | E_Record_Subtype
7751             | Class_Wide_Kind  =>
7752             Build_Derived_Record_Type
7753               (N, Parent_Type, Derived_Type, Derive_Subps);
7754             return;
7755
7756          when Enumeration_Kind =>
7757             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
7758
7759          when Access_Kind =>
7760             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
7761
7762          when Incomplete_Or_Private_Kind =>
7763             Build_Derived_Private_Type
7764               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
7765
7766             --  For discriminated types, the derivation includes deriving
7767             --  primitive operations. For others it is done below.
7768
7769             if Is_Tagged_Type (Parent_Type)
7770               or else Has_Discriminants (Parent_Type)
7771               or else (Present (Full_View (Parent_Type))
7772                         and then Has_Discriminants (Full_View (Parent_Type)))
7773             then
7774                return;
7775             end if;
7776
7777          when Concurrent_Kind =>
7778             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
7779
7780          when others =>
7781             raise Program_Error;
7782       end case;
7783
7784       if Etype (Derived_Type) = Any_Type then
7785          return;
7786       end if;
7787
7788       --  Set delayed freeze and then derive subprograms, we need to do this
7789       --  in this order so that derived subprograms inherit the derived freeze
7790       --  if necessary.
7791
7792       Set_Has_Delayed_Freeze (Derived_Type);
7793       if Derive_Subps then
7794          Derive_Subprograms (Parent_Type, Derived_Type);
7795       end if;
7796
7797       Set_Has_Primitive_Operations
7798         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
7799    end Build_Derived_Type;
7800
7801    -----------------------
7802    -- Build_Discriminal --
7803    -----------------------
7804
7805    procedure Build_Discriminal (Discrim : Entity_Id) is
7806       D_Minal : Entity_Id;
7807       CR_Disc : Entity_Id;
7808
7809    begin
7810       --  A discriminal has the same name as the discriminant
7811
7812       D_Minal :=
7813         Make_Defining_Identifier (Sloc (Discrim),
7814           Chars => Chars (Discrim));
7815
7816       Set_Ekind     (D_Minal, E_In_Parameter);
7817       Set_Mechanism (D_Minal, Default_Mechanism);
7818       Set_Etype     (D_Minal, Etype (Discrim));
7819       Set_Scope     (D_Minal, Current_Scope);
7820
7821       Set_Discriminal (Discrim, D_Minal);
7822       Set_Discriminal_Link (D_Minal, Discrim);
7823
7824       --  For task types, build at once the discriminants of the corresponding
7825       --  record, which are needed if discriminants are used in entry defaults
7826       --  and in family bounds.
7827
7828       if Is_Concurrent_Type (Current_Scope)
7829         or else Is_Limited_Type (Current_Scope)
7830       then
7831          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
7832
7833          Set_Ekind            (CR_Disc, E_In_Parameter);
7834          Set_Mechanism        (CR_Disc, Default_Mechanism);
7835          Set_Etype            (CR_Disc, Etype (Discrim));
7836          Set_Scope            (CR_Disc, Current_Scope);
7837          Set_Discriminal_Link (CR_Disc, Discrim);
7838          Set_CR_Discriminant  (Discrim, CR_Disc);
7839       end if;
7840    end Build_Discriminal;
7841
7842    ------------------------------------
7843    -- Build_Discriminant_Constraints --
7844    ------------------------------------
7845
7846    function Build_Discriminant_Constraints
7847      (T           : Entity_Id;
7848       Def         : Node_Id;
7849       Derived_Def : Boolean := False) return Elist_Id
7850    is
7851       C        : constant Node_Id := Constraint (Def);
7852       Nb_Discr : constant Nat     := Number_Discriminants (T);
7853
7854       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
7855       --  Saves the expression corresponding to a given discriminant in T
7856
7857       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
7858       --  Return the Position number within array Discr_Expr of a discriminant
7859       --  D within the discriminant list of the discriminated type T.
7860
7861       ------------------
7862       -- Pos_Of_Discr --
7863       ------------------
7864
7865       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
7866          Disc : Entity_Id;
7867
7868       begin
7869          Disc := First_Discriminant (T);
7870          for J in Discr_Expr'Range loop
7871             if Disc = D then
7872                return J;
7873             end if;
7874
7875             Next_Discriminant (Disc);
7876          end loop;
7877
7878          --  Note: Since this function is called on discriminants that are
7879          --  known to belong to the discriminated type, falling through the
7880          --  loop with no match signals an internal compiler error.
7881
7882          raise Program_Error;
7883       end Pos_Of_Discr;
7884
7885       --  Declarations local to Build_Discriminant_Constraints
7886
7887       Discr : Entity_Id;
7888       E     : Entity_Id;
7889       Elist : constant Elist_Id := New_Elmt_List;
7890
7891       Constr   : Node_Id;
7892       Expr     : Node_Id;
7893       Id       : Node_Id;
7894       Position : Nat;
7895       Found    : Boolean;
7896
7897       Discrim_Present : Boolean := False;
7898
7899    --  Start of processing for Build_Discriminant_Constraints
7900
7901    begin
7902       --  The following loop will process positional associations only.
7903       --  For a positional association, the (single) discriminant is
7904       --  implicitly specified by position, in textual order (RM 3.7.2).
7905
7906       Discr  := First_Discriminant (T);
7907       Constr := First (Constraints (C));
7908       for D in Discr_Expr'Range loop
7909          exit when Nkind (Constr) = N_Discriminant_Association;
7910
7911          if No (Constr) then
7912             Error_Msg_N ("too few discriminants given in constraint", C);
7913             return New_Elmt_List;
7914
7915          elsif Nkind (Constr) = N_Range
7916            or else (Nkind (Constr) = N_Attribute_Reference
7917                      and then
7918                     Attribute_Name (Constr) = Name_Range)
7919          then
7920             Error_Msg_N
7921               ("a range is not a valid discriminant constraint", Constr);
7922             Discr_Expr (D) := Error;
7923
7924          else
7925             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
7926             Discr_Expr (D) := Constr;
7927          end if;
7928
7929          Next_Discriminant (Discr);
7930          Next (Constr);
7931       end loop;
7932
7933       if No (Discr) and then Present (Constr) then
7934          Error_Msg_N ("too many discriminants given in constraint", Constr);
7935          return New_Elmt_List;
7936       end if;
7937
7938       --  Named associations can be given in any order, but if both positional
7939       --  and named associations are used in the same discriminant constraint,
7940       --  then positional associations must occur first, at their normal
7941       --  position. Hence once a named association is used, the rest of the
7942       --  discriminant constraint must use only named associations.
7943
7944       while Present (Constr) loop
7945
7946          --  Positional association forbidden after a named association
7947
7948          if Nkind (Constr) /= N_Discriminant_Association then
7949             Error_Msg_N ("positional association follows named one", Constr);
7950             return New_Elmt_List;
7951
7952          --  Otherwise it is a named association
7953
7954          else
7955             --  E records the type of the discriminants in the named
7956             --  association. All the discriminants specified in the same name
7957             --  association must have the same type.
7958
7959             E := Empty;
7960
7961             --  Search the list of discriminants in T to see if the simple name
7962             --  given in the constraint matches any of them.
7963
7964             Id := First (Selector_Names (Constr));
7965             while Present (Id) loop
7966                Found := False;
7967
7968                --  If Original_Discriminant is present, we are processing a
7969                --  generic instantiation and this is an instance node. We need
7970                --  to find the name of the corresponding discriminant in the
7971                --  actual record type T and not the name of the discriminant in
7972                --  the generic formal. Example:
7973
7974                --    generic
7975                --       type G (D : int) is private;
7976                --    package P is
7977                --       subtype W is G (D => 1);
7978                --    end package;
7979                --    type Rec (X : int) is record ... end record;
7980                --    package Q is new P (G => Rec);
7981
7982                --  At the point of the instantiation, formal type G is Rec
7983                --  and therefore when reanalyzing "subtype W is G (D => 1);"
7984                --  which really looks like "subtype W is Rec (D => 1);" at
7985                --  the point of instantiation, we want to find the discriminant
7986                --  that corresponds to D in Rec, i.e. X.
7987
7988                if Present (Original_Discriminant (Id)) then
7989                   Discr := Find_Corresponding_Discriminant (Id, T);
7990                   Found := True;
7991
7992                else
7993                   Discr := First_Discriminant (T);
7994                   while Present (Discr) loop
7995                      if Chars (Discr) = Chars (Id) then
7996                         Found := True;
7997                         exit;
7998                      end if;
7999
8000                      Next_Discriminant (Discr);
8001                   end loop;
8002
8003                   if not Found then
8004                      Error_Msg_N ("& does not match any discriminant", Id);
8005                      return New_Elmt_List;
8006
8007                   --  The following is only useful for the benefit of generic
8008                   --  instances but it does not interfere with other
8009                   --  processing for the non-generic case so we do it in all
8010                   --  cases (for generics this statement is executed when
8011                   --  processing the generic definition, see comment at the
8012                   --  beginning of this if statement).
8013
8014                   else
8015                      Set_Original_Discriminant (Id, Discr);
8016                   end if;
8017                end if;
8018
8019                Position := Pos_Of_Discr (T, Discr);
8020
8021                if Present (Discr_Expr (Position)) then
8022                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
8023
8024                else
8025                   --  Each discriminant specified in the same named association
8026                   --  must be associated with a separate copy of the
8027                   --  corresponding expression.
8028
8029                   if Present (Next (Id)) then
8030                      Expr := New_Copy_Tree (Expression (Constr));
8031                      Set_Parent (Expr, Parent (Expression (Constr)));
8032                   else
8033                      Expr := Expression (Constr);
8034                   end if;
8035
8036                   Discr_Expr (Position) := Expr;
8037                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
8038                end if;
8039
8040                --  A discriminant association with more than one discriminant
8041                --  name is only allowed if the named discriminants are all of
8042                --  the same type (RM 3.7.1(8)).
8043
8044                if E = Empty then
8045                   E := Base_Type (Etype (Discr));
8046
8047                elsif Base_Type (Etype (Discr)) /= E then
8048                   Error_Msg_N
8049                     ("all discriminants in an association " &
8050                      "must have the same type", Id);
8051                end if;
8052
8053                Next (Id);
8054             end loop;
8055          end if;
8056
8057          Next (Constr);
8058       end loop;
8059
8060       --  A discriminant constraint must provide exactly one value for each
8061       --  discriminant of the type (RM 3.7.1(8)).
8062
8063       for J in Discr_Expr'Range loop
8064          if No (Discr_Expr (J)) then
8065             Error_Msg_N ("too few discriminants given in constraint", C);
8066             return New_Elmt_List;
8067          end if;
8068       end loop;
8069
8070       --  Determine if there are discriminant expressions in the constraint
8071
8072       for J in Discr_Expr'Range loop
8073          if Denotes_Discriminant
8074               (Discr_Expr (J), Check_Concurrent => True)
8075          then
8076             Discrim_Present := True;
8077          end if;
8078       end loop;
8079
8080       --  Build an element list consisting of the expressions given in the
8081       --  discriminant constraint and apply the appropriate checks. The list
8082       --  is constructed after resolving any named discriminant associations
8083       --  and therefore the expressions appear in the textual order of the
8084       --  discriminants.
8085
8086       Discr := First_Discriminant (T);
8087       for J in Discr_Expr'Range loop
8088          if Discr_Expr (J) /= Error then
8089             Append_Elmt (Discr_Expr (J), Elist);
8090
8091             --  If any of the discriminant constraints is given by a
8092             --  discriminant and we are in a derived type declaration we
8093             --  have a discriminant renaming. Establish link between new
8094             --  and old discriminant.
8095
8096             if Denotes_Discriminant (Discr_Expr (J)) then
8097                if Derived_Def then
8098                   Set_Corresponding_Discriminant
8099                     (Entity (Discr_Expr (J)), Discr);
8100                end if;
8101
8102             --  Force the evaluation of non-discriminant expressions.
8103             --  If we have found a discriminant in the constraint 3.4(26)
8104             --  and 3.8(18) demand that no range checks are performed are
8105             --  after evaluation. If the constraint is for a component
8106             --  definition that has a per-object constraint, expressions are
8107             --  evaluated but not checked either. In all other cases perform
8108             --  a range check.
8109
8110             else
8111                if Discrim_Present then
8112                   null;
8113
8114                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8115                  and then
8116                    Has_Per_Object_Constraint
8117                      (Defining_Identifier (Parent (Parent (Def))))
8118                then
8119                   null;
8120
8121                elsif Is_Access_Type (Etype (Discr)) then
8122                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8123
8124                else
8125                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8126                end if;
8127
8128                Force_Evaluation (Discr_Expr (J));
8129             end if;
8130
8131             --  Check that the designated type of an access discriminant's
8132             --  expression is not a class-wide type unless the discriminant's
8133             --  designated type is also class-wide.
8134
8135             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8136               and then not Is_Class_Wide_Type
8137                          (Designated_Type (Etype (Discr)))
8138               and then Etype (Discr_Expr (J)) /= Any_Type
8139               and then Is_Class_Wide_Type
8140                          (Designated_Type (Etype (Discr_Expr (J))))
8141             then
8142                Wrong_Type (Discr_Expr (J), Etype (Discr));
8143
8144             elsif Is_Access_Type (Etype (Discr))
8145               and then not Is_Access_Constant (Etype (Discr))
8146               and then Is_Access_Type (Etype (Discr_Expr (J)))
8147               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8148             then
8149                Error_Msg_NE
8150                  ("constraint for discriminant& must be access to variable",
8151                     Def, Discr);
8152             end if;
8153          end if;
8154
8155          Next_Discriminant (Discr);
8156       end loop;
8157
8158       return Elist;
8159    end Build_Discriminant_Constraints;
8160
8161    ---------------------------------
8162    -- Build_Discriminated_Subtype --
8163    ---------------------------------
8164
8165    procedure Build_Discriminated_Subtype
8166      (T           : Entity_Id;
8167       Def_Id      : Entity_Id;
8168       Elist       : Elist_Id;
8169       Related_Nod : Node_Id;
8170       For_Access  : Boolean := False)
8171    is
8172       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8173       Constrained : constant Boolean :=
8174                       (Has_Discrs
8175                          and then not Is_Empty_Elmt_List (Elist)
8176                          and then not Is_Class_Wide_Type (T))
8177                         or else Is_Constrained (T);
8178
8179    begin
8180       if Ekind (T) = E_Record_Type then
8181          if For_Access then
8182             Set_Ekind (Def_Id, E_Private_Subtype);
8183             Set_Is_For_Access_Subtype (Def_Id, True);
8184          else
8185             Set_Ekind (Def_Id, E_Record_Subtype);
8186          end if;
8187
8188          --  Inherit preelaboration flag from base, for types for which it
8189          --  may have been set: records, private types, protected types.
8190
8191          Set_Known_To_Have_Preelab_Init
8192            (Def_Id, Known_To_Have_Preelab_Init (T));
8193
8194       elsif Ekind (T) = E_Task_Type then
8195          Set_Ekind (Def_Id, E_Task_Subtype);
8196
8197       elsif Ekind (T) = E_Protected_Type then
8198          Set_Ekind (Def_Id, E_Protected_Subtype);
8199          Set_Known_To_Have_Preelab_Init
8200            (Def_Id, Known_To_Have_Preelab_Init (T));
8201
8202       elsif Is_Private_Type (T) then
8203          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8204          Set_Known_To_Have_Preelab_Init
8205            (Def_Id, Known_To_Have_Preelab_Init (T));
8206
8207       elsif Is_Class_Wide_Type (T) then
8208          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8209
8210       else
8211          --  Incomplete type. Attach subtype to list of dependents, to be
8212          --  completed with full view of parent type,  unless is it the
8213          --  designated subtype of a record component within an init_proc.
8214          --  This last case arises for a component of an access type whose
8215          --  designated type is incomplete (e.g. a Taft Amendment type).
8216          --  The designated subtype is within an inner scope, and needs no
8217          --  elaboration, because only the access type is needed in the
8218          --  initialization procedure.
8219
8220          Set_Ekind (Def_Id, Ekind (T));
8221
8222          if For_Access and then Within_Init_Proc then
8223             null;
8224          else
8225             Append_Elmt (Def_Id, Private_Dependents (T));
8226          end if;
8227       end if;
8228
8229       Set_Etype             (Def_Id, T);
8230       Init_Size_Align       (Def_Id);
8231       Set_Has_Discriminants (Def_Id, Has_Discrs);
8232       Set_Is_Constrained    (Def_Id, Constrained);
8233
8234       Set_First_Entity      (Def_Id, First_Entity   (T));
8235       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8236
8237       --  If the subtype is the completion of a private declaration, there may
8238       --  have been representation clauses for the partial view, and they must
8239       --  be preserved. Build_Derived_Type chains the inherited clauses with
8240       --  the ones appearing on the extension. If this comes from a subtype
8241       --  declaration, all clauses are inherited.
8242
8243       if No (First_Rep_Item (Def_Id)) then
8244          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8245       end if;
8246
8247       if Is_Tagged_Type (T) then
8248          Set_Is_Tagged_Type  (Def_Id);
8249          Make_Class_Wide_Type (Def_Id);
8250       end if;
8251
8252       Set_Stored_Constraint (Def_Id, No_Elist);
8253
8254       if Has_Discrs then
8255          Set_Discriminant_Constraint (Def_Id, Elist);
8256          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8257       end if;
8258
8259       if Is_Tagged_Type (T) then
8260
8261          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8262          --  concurrent record type (which has the list of primitive
8263          --  operations).
8264
8265          if Ada_Version >= Ada_2005
8266            and then Is_Concurrent_Type (T)
8267          then
8268             Set_Corresponding_Record_Type (Def_Id,
8269                Corresponding_Record_Type (T));
8270          else
8271             Set_Direct_Primitive_Operations (Def_Id,
8272               Direct_Primitive_Operations (T));
8273          end if;
8274
8275          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8276       end if;
8277
8278       --  Subtypes introduced by component declarations do not need to be
8279       --  marked as delayed, and do not get freeze nodes, because the semantics
8280       --  verifies that the parents of the subtypes are frozen before the
8281       --  enclosing record is frozen.
8282
8283       if not Is_Type (Scope (Def_Id)) then
8284          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8285
8286          if Is_Private_Type (T)
8287            and then Present (Full_View (T))
8288          then
8289             Conditional_Delay (Def_Id, Full_View (T));
8290          else
8291             Conditional_Delay (Def_Id, T);
8292          end if;
8293       end if;
8294
8295       if Is_Record_Type (T) then
8296          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8297
8298          if Has_Discrs
8299             and then not Is_Empty_Elmt_List (Elist)
8300             and then not For_Access
8301          then
8302             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8303          elsif not For_Access then
8304             Set_Cloned_Subtype (Def_Id, T);
8305          end if;
8306       end if;
8307    end Build_Discriminated_Subtype;
8308
8309    ---------------------------
8310    -- Build_Itype_Reference --
8311    ---------------------------
8312
8313    procedure Build_Itype_Reference
8314      (Ityp : Entity_Id;
8315       Nod  : Node_Id)
8316    is
8317       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8318    begin
8319       Set_Itype (IR, Ityp);
8320       Insert_After (Nod, IR);
8321    end Build_Itype_Reference;
8322
8323    ------------------------
8324    -- Build_Scalar_Bound --
8325    ------------------------
8326
8327    function Build_Scalar_Bound
8328      (Bound : Node_Id;
8329       Par_T : Entity_Id;
8330       Der_T : Entity_Id) return Node_Id
8331    is
8332       New_Bound : Entity_Id;
8333
8334    begin
8335       --  Note: not clear why this is needed, how can the original bound
8336       --  be unanalyzed at this point? and if it is, what business do we
8337       --  have messing around with it? and why is the base type of the
8338       --  parent type the right type for the resolution. It probably is
8339       --  not! It is OK for the new bound we are creating, but not for
8340       --  the old one??? Still if it never happens, no problem!
8341
8342       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8343
8344       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8345          New_Bound := New_Copy (Bound);
8346          Set_Etype (New_Bound, Der_T);
8347          Set_Analyzed (New_Bound);
8348
8349       elsif Is_Entity_Name (Bound) then
8350          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8351
8352       --  The following is almost certainly wrong. What business do we have
8353       --  relocating a node (Bound) that is presumably still attached to
8354       --  the tree elsewhere???
8355
8356       else
8357          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8358       end if;
8359
8360       Set_Etype (New_Bound, Der_T);
8361       return New_Bound;
8362    end Build_Scalar_Bound;
8363
8364    --------------------------------
8365    -- Build_Underlying_Full_View --
8366    --------------------------------
8367
8368    procedure Build_Underlying_Full_View
8369      (N   : Node_Id;
8370       Typ : Entity_Id;
8371       Par : Entity_Id)
8372    is
8373       Loc  : constant Source_Ptr := Sloc (N);
8374       Subt : constant Entity_Id :=
8375                Make_Defining_Identifier
8376                  (Loc, New_External_Name (Chars (Typ), 'S'));
8377
8378       Constr : Node_Id;
8379       Indic  : Node_Id;
8380       C      : Node_Id;
8381       Id     : Node_Id;
8382
8383       procedure Set_Discriminant_Name (Id : Node_Id);
8384       --  If the derived type has discriminants, they may rename discriminants
8385       --  of the parent. When building the full view of the parent, we need to
8386       --  recover the names of the original discriminants if the constraint is
8387       --  given by named associations.
8388
8389       ---------------------------
8390       -- Set_Discriminant_Name --
8391       ---------------------------
8392
8393       procedure Set_Discriminant_Name (Id : Node_Id) is
8394          Disc : Entity_Id;
8395
8396       begin
8397          Set_Original_Discriminant (Id, Empty);
8398
8399          if Has_Discriminants (Typ) then
8400             Disc := First_Discriminant (Typ);
8401             while Present (Disc) loop
8402                if Chars (Disc) = Chars (Id)
8403                  and then Present (Corresponding_Discriminant (Disc))
8404                then
8405                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
8406                end if;
8407                Next_Discriminant (Disc);
8408             end loop;
8409          end if;
8410       end Set_Discriminant_Name;
8411
8412    --  Start of processing for Build_Underlying_Full_View
8413
8414    begin
8415       if Nkind (N) = N_Full_Type_Declaration then
8416          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
8417
8418       elsif Nkind (N) = N_Subtype_Declaration then
8419          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
8420
8421       elsif Nkind (N) = N_Component_Declaration then
8422          Constr :=
8423            New_Copy_Tree
8424              (Constraint (Subtype_Indication (Component_Definition (N))));
8425
8426       else
8427          raise Program_Error;
8428       end if;
8429
8430       C := First (Constraints (Constr));
8431       while Present (C) loop
8432          if Nkind (C) = N_Discriminant_Association then
8433             Id := First (Selector_Names (C));
8434             while Present (Id) loop
8435                Set_Discriminant_Name (Id);
8436                Next (Id);
8437             end loop;
8438          end if;
8439
8440          Next (C);
8441       end loop;
8442
8443       Indic :=
8444         Make_Subtype_Declaration (Loc,
8445           Defining_Identifier => Subt,
8446           Subtype_Indication  =>
8447             Make_Subtype_Indication (Loc,
8448               Subtype_Mark => New_Reference_To (Par, Loc),
8449               Constraint   => New_Copy_Tree (Constr)));
8450
8451       --  If this is a component subtype for an outer itype, it is not
8452       --  a list member, so simply set the parent link for analysis: if
8453       --  the enclosing type does not need to be in a declarative list,
8454       --  neither do the components.
8455
8456       if Is_List_Member (N)
8457         and then Nkind (N) /= N_Component_Declaration
8458       then
8459          Insert_Before (N, Indic);
8460       else
8461          Set_Parent (Indic, Parent (N));
8462       end if;
8463
8464       Analyze (Indic);
8465       Set_Underlying_Full_View (Typ, Full_View (Subt));
8466    end Build_Underlying_Full_View;
8467
8468    -------------------------------
8469    -- Check_Abstract_Overriding --
8470    -------------------------------
8471
8472    procedure Check_Abstract_Overriding (T : Entity_Id) is
8473       Alias_Subp : Entity_Id;
8474       Elmt       : Elmt_Id;
8475       Op_List    : Elist_Id;
8476       Subp       : Entity_Id;
8477       Type_Def   : Node_Id;
8478
8479       procedure Check_Pragma_Implemented (Subp : Entity_Id);
8480       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
8481       --  which has pragma Implemented already set. Check whether Subp's entity
8482       --  kind conforms to the implementation kind of the overridden routine.
8483
8484       procedure Check_Pragma_Implemented
8485         (Subp       : Entity_Id;
8486          Iface_Subp : Entity_Id);
8487       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
8488       --  Iface_Subp and both entities have pragma Implemented already set on
8489       --  them. Check whether the two implementation kinds are conforming.
8490
8491       procedure Inherit_Pragma_Implemented
8492         (Subp       : Entity_Id;
8493          Iface_Subp : Entity_Id);
8494       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
8495       --  subprogram Iface_Subp which has been marked by pragma Implemented.
8496       --  Propagate the implementation kind of Iface_Subp to Subp.
8497
8498       ------------------------------
8499       -- Check_Pragma_Implemented --
8500       ------------------------------
8501
8502       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
8503          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
8504          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
8505          Contr_Typ   : Entity_Id;
8506
8507       begin
8508          --  Subp must have an alias since it is a hidden entity used to link
8509          --  an interface subprogram to its overriding counterpart.
8510
8511          pragma Assert (Present (Alias (Subp)));
8512
8513          --  Extract the type of the controlling formal
8514
8515          Contr_Typ := Etype (First_Formal (Alias (Subp)));
8516
8517          if Is_Concurrent_Record_Type (Contr_Typ) then
8518             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
8519          end if;
8520
8521          --  An interface subprogram whose implementation kind is By_Entry must
8522          --  be implemented by an entry.
8523
8524          if Impl_Kind = Name_By_Entry
8525            and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Entry
8526          then
8527             Error_Msg_Node_2 := Iface_Alias;
8528             Error_Msg_NE
8529               ("type & must implement abstract subprogram & with an entry",
8530                Alias (Subp), Contr_Typ);
8531
8532          elsif Impl_Kind = Name_By_Protected_Procedure then
8533
8534             --  An interface subprogram whose implementation kind is By_
8535             --  Protected_Procedure cannot be implemented by a primitive
8536             --  procedure of a task type.
8537
8538             if Ekind (Contr_Typ) /= E_Protected_Type then
8539                Error_Msg_Node_2 := Contr_Typ;
8540                Error_Msg_NE
8541                  ("interface subprogram & cannot be implemented by a " &
8542                   "primitive procedure of task type &", Alias (Subp),
8543                   Iface_Alias);
8544
8545             --  An interface subprogram whose implementation kind is By_
8546             --  Protected_Procedure must be implemented by a procedure.
8547
8548             elsif Is_Primitive_Wrapper (Alias (Subp))
8549               and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Procedure
8550             then
8551                Error_Msg_Node_2 := Iface_Alias;
8552                Error_Msg_NE
8553                  ("type & must implement abstract subprogram & with a " &
8554                   "procedure", Alias (Subp), Contr_Typ);
8555             end if;
8556          end if;
8557       end Check_Pragma_Implemented;
8558
8559       ------------------------------
8560       -- Check_Pragma_Implemented --
8561       ------------------------------
8562
8563       procedure Check_Pragma_Implemented
8564         (Subp       : Entity_Id;
8565          Iface_Subp : Entity_Id)
8566       is
8567          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
8568          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
8569
8570       begin
8571          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
8572          --  and overriding subprogram are different. In general this is an
8573          --  error except when the implementation kind of the overridden
8574          --  subprograms is By_Any.
8575
8576          if Iface_Kind /= Subp_Kind
8577            and then Iface_Kind /= Name_By_Any
8578          then
8579             if Iface_Kind = Name_By_Entry then
8580                Error_Msg_N
8581                  ("incompatible implementation kind, overridden subprogram " &
8582                   "is marked By_Entry", Subp);
8583             else
8584                Error_Msg_N
8585                  ("incompatible implementation kind, overridden subprogram " &
8586                   "is marked By_Protected_Procedure", Subp);
8587             end if;
8588          end if;
8589       end Check_Pragma_Implemented;
8590
8591       --------------------------------
8592       -- Inherit_Pragma_Implemented --
8593       --------------------------------
8594
8595       procedure Inherit_Pragma_Implemented
8596         (Subp       : Entity_Id;
8597          Iface_Subp : Entity_Id)
8598       is
8599          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
8600          Loc        : constant Source_Ptr := Sloc (Subp);
8601          Impl_Prag  : Node_Id;
8602
8603       begin
8604          --  Since the implementation kind is stored as a representation item
8605          --  rather than a flag, create a pragma node.
8606
8607          Impl_Prag :=
8608            Make_Pragma (Loc,
8609              Chars => Name_Implemented,
8610              Pragma_Argument_Associations => New_List (
8611                Make_Pragma_Argument_Association (Loc,
8612                  Expression =>
8613                    New_Reference_To (Subp, Loc)),
8614
8615                Make_Pragma_Argument_Association (Loc,
8616                  Expression =>
8617                    Make_Identifier (Loc, Iface_Kind))));
8618
8619          --  The pragma doesn't need to be analyzed because it is internaly
8620          --  build. It is safe to directly register it as a rep item since we
8621          --  are only interested in the characters of the implementation kind.
8622
8623          Record_Rep_Item (Subp, Impl_Prag);
8624       end Inherit_Pragma_Implemented;
8625
8626    --  Start of processing for Check_Abstract_Overriding
8627
8628    begin
8629       Op_List := Primitive_Operations (T);
8630
8631       --  Loop to check primitive operations
8632
8633       Elmt := First_Elmt (Op_List);
8634       while Present (Elmt) loop
8635          Subp := Node (Elmt);
8636          Alias_Subp := Alias (Subp);
8637
8638          --  Inherited subprograms are identified by the fact that they do not
8639          --  come from source, and the associated source location is the
8640          --  location of the first subtype of the derived type.
8641
8642          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
8643          --  subprograms that "require overriding".
8644
8645          --  Special exception, do not complain about failure to override the
8646          --  stream routines _Input and _Output, as well as the primitive
8647          --  operations used in dispatching selects since we always provide
8648          --  automatic overridings for these subprograms.
8649
8650          --  Also ignore this rule for convention CIL since .NET libraries
8651          --  do bizarre things with interfaces???
8652
8653          --  The partial view of T may have been a private extension, for
8654          --  which inherited functions dispatching on result are abstract.
8655          --  If the full view is a null extension, there is no need for
8656          --  overriding in Ada2005, but wrappers need to be built for them
8657          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
8658
8659          if Is_Null_Extension (T)
8660            and then Has_Controlling_Result (Subp)
8661            and then Ada_Version >= Ada_2005
8662            and then Present (Alias_Subp)
8663            and then not Comes_From_Source (Subp)
8664            and then not Is_Abstract_Subprogram (Alias_Subp)
8665            and then not Is_Access_Type (Etype (Subp))
8666          then
8667             null;
8668
8669          --  Ada 2005 (AI-251): Internal entities of interfaces need no
8670          --  processing because this check is done with the aliased
8671          --  entity
8672
8673          elsif Present (Interface_Alias (Subp)) then
8674             null;
8675
8676          elsif (Is_Abstract_Subprogram (Subp)
8677                  or else Requires_Overriding (Subp)
8678                  or else
8679                    (Has_Controlling_Result (Subp)
8680                      and then Present (Alias_Subp)
8681                      and then not Comes_From_Source (Subp)
8682                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
8683            and then not Is_TSS (Subp, TSS_Stream_Input)
8684            and then not Is_TSS (Subp, TSS_Stream_Output)
8685            and then not Is_Abstract_Type (T)
8686            and then Convention (T) /= Convention_CIL
8687            and then not Is_Predefined_Interface_Primitive (Subp)
8688
8689             --  Ada 2005 (AI-251): Do not consider hidden entities associated
8690             --  with abstract interface types because the check will be done
8691             --  with the aliased entity (otherwise we generate a duplicated
8692             --  error message).
8693
8694            and then not Present (Interface_Alias (Subp))
8695          then
8696             if Present (Alias_Subp) then
8697
8698                --  Only perform the check for a derived subprogram when the
8699                --  type has an explicit record extension. This avoids incorrect
8700                --  flagging of abstract subprograms for the case of a type
8701                --  without an extension that is derived from a formal type
8702                --  with a tagged actual (can occur within a private part).
8703
8704                --  Ada 2005 (AI-391): In the case of an inherited function with
8705                --  a controlling result of the type, the rule does not apply if
8706                --  the type is a null extension (unless the parent function
8707                --  itself is abstract, in which case the function must still be
8708                --  be overridden). The expander will generate an overriding
8709                --  wrapper function calling the parent subprogram (see
8710                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
8711
8712                Type_Def := Type_Definition (Parent (T));
8713
8714                if Nkind (Type_Def) = N_Derived_Type_Definition
8715                  and then Present (Record_Extension_Part (Type_Def))
8716                  and then
8717                    (Ada_Version < Ada_2005
8718                       or else not Is_Null_Extension (T)
8719                       or else Ekind (Subp) = E_Procedure
8720                       or else not Has_Controlling_Result (Subp)
8721                       or else Is_Abstract_Subprogram (Alias_Subp)
8722                       or else Requires_Overriding (Subp)
8723                       or else Is_Access_Type (Etype (Subp)))
8724                then
8725                   --  Avoid reporting error in case of abstract predefined
8726                   --  primitive inherited from interface type because the
8727                   --  body of internally generated predefined primitives
8728                   --  of tagged types are generated later by Freeze_Type
8729
8730                   if Is_Interface (Root_Type (T))
8731                     and then Is_Abstract_Subprogram (Subp)
8732                     and then Is_Predefined_Dispatching_Operation (Subp)
8733                     and then not Comes_From_Source (Ultimate_Alias (Subp))
8734                   then
8735                      null;
8736
8737                   else
8738                      Error_Msg_NE
8739                        ("type must be declared abstract or & overridden",
8740                         T, Subp);
8741
8742                      --  Traverse the whole chain of aliased subprograms to
8743                      --  complete the error notification. This is especially
8744                      --  useful for traceability of the chain of entities when
8745                      --  the subprogram corresponds with an interface
8746                      --  subprogram (which may be defined in another package).
8747
8748                      if Present (Alias_Subp) then
8749                         declare
8750                            E : Entity_Id;
8751
8752                         begin
8753                            E := Subp;
8754                            while Present (Alias (E)) loop
8755                               Error_Msg_Sloc := Sloc (E);
8756                               Error_Msg_NE
8757                                 ("\& has been inherited #", T, Subp);
8758                               E := Alias (E);
8759                            end loop;
8760
8761                            Error_Msg_Sloc := Sloc (E);
8762                            Error_Msg_NE
8763                              ("\& has been inherited from subprogram #",
8764                               T, Subp);
8765                         end;
8766                      end if;
8767                   end if;
8768
8769                --  Ada 2005 (AI-345): Protected or task type implementing
8770                --  abstract interfaces.
8771
8772                elsif Is_Concurrent_Record_Type (T)
8773                  and then Present (Interfaces (T))
8774                then
8775                   --  The controlling formal of Subp must be of mode "out",
8776                   --  "in out" or an access-to-variable to be overridden.
8777
8778                   --  Error message below needs rewording (remember comma
8779                   --  in -gnatj mode) ???
8780
8781                   if Ekind (First_Formal (Subp)) = E_In_Parameter
8782                     and then Ekind (Subp) /= E_Function
8783                   then
8784                      if not Is_Predefined_Dispatching_Operation (Subp) then
8785                         Error_Msg_NE
8786                           ("first formal of & must be of mode `OUT`, " &
8787                            "`IN OUT` or access-to-variable", T, Subp);
8788                         Error_Msg_N
8789                           ("\to be overridden by protected procedure or " &
8790                            "entry (RM 9.4(11.9/2))", T);
8791                      end if;
8792
8793                   --  Some other kind of overriding failure
8794
8795                   else
8796                      Error_Msg_NE
8797                        ("interface subprogram & must be overridden",
8798                         T, Subp);
8799
8800                      --  Examine primitive operations of synchronized type,
8801                      --  to find homonyms that have the wrong profile.
8802
8803                      declare
8804                         Prim : Entity_Id;
8805
8806                      begin
8807                         Prim :=
8808                           First_Entity (Corresponding_Concurrent_Type (T));
8809                         while Present (Prim) loop
8810                            if Chars (Prim) = Chars (Subp) then
8811                               Error_Msg_NE
8812                                 ("profile is not type conformant with "
8813                                    & "prefixed view profile of "
8814                                    & "inherited operation&", Prim, Subp);
8815                            end if;
8816
8817                            Next_Entity (Prim);
8818                         end loop;
8819                      end;
8820                   end if;
8821                end if;
8822
8823             else
8824                Error_Msg_Node_2 := T;
8825                Error_Msg_N
8826                  ("abstract subprogram& not allowed for type&", Subp);
8827
8828                --  Also post unconditional warning on the type (unconditional
8829                --  so that if there are more than one of these cases, we get
8830                --  them all, and not just the first one).
8831
8832                Error_Msg_Node_2 := Subp;
8833                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
8834             end if;
8835          end if;
8836
8837          --  Ada 2012 (AI05-0030): Perform some checks related to pragma
8838          --  Implemented
8839
8840          --  Subp is an expander-generated procedure which maps an interface
8841          --  alias to a protected wrapper. The interface alias is flagged by
8842          --  pragma Implemented. Ensure that Subp is a procedure when the
8843          --  implementation kind is By_Protected_Procedure or an entry when
8844          --  By_Entry.
8845
8846          if Ada_Version >= Ada_2012
8847            and then Is_Hidden (Subp)
8848            and then Present (Interface_Alias (Subp))
8849            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
8850          then
8851             Check_Pragma_Implemented (Subp);
8852          end if;
8853
8854          --  Subp is an interface primitive which overrides another interface
8855          --  primitive marked with pragma Implemented.
8856
8857          if Ada_Version >= Ada_2012
8858            and then Is_Overriding_Operation (Subp)
8859            and then Present (Overridden_Operation (Subp))
8860            and then Has_Rep_Pragma
8861                       (Overridden_Operation (Subp), Name_Implemented)
8862          then
8863             --  If the overriding routine is also marked by Implemented, check
8864             --  that the two implementation kinds are conforming.
8865
8866             if Has_Rep_Pragma (Subp, Name_Implemented) then
8867                Check_Pragma_Implemented
8868                  (Subp       => Subp,
8869                   Iface_Subp => Overridden_Operation (Subp));
8870
8871             --  Otherwise the overriding routine inherits the implementation
8872             --  kind from the overridden subprogram.
8873
8874             else
8875                Inherit_Pragma_Implemented
8876                  (Subp       => Subp,
8877                   Iface_Subp => Overridden_Operation (Subp));
8878             end if;
8879          end if;
8880
8881          Next_Elmt (Elmt);
8882       end loop;
8883    end Check_Abstract_Overriding;
8884
8885    ------------------------------------------------
8886    -- Check_Access_Discriminant_Requires_Limited --
8887    ------------------------------------------------
8888
8889    procedure Check_Access_Discriminant_Requires_Limited
8890      (D   : Node_Id;
8891       Loc : Node_Id)
8892    is
8893    begin
8894       --  A discriminant_specification for an access discriminant shall appear
8895       --  only in the declaration for a task or protected type, or for a type
8896       --  with the reserved word 'limited' in its definition or in one of its
8897       --  ancestors (RM 3.7(10)).
8898
8899       --  AI-0063: The proper condition is that type must be immutably limited,
8900       --  or else be a partial view.
8901
8902       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
8903          if Is_Immutably_Limited_Type (Current_Scope)
8904            or else
8905              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
8906                and then Limited_Present (Parent (Current_Scope)))
8907          then
8908             null;
8909
8910          else
8911             Error_Msg_N
8912               ("access discriminants allowed only for limited types", Loc);
8913          end if;
8914       end if;
8915    end Check_Access_Discriminant_Requires_Limited;
8916
8917    -----------------------------------
8918    -- Check_Aliased_Component_Types --
8919    -----------------------------------
8920
8921    procedure Check_Aliased_Component_Types (T : Entity_Id) is
8922       C : Entity_Id;
8923
8924    begin
8925       --  ??? Also need to check components of record extensions, but not
8926       --  components of protected types (which are always limited).
8927
8928       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
8929       --  types to be unconstrained. This is safe because it is illegal to
8930       --  create access subtypes to such types with explicit discriminant
8931       --  constraints.
8932
8933       if not Is_Limited_Type (T) then
8934          if Ekind (T) = E_Record_Type then
8935             C := First_Component (T);
8936             while Present (C) loop
8937                if Is_Aliased (C)
8938                  and then Has_Discriminants (Etype (C))
8939                  and then not Is_Constrained (Etype (C))
8940                  and then not In_Instance_Body
8941                  and then Ada_Version < Ada_2005
8942                then
8943                   Error_Msg_N
8944                     ("aliased component must be constrained (RM 3.6(11))",
8945                       C);
8946                end if;
8947
8948                Next_Component (C);
8949             end loop;
8950
8951          elsif Ekind (T) = E_Array_Type then
8952             if Has_Aliased_Components (T)
8953               and then Has_Discriminants (Component_Type (T))
8954               and then not Is_Constrained (Component_Type (T))
8955               and then not In_Instance_Body
8956               and then Ada_Version < Ada_2005
8957             then
8958                Error_Msg_N
8959                  ("aliased component type must be constrained (RM 3.6(11))",
8960                     T);
8961             end if;
8962          end if;
8963       end if;
8964    end Check_Aliased_Component_Types;
8965
8966    ----------------------
8967    -- Check_Completion --
8968    ----------------------
8969
8970    procedure Check_Completion (Body_Id : Node_Id := Empty) is
8971       E : Entity_Id;
8972
8973       procedure Post_Error;
8974       --  Post error message for lack of completion for entity E
8975
8976       ----------------
8977       -- Post_Error --
8978       ----------------
8979
8980       procedure Post_Error is
8981
8982          procedure Missing_Body;
8983          --  Output missing body message
8984
8985          ------------------
8986          -- Missing_Body --
8987          ------------------
8988
8989          procedure Missing_Body is
8990          begin
8991             --  Spec is in same unit, so we can post on spec
8992
8993             if In_Same_Source_Unit (Body_Id, E) then
8994                Error_Msg_N ("missing body for &", E);
8995
8996             --  Spec is in a separate unit, so we have to post on the body
8997
8998             else
8999                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
9000             end if;
9001          end Missing_Body;
9002
9003       --  Start of processing for Post_Error
9004
9005       begin
9006          if not Comes_From_Source (E) then
9007
9008             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
9009                --  It may be an anonymous protected type created for a
9010                --  single variable. Post error on variable, if present.
9011
9012                declare
9013                   Var : Entity_Id;
9014
9015                begin
9016                   Var := First_Entity (Current_Scope);
9017                   while Present (Var) loop
9018                      exit when Etype (Var) = E
9019                        and then Comes_From_Source (Var);
9020
9021                      Next_Entity (Var);
9022                   end loop;
9023
9024                   if Present (Var) then
9025                      E := Var;
9026                   end if;
9027                end;
9028             end if;
9029          end if;
9030
9031          --  If a generated entity has no completion, then either previous
9032          --  semantic errors have disabled the expansion phase, or else we had
9033          --  missing subunits, or else we are compiling without expansion,
9034          --  or else something is very wrong.
9035
9036          if not Comes_From_Source (E) then
9037             pragma Assert
9038               (Serious_Errors_Detected > 0
9039                 or else Configurable_Run_Time_Violations > 0
9040                 or else Subunits_Missing
9041                 or else not Expander_Active);
9042             return;
9043
9044          --  Here for source entity
9045
9046          else
9047             --  Here if no body to post the error message, so we post the error
9048             --  on the declaration that has no completion. This is not really
9049             --  the right place to post it, think about this later ???
9050
9051             if No (Body_Id) then
9052                if Is_Type (E) then
9053                   Error_Msg_NE
9054                     ("missing full declaration for }", Parent (E), E);
9055                else
9056                   Error_Msg_NE ("missing body for &", Parent (E), E);
9057                end if;
9058
9059             --  Package body has no completion for a declaration that appears
9060             --  in the corresponding spec. Post error on the body, with a
9061             --  reference to the non-completed declaration.
9062
9063             else
9064                Error_Msg_Sloc := Sloc (E);
9065
9066                if Is_Type (E) then
9067                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
9068
9069                elsif Is_Overloadable (E)
9070                  and then Current_Entity_In_Scope (E) /= E
9071                then
9072                   --  It may be that the completion is mistyped and appears as
9073                   --  a distinct overloading of the entity.
9074
9075                   declare
9076                      Candidate : constant Entity_Id :=
9077                                    Current_Entity_In_Scope (E);
9078                      Decl      : constant Node_Id :=
9079                                    Unit_Declaration_Node (Candidate);
9080
9081                   begin
9082                      if Is_Overloadable (Candidate)
9083                        and then Ekind (Candidate) = Ekind (E)
9084                        and then Nkind (Decl) = N_Subprogram_Body
9085                        and then Acts_As_Spec (Decl)
9086                      then
9087                         Check_Type_Conformant (Candidate, E);
9088
9089                      else
9090                         Missing_Body;
9091                      end if;
9092                   end;
9093
9094                else
9095                   Missing_Body;
9096                end if;
9097             end if;
9098          end if;
9099       end Post_Error;
9100
9101    --  Start of processing for Check_Completion
9102
9103    begin
9104       E := First_Entity (Current_Scope);
9105       while Present (E) loop
9106          if Is_Intrinsic_Subprogram (E) then
9107             null;
9108
9109          --  The following situation requires special handling: a child unit
9110          --  that appears in the context clause of the body of its parent:
9111
9112          --    procedure Parent.Child (...);
9113
9114          --    with Parent.Child;
9115          --    package body Parent is
9116
9117          --  Here Parent.Child appears as a local entity, but should not be
9118          --  flagged as requiring completion, because it is a compilation
9119          --  unit.
9120
9121          --  Ignore missing completion for a subprogram that does not come from
9122          --  source (including the _Call primitive operation of RAS types,
9123          --  which has to have the flag Comes_From_Source for other purposes):
9124          --  we assume that the expander will provide the missing completion.
9125          --  In case of previous errors, other expansion actions that provide
9126          --  bodies for null procedures with not be invoked, so inhibit message
9127          --  in those cases.
9128          --  Note that E_Operator is not in the list that follows, because
9129          --  this kind is reserved for predefined operators, that are
9130          --  intrinsic and do not need completion.
9131
9132          elsif     Ekind (E) = E_Function
9133            or else Ekind (E) = E_Procedure
9134            or else Ekind (E) = E_Generic_Function
9135            or else Ekind (E) = E_Generic_Procedure
9136          then
9137             if Has_Completion (E) then
9138                null;
9139
9140             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
9141                null;
9142
9143             elsif Is_Subprogram (E)
9144               and then (not Comes_From_Source (E)
9145                           or else Chars (E) = Name_uCall)
9146             then
9147                null;
9148
9149             elsif
9150                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
9151             then
9152                null;
9153
9154             elsif Nkind (Parent (E)) = N_Procedure_Specification
9155               and then Null_Present (Parent (E))
9156               and then Serious_Errors_Detected > 0
9157             then
9158                null;
9159
9160             else
9161                Post_Error;
9162             end if;
9163
9164          elsif Is_Entry (E) then
9165             if not Has_Completion (E) and then
9166               (Ekind (Scope (E)) = E_Protected_Object
9167                 or else Ekind (Scope (E)) = E_Protected_Type)
9168             then
9169                Post_Error;
9170             end if;
9171
9172          elsif Is_Package_Or_Generic_Package (E) then
9173             if Unit_Requires_Body (E) then
9174                if not Has_Completion (E)
9175                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
9176                                                        N_Compilation_Unit
9177                then
9178                   Post_Error;
9179                end if;
9180
9181             elsif not Is_Child_Unit (E) then
9182                May_Need_Implicit_Body (E);
9183             end if;
9184
9185          elsif Ekind (E) = E_Incomplete_Type
9186            and then No (Underlying_Type (E))
9187          then
9188             Post_Error;
9189
9190          elsif (Ekind (E) = E_Task_Type or else
9191                 Ekind (E) = E_Protected_Type)
9192            and then not Has_Completion (E)
9193          then
9194             Post_Error;
9195
9196          --  A single task declared in the current scope is a constant, verify
9197          --  that the body of its anonymous type is in the same scope. If the
9198          --  task is defined elsewhere, this may be a renaming declaration for
9199          --  which no completion is needed.
9200
9201          elsif Ekind (E) = E_Constant
9202            and then Ekind (Etype (E)) = E_Task_Type
9203            and then not Has_Completion (Etype (E))
9204            and then Scope (Etype (E)) = Current_Scope
9205          then
9206             Post_Error;
9207
9208          elsif Ekind (E) = E_Protected_Object
9209            and then not Has_Completion (Etype (E))
9210          then
9211             Post_Error;
9212
9213          elsif Ekind (E) = E_Record_Type then
9214             if Is_Tagged_Type (E) then
9215                Check_Abstract_Overriding (E);
9216                Check_Conventions (E);
9217             end if;
9218
9219             Check_Aliased_Component_Types (E);
9220
9221          elsif Ekind (E) = E_Array_Type then
9222             Check_Aliased_Component_Types (E);
9223
9224          end if;
9225
9226          Next_Entity (E);
9227       end loop;
9228    end Check_Completion;
9229
9230    ----------------------------
9231    -- Check_Delta_Expression --
9232    ----------------------------
9233
9234    procedure Check_Delta_Expression (E : Node_Id) is
9235    begin
9236       if not (Is_Real_Type (Etype (E))) then
9237          Wrong_Type (E, Any_Real);
9238
9239       elsif not Is_OK_Static_Expression (E) then
9240          Flag_Non_Static_Expr
9241            ("non-static expression used for delta value!", E);
9242
9243       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9244          Error_Msg_N ("delta expression must be positive", E);
9245
9246       else
9247          return;
9248       end if;
9249
9250       --  If any of above errors occurred, then replace the incorrect
9251       --  expression by the real 0.1, which should prevent further errors.
9252
9253       Rewrite (E,
9254         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9255       Analyze_And_Resolve (E, Standard_Float);
9256    end Check_Delta_Expression;
9257
9258    -----------------------------
9259    -- Check_Digits_Expression --
9260    -----------------------------
9261
9262    procedure Check_Digits_Expression (E : Node_Id) is
9263    begin
9264       if not (Is_Integer_Type (Etype (E))) then
9265          Wrong_Type (E, Any_Integer);
9266
9267       elsif not Is_OK_Static_Expression (E) then
9268          Flag_Non_Static_Expr
9269            ("non-static expression used for digits value!", E);
9270
9271       elsif Expr_Value (E) <= 0 then
9272          Error_Msg_N ("digits value must be greater than zero", E);
9273
9274       else
9275          return;
9276       end if;
9277
9278       --  If any of above errors occurred, then replace the incorrect
9279       --  expression by the integer 1, which should prevent further errors.
9280
9281       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9282       Analyze_And_Resolve (E, Standard_Integer);
9283
9284    end Check_Digits_Expression;
9285
9286    --------------------------
9287    -- Check_Initialization --
9288    --------------------------
9289
9290    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9291    begin
9292       if Is_Limited_Type (T)
9293         and then not In_Instance
9294         and then not In_Inlined_Body
9295       then
9296          if not OK_For_Limited_Init (T, Exp) then
9297
9298             --  In GNAT mode, this is just a warning, to allow it to be evilly
9299             --  turned off. Otherwise it is a real error.
9300
9301             if GNAT_Mode then
9302                Error_Msg_N
9303                  ("?cannot initialize entities of limited type!", Exp);
9304
9305             elsif Ada_Version < Ada_2005 then
9306                Error_Msg_N
9307                  ("cannot initialize entities of limited type", Exp);
9308                Explain_Limited_Type (T, Exp);
9309
9310             else
9311                --  Specialize error message according to kind of illegal
9312                --  initial expression.
9313
9314                if Nkind (Exp) = N_Type_Conversion
9315                  and then Nkind (Expression (Exp)) = N_Function_Call
9316                then
9317                   Error_Msg_N
9318                     ("illegal context for call"
9319                       & " to function with limited result", Exp);
9320
9321                else
9322                   Error_Msg_N
9323                     ("initialization of limited object requires aggregate "
9324                       & "or function call",  Exp);
9325                end if;
9326             end if;
9327          end if;
9328       end if;
9329    end Check_Initialization;
9330
9331    ----------------------
9332    -- Check_Interfaces --
9333    ----------------------
9334
9335    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
9336       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
9337
9338       Iface       : Node_Id;
9339       Iface_Def   : Node_Id;
9340       Iface_Typ   : Entity_Id;
9341       Parent_Node : Node_Id;
9342
9343       Is_Task : Boolean := False;
9344       --  Set True if parent type or any progenitor is a task interface
9345
9346       Is_Protected : Boolean := False;
9347       --  Set True if parent type or any progenitor is a protected interface
9348
9349       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
9350       --  Check that a progenitor is compatible with declaration.
9351       --  Error is posted on Error_Node.
9352
9353       ------------------
9354       -- Check_Ifaces --
9355       ------------------
9356
9357       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
9358          Iface_Id : constant Entity_Id :=
9359                       Defining_Identifier (Parent (Iface_Def));
9360          Type_Def : Node_Id;
9361
9362       begin
9363          if Nkind (N) = N_Private_Extension_Declaration then
9364             Type_Def := N;
9365          else
9366             Type_Def := Type_Definition (N);
9367          end if;
9368
9369          if Is_Task_Interface (Iface_Id) then
9370             Is_Task := True;
9371
9372          elsif Is_Protected_Interface (Iface_Id) then
9373             Is_Protected := True;
9374          end if;
9375
9376          if Is_Synchronized_Interface (Iface_Id) then
9377
9378             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
9379             --  extension derived from a synchronized interface must explicitly
9380             --  be declared synchronized, because the full view will be a
9381             --  synchronized type.
9382
9383             if Nkind (N) = N_Private_Extension_Declaration then
9384                if not Synchronized_Present (N) then
9385                   Error_Msg_NE
9386                     ("private extension of& must be explicitly synchronized",
9387                       N, Iface_Id);
9388                end if;
9389
9390             --  However, by 3.9.4(16/2), a full type that is a record extension
9391             --  is never allowed to derive from a synchronized interface (note
9392             --  that interfaces must be excluded from this check, because those
9393             --  are represented by derived type definitions in some cases).
9394
9395             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9396               and then not Interface_Present (Type_Definition (N))
9397             then
9398                Error_Msg_N ("record extension cannot derive from synchronized"
9399                              & " interface", Error_Node);
9400             end if;
9401          end if;
9402
9403          --  Check that the characteristics of the progenitor are compatible
9404          --  with the explicit qualifier in the declaration.
9405          --  The check only applies to qualifiers that come from source.
9406          --  Limited_Present also appears in the declaration of corresponding
9407          --  records, and the check does not apply to them.
9408
9409          if Limited_Present (Type_Def)
9410            and then not
9411              Is_Concurrent_Record_Type (Defining_Identifier (N))
9412          then
9413             if Is_Limited_Interface (Parent_Type)
9414               and then not Is_Limited_Interface (Iface_Id)
9415             then
9416                Error_Msg_NE
9417                  ("progenitor& must be limited interface",
9418                    Error_Node, Iface_Id);
9419
9420             elsif
9421               (Task_Present (Iface_Def)
9422                 or else Protected_Present (Iface_Def)
9423                 or else Synchronized_Present (Iface_Def))
9424               and then Nkind (N) /= N_Private_Extension_Declaration
9425               and then not Error_Posted (N)
9426             then
9427                Error_Msg_NE
9428                  ("progenitor& must be limited interface",
9429                    Error_Node, Iface_Id);
9430             end if;
9431
9432          --  Protected interfaces can only inherit from limited, synchronized
9433          --  or protected interfaces.
9434
9435          elsif Nkind (N) = N_Full_Type_Declaration
9436            and then  Protected_Present (Type_Def)
9437          then
9438             if Limited_Present (Iface_Def)
9439               or else Synchronized_Present (Iface_Def)
9440               or else Protected_Present (Iface_Def)
9441             then
9442                null;
9443
9444             elsif Task_Present (Iface_Def) then
9445                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9446                             & " from task interface", Error_Node);
9447
9448             else
9449                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9450                             & " from non-limited interface", Error_Node);
9451             end if;
9452
9453          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
9454          --  limited and synchronized.
9455
9456          elsif Synchronized_Present (Type_Def) then
9457             if Limited_Present (Iface_Def)
9458               or else Synchronized_Present (Iface_Def)
9459             then
9460                null;
9461
9462             elsif Protected_Present (Iface_Def)
9463               and then Nkind (N) /= N_Private_Extension_Declaration
9464             then
9465                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9466                             & " from protected interface", Error_Node);
9467
9468             elsif Task_Present (Iface_Def)
9469               and then Nkind (N) /= N_Private_Extension_Declaration
9470             then
9471                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9472                             & " from task interface", Error_Node);
9473
9474             elsif not Is_Limited_Interface (Iface_Id) then
9475                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9476                             & " from non-limited interface", Error_Node);
9477             end if;
9478
9479          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
9480          --  synchronized or task interfaces.
9481
9482          elsif Nkind (N) = N_Full_Type_Declaration
9483            and then Task_Present (Type_Def)
9484          then
9485             if Limited_Present (Iface_Def)
9486               or else Synchronized_Present (Iface_Def)
9487               or else Task_Present (Iface_Def)
9488             then
9489                null;
9490
9491             elsif Protected_Present (Iface_Def) then
9492                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9493                             & " protected interface", Error_Node);
9494
9495             else
9496                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9497                             & " non-limited interface", Error_Node);
9498             end if;
9499          end if;
9500       end Check_Ifaces;
9501
9502    --  Start of processing for Check_Interfaces
9503
9504    begin
9505       if Is_Interface (Parent_Type) then
9506          if Is_Task_Interface (Parent_Type) then
9507             Is_Task := True;
9508
9509          elsif Is_Protected_Interface (Parent_Type) then
9510             Is_Protected := True;
9511          end if;
9512       end if;
9513
9514       if Nkind (N) = N_Private_Extension_Declaration then
9515
9516          --  Check that progenitors are compatible with declaration
9517
9518          Iface := First (Interface_List (Def));
9519          while Present (Iface) loop
9520             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9521
9522             Parent_Node := Parent (Base_Type (Iface_Typ));
9523             Iface_Def   := Type_Definition (Parent_Node);
9524
9525             if not Is_Interface (Iface_Typ) then
9526                Diagnose_Interface (Iface, Iface_Typ);
9527
9528             else
9529                Check_Ifaces (Iface_Def, Iface);
9530             end if;
9531
9532             Next (Iface);
9533          end loop;
9534
9535          if Is_Task and Is_Protected then
9536             Error_Msg_N
9537               ("type cannot derive from task and protected interface", N);
9538          end if;
9539
9540          return;
9541       end if;
9542
9543       --  Full type declaration of derived type.
9544       --  Check compatibility with parent if it is interface type
9545
9546       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9547         and then Is_Interface (Parent_Type)
9548       then
9549          Parent_Node := Parent (Parent_Type);
9550
9551          --  More detailed checks for interface varieties
9552
9553          Check_Ifaces
9554            (Iface_Def  => Type_Definition (Parent_Node),
9555             Error_Node => Subtype_Indication (Type_Definition (N)));
9556       end if;
9557
9558       Iface := First (Interface_List (Def));
9559       while Present (Iface) loop
9560          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9561
9562          Parent_Node := Parent (Base_Type (Iface_Typ));
9563          Iface_Def   := Type_Definition (Parent_Node);
9564
9565          if not Is_Interface (Iface_Typ) then
9566             Diagnose_Interface (Iface, Iface_Typ);
9567
9568          else
9569             --  "The declaration of a specific descendant of an interface
9570             --   type freezes the interface type" RM 13.14
9571
9572             Freeze_Before (N, Iface_Typ);
9573             Check_Ifaces (Iface_Def, Error_Node => Iface);
9574          end if;
9575
9576          Next (Iface);
9577       end loop;
9578
9579       if Is_Task and Is_Protected then
9580          Error_Msg_N
9581            ("type cannot derive from task and protected interface", N);
9582       end if;
9583    end Check_Interfaces;
9584
9585    ------------------------------------
9586    -- Check_Or_Process_Discriminants --
9587    ------------------------------------
9588
9589    --  If an incomplete or private type declaration was already given for the
9590    --  type, the discriminants may have already been processed if they were
9591    --  present on the incomplete declaration. In this case a full conformance
9592    --  check is performed otherwise just process them.
9593
9594    procedure Check_Or_Process_Discriminants
9595      (N    : Node_Id;
9596       T    : Entity_Id;
9597       Prev : Entity_Id := Empty)
9598    is
9599    begin
9600       if Has_Discriminants (T) then
9601
9602          --  Make the discriminants visible to component declarations
9603
9604          declare
9605             D    : Entity_Id;
9606             Prev : Entity_Id;
9607
9608          begin
9609             D := First_Discriminant (T);
9610             while Present (D) loop
9611                Prev := Current_Entity (D);
9612                Set_Current_Entity (D);
9613                Set_Is_Immediately_Visible (D);
9614                Set_Homonym (D, Prev);
9615
9616                --  Ada 2005 (AI-230): Access discriminant allowed in
9617                --  non-limited record types.
9618
9619                if Ada_Version < Ada_2005 then
9620
9621                   --  This restriction gets applied to the full type here. It
9622                   --  has already been applied earlier to the partial view.
9623
9624                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
9625                end if;
9626
9627                Next_Discriminant (D);
9628             end loop;
9629          end;
9630
9631       elsif Present (Discriminant_Specifications (N)) then
9632          Process_Discriminants (N, Prev);
9633       end if;
9634    end Check_Or_Process_Discriminants;
9635
9636    ----------------------
9637    -- Check_Real_Bound --
9638    ----------------------
9639
9640    procedure Check_Real_Bound (Bound : Node_Id) is
9641    begin
9642       if not Is_Real_Type (Etype (Bound)) then
9643          Error_Msg_N
9644            ("bound in real type definition must be of real type", Bound);
9645
9646       elsif not Is_OK_Static_Expression (Bound) then
9647          Flag_Non_Static_Expr
9648            ("non-static expression used for real type bound!", Bound);
9649
9650       else
9651          return;
9652       end if;
9653
9654       Rewrite
9655         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
9656       Analyze (Bound);
9657       Resolve (Bound, Standard_Float);
9658    end Check_Real_Bound;
9659
9660    ------------------------------
9661    -- Complete_Private_Subtype --
9662    ------------------------------
9663
9664    procedure Complete_Private_Subtype
9665      (Priv        : Entity_Id;
9666       Full        : Entity_Id;
9667       Full_Base   : Entity_Id;
9668       Related_Nod : Node_Id)
9669    is
9670       Save_Next_Entity : Entity_Id;
9671       Save_Homonym     : Entity_Id;
9672
9673    begin
9674       --  Set semantic attributes for (implicit) private subtype completion.
9675       --  If the full type has no discriminants, then it is a copy of the full
9676       --  view of the base. Otherwise, it is a subtype of the base with a
9677       --  possible discriminant constraint. Save and restore the original
9678       --  Next_Entity field of full to ensure that the calls to Copy_Node
9679       --  do not corrupt the entity chain.
9680
9681       --  Note that the type of the full view is the same entity as the type of
9682       --  the partial view. In this fashion, the subtype has access to the
9683       --  correct view of the parent.
9684
9685       Save_Next_Entity := Next_Entity (Full);
9686       Save_Homonym     := Homonym (Priv);
9687
9688       case Ekind (Full_Base) is
9689          when E_Record_Type    |
9690               E_Record_Subtype |
9691               Class_Wide_Kind  |
9692               Private_Kind     |
9693               Task_Kind        |
9694               Protected_Kind   =>
9695             Copy_Node (Priv, Full);
9696
9697             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
9698             Set_First_Entity       (Full, First_Entity (Full_Base));
9699             Set_Last_Entity        (Full, Last_Entity (Full_Base));
9700
9701          when others =>
9702             Copy_Node (Full_Base, Full);
9703             Set_Chars          (Full, Chars (Priv));
9704             Conditional_Delay  (Full, Priv);
9705             Set_Sloc           (Full, Sloc (Priv));
9706       end case;
9707
9708       Set_Next_Entity (Full, Save_Next_Entity);
9709       Set_Homonym     (Full, Save_Homonym);
9710       Set_Associated_Node_For_Itype (Full, Related_Nod);
9711
9712       --  Set common attributes for all subtypes
9713
9714       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
9715
9716       --  The Etype of the full view is inconsistent. Gigi needs to see the
9717       --  structural full view,  which is what the current scheme gives:
9718       --  the Etype of the full view is the etype of the full base. However,
9719       --  if the full base is a derived type, the full view then looks like
9720       --  a subtype of the parent, not a subtype of the full base. If instead
9721       --  we write:
9722
9723       --       Set_Etype (Full, Full_Base);
9724
9725       --  then we get inconsistencies in the front-end (confusion between
9726       --  views). Several outstanding bugs are related to this ???
9727
9728       Set_Is_First_Subtype (Full, False);
9729       Set_Scope            (Full, Scope (Priv));
9730       Set_Size_Info        (Full, Full_Base);
9731       Set_RM_Size          (Full, RM_Size (Full_Base));
9732       Set_Is_Itype         (Full);
9733
9734       --  A subtype of a private-type-without-discriminants, whose full-view
9735       --  has discriminants with default expressions, is not constrained!
9736
9737       if not Has_Discriminants (Priv) then
9738          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
9739
9740          if Has_Discriminants (Full_Base) then
9741             Set_Discriminant_Constraint
9742               (Full, Discriminant_Constraint (Full_Base));
9743
9744             --  The partial view may have been indefinite, the full view
9745             --  might not be.
9746
9747             Set_Has_Unknown_Discriminants
9748               (Full, Has_Unknown_Discriminants (Full_Base));
9749          end if;
9750       end if;
9751
9752       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
9753       Set_Depends_On_Private (Full, Has_Private_Component (Full));
9754
9755       --  Freeze the private subtype entity if its parent is delayed, and not
9756       --  already frozen. We skip this processing if the type is an anonymous
9757       --  subtype of a record component, or is the corresponding record of a
9758       --  protected type, since ???
9759
9760       if not Is_Type (Scope (Full)) then
9761          Set_Has_Delayed_Freeze (Full,
9762            Has_Delayed_Freeze (Full_Base)
9763              and then (not Is_Frozen (Full_Base)));
9764       end if;
9765
9766       Set_Freeze_Node (Full, Empty);
9767       Set_Is_Frozen (Full, False);
9768       Set_Full_View (Priv, Full);
9769
9770       if Has_Discriminants (Full) then
9771          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
9772          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
9773
9774          if Has_Unknown_Discriminants (Full) then
9775             Set_Discriminant_Constraint (Full, No_Elist);
9776          end if;
9777       end if;
9778
9779       if Ekind (Full_Base) = E_Record_Type
9780         and then Has_Discriminants (Full_Base)
9781         and then Has_Discriminants (Priv) -- might not, if errors
9782         and then not Has_Unknown_Discriminants (Priv)
9783         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
9784       then
9785          Create_Constrained_Components
9786            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
9787
9788       --  If the full base is itself derived from private, build a congruent
9789       --  subtype of its underlying type, for use by the back end. For a
9790       --  constrained record component, the declaration cannot be placed on
9791       --  the component list, but it must nevertheless be built an analyzed, to
9792       --  supply enough information for Gigi to compute the size of component.
9793
9794       elsif Ekind (Full_Base) in Private_Kind
9795         and then Is_Derived_Type (Full_Base)
9796         and then Has_Discriminants (Full_Base)
9797         and then (Ekind (Current_Scope) /= E_Record_Subtype)
9798       then
9799          if not Is_Itype (Priv)
9800            and then
9801              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
9802          then
9803             Build_Underlying_Full_View
9804               (Parent (Priv), Full, Etype (Full_Base));
9805
9806          elsif Nkind (Related_Nod) = N_Component_Declaration then
9807             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
9808          end if;
9809
9810       elsif Is_Record_Type (Full_Base) then
9811
9812          --  Show Full is simply a renaming of Full_Base
9813
9814          Set_Cloned_Subtype (Full, Full_Base);
9815       end if;
9816
9817       --  It is unsafe to share to bounds of a scalar type, because the Itype
9818       --  is elaborated on demand, and if a bound is non-static then different
9819       --  orders of elaboration in different units will lead to different
9820       --  external symbols.
9821
9822       if Is_Scalar_Type (Full_Base) then
9823          Set_Scalar_Range (Full,
9824            Make_Range (Sloc (Related_Nod),
9825              Low_Bound  =>
9826                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
9827              High_Bound =>
9828                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
9829
9830          --  This completion inherits the bounds of the full parent, but if
9831          --  the parent is an unconstrained floating point type, so is the
9832          --  completion.
9833
9834          if Is_Floating_Point_Type (Full_Base) then
9835             Set_Includes_Infinities
9836              (Scalar_Range (Full), Has_Infinities (Full_Base));
9837          end if;
9838       end if;
9839
9840       --  ??? It seems that a lot of fields are missing that should be copied
9841       --  from Full_Base to Full. Here are some that are introduced in a
9842       --  non-disruptive way but a cleanup is necessary.
9843
9844       if Is_Tagged_Type (Full_Base) then
9845          Set_Is_Tagged_Type (Full);
9846          Set_Direct_Primitive_Operations (Full,
9847            Direct_Primitive_Operations (Full_Base));
9848
9849          --  Inherit class_wide type of full_base in case the partial view was
9850          --  not tagged. Otherwise it has already been created when the private
9851          --  subtype was analyzed.
9852
9853          if No (Class_Wide_Type (Full)) then
9854             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
9855          end if;
9856
9857       --  If this is a subtype of a protected or task type, constrain its
9858       --  corresponding record, unless this is a subtype without constraints,
9859       --  i.e. a simple renaming as with an actual subtype in an instance.
9860
9861       elsif Is_Concurrent_Type (Full_Base) then
9862          if Has_Discriminants (Full)
9863            and then Present (Corresponding_Record_Type (Full_Base))
9864            and then
9865              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
9866          then
9867             Set_Corresponding_Record_Type (Full,
9868               Constrain_Corresponding_Record
9869                 (Full, Corresponding_Record_Type (Full_Base),
9870                   Related_Nod, Full_Base));
9871
9872          else
9873             Set_Corresponding_Record_Type (Full,
9874               Corresponding_Record_Type (Full_Base));
9875          end if;
9876       end if;
9877    end Complete_Private_Subtype;
9878
9879    ----------------------------
9880    -- Constant_Redeclaration --
9881    ----------------------------
9882
9883    procedure Constant_Redeclaration
9884      (Id : Entity_Id;
9885       N  : Node_Id;
9886       T  : out Entity_Id)
9887    is
9888       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
9889       Obj_Def : constant Node_Id := Object_Definition (N);
9890       New_T   : Entity_Id;
9891
9892       procedure Check_Possible_Deferred_Completion
9893         (Prev_Id      : Entity_Id;
9894          Prev_Obj_Def : Node_Id;
9895          Curr_Obj_Def : Node_Id);
9896       --  Determine whether the two object definitions describe the partial
9897       --  and the full view of a constrained deferred constant. Generate
9898       --  a subtype for the full view and verify that it statically matches
9899       --  the subtype of the partial view.
9900
9901       procedure Check_Recursive_Declaration (Typ : Entity_Id);
9902       --  If deferred constant is an access type initialized with an allocator,
9903       --  check whether there is an illegal recursion in the definition,
9904       --  through a default value of some record subcomponent. This is normally
9905       --  detected when generating init procs, but requires this additional
9906       --  mechanism when expansion is disabled.
9907
9908       ----------------------------------------
9909       -- Check_Possible_Deferred_Completion --
9910       ----------------------------------------
9911
9912       procedure Check_Possible_Deferred_Completion
9913         (Prev_Id      : Entity_Id;
9914          Prev_Obj_Def : Node_Id;
9915          Curr_Obj_Def : Node_Id)
9916       is
9917       begin
9918          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
9919            and then Present (Constraint (Prev_Obj_Def))
9920            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
9921            and then Present (Constraint (Curr_Obj_Def))
9922          then
9923             declare
9924                Loc    : constant Source_Ptr := Sloc (N);
9925                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
9926                Decl   : constant Node_Id    :=
9927                           Make_Subtype_Declaration (Loc,
9928                             Defining_Identifier => Def_Id,
9929                             Subtype_Indication  =>
9930                               Relocate_Node (Curr_Obj_Def));
9931
9932             begin
9933                Insert_Before_And_Analyze (N, Decl);
9934                Set_Etype (Id, Def_Id);
9935
9936                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
9937                   Error_Msg_Sloc := Sloc (Prev_Id);
9938                   Error_Msg_N ("subtype does not statically match deferred " &
9939                                "declaration#", N);
9940                end if;
9941             end;
9942          end if;
9943       end Check_Possible_Deferred_Completion;
9944
9945       ---------------------------------
9946       -- Check_Recursive_Declaration --
9947       ---------------------------------
9948
9949       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
9950          Comp : Entity_Id;
9951
9952       begin
9953          if Is_Record_Type (Typ) then
9954             Comp := First_Component (Typ);
9955             while Present (Comp) loop
9956                if Comes_From_Source (Comp) then
9957                   if Present (Expression (Parent (Comp)))
9958                     and then Is_Entity_Name (Expression (Parent (Comp)))
9959                     and then Entity (Expression (Parent (Comp))) = Prev
9960                   then
9961                      Error_Msg_Sloc := Sloc (Parent (Comp));
9962                      Error_Msg_NE
9963                        ("illegal circularity with declaration for&#",
9964                          N, Comp);
9965                      return;
9966
9967                   elsif Is_Record_Type (Etype (Comp)) then
9968                      Check_Recursive_Declaration (Etype (Comp));
9969                   end if;
9970                end if;
9971
9972                Next_Component (Comp);
9973             end loop;
9974          end if;
9975       end Check_Recursive_Declaration;
9976
9977    --  Start of processing for Constant_Redeclaration
9978
9979    begin
9980       if Nkind (Parent (Prev)) = N_Object_Declaration then
9981          if Nkind (Object_Definition
9982                      (Parent (Prev))) = N_Subtype_Indication
9983          then
9984             --  Find type of new declaration. The constraints of the two
9985             --  views must match statically, but there is no point in
9986             --  creating an itype for the full view.
9987
9988             if Nkind (Obj_Def) = N_Subtype_Indication then
9989                Find_Type (Subtype_Mark (Obj_Def));
9990                New_T := Entity (Subtype_Mark (Obj_Def));
9991
9992             else
9993                Find_Type (Obj_Def);
9994                New_T := Entity (Obj_Def);
9995             end if;
9996
9997             T := Etype (Prev);
9998
9999          else
10000             --  The full view may impose a constraint, even if the partial
10001             --  view does not, so construct the subtype.
10002
10003             New_T := Find_Type_Of_Object (Obj_Def, N);
10004             T     := New_T;
10005          end if;
10006
10007       else
10008          --  Current declaration is illegal, diagnosed below in Enter_Name
10009
10010          T := Empty;
10011          New_T := Any_Type;
10012       end if;
10013
10014       --  If previous full declaration or a renaming declaration exists, or if
10015       --  a homograph is present, let Enter_Name handle it, either with an
10016       --  error or with the removal of an overridden implicit subprogram.
10017
10018       if Ekind (Prev) /= E_Constant
10019         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
10020         or else Present (Expression (Parent (Prev)))
10021         or else Present (Full_View (Prev))
10022       then
10023          Enter_Name (Id);
10024
10025       --  Verify that types of both declarations match, or else that both types
10026       --  are anonymous access types whose designated subtypes statically match
10027       --  (as allowed in Ada 2005 by AI-385).
10028
10029       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
10030         and then
10031           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
10032              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
10033              or else Is_Access_Constant (Etype (New_T)) /=
10034                      Is_Access_Constant (Etype (Prev))
10035              or else Can_Never_Be_Null (Etype (New_T)) /=
10036                      Can_Never_Be_Null (Etype (Prev))
10037              or else Null_Exclusion_Present (Parent (Prev)) /=
10038                      Null_Exclusion_Present (Parent (Id))
10039              or else not Subtypes_Statically_Match
10040                            (Designated_Type (Etype (Prev)),
10041                             Designated_Type (Etype (New_T))))
10042       then
10043          Error_Msg_Sloc := Sloc (Prev);
10044          Error_Msg_N ("type does not match declaration#", N);
10045          Set_Full_View (Prev, Id);
10046          Set_Etype (Id, Any_Type);
10047
10048       elsif
10049         Null_Exclusion_Present (Parent (Prev))
10050           and then not Null_Exclusion_Present (N)
10051       then
10052          Error_Msg_Sloc := Sloc (Prev);
10053          Error_Msg_N ("null-exclusion does not match declaration#", N);
10054          Set_Full_View (Prev, Id);
10055          Set_Etype (Id, Any_Type);
10056
10057       --  If so, process the full constant declaration
10058
10059       else
10060          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
10061          --  the deferred declaration is constrained, then the subtype defined
10062          --  by the subtype_indication in the full declaration shall match it
10063          --  statically.
10064
10065          Check_Possible_Deferred_Completion
10066            (Prev_Id      => Prev,
10067             Prev_Obj_Def => Object_Definition (Parent (Prev)),
10068             Curr_Obj_Def => Obj_Def);
10069
10070          Set_Full_View (Prev, Id);
10071          Set_Is_Public (Id, Is_Public (Prev));
10072          Set_Is_Internal (Id);
10073          Append_Entity (Id, Current_Scope);
10074
10075          --  Check ALIASED present if present before (RM 7.4(7))
10076
10077          if Is_Aliased (Prev)
10078            and then not Aliased_Present (N)
10079          then
10080             Error_Msg_Sloc := Sloc (Prev);
10081             Error_Msg_N ("ALIASED required (see declaration#)", N);
10082          end if;
10083
10084          --  Check that placement is in private part and that the incomplete
10085          --  declaration appeared in the visible part.
10086
10087          if Ekind (Current_Scope) = E_Package
10088            and then not In_Private_Part (Current_Scope)
10089          then
10090             Error_Msg_Sloc := Sloc (Prev);
10091             Error_Msg_N
10092               ("full constant for declaration#"
10093                & " must be in private part", N);
10094
10095          elsif Ekind (Current_Scope) = E_Package
10096            and then
10097              List_Containing (Parent (Prev)) /=
10098                Visible_Declarations
10099                  (Specification (Unit_Declaration_Node (Current_Scope)))
10100          then
10101             Error_Msg_N
10102               ("deferred constant must be declared in visible part",
10103                  Parent (Prev));
10104          end if;
10105
10106          if Is_Access_Type (T)
10107            and then Nkind (Expression (N)) = N_Allocator
10108          then
10109             Check_Recursive_Declaration (Designated_Type (T));
10110          end if;
10111       end if;
10112    end Constant_Redeclaration;
10113
10114    ----------------------
10115    -- Constrain_Access --
10116    ----------------------
10117
10118    procedure Constrain_Access
10119      (Def_Id      : in out Entity_Id;
10120       S           : Node_Id;
10121       Related_Nod : Node_Id)
10122    is
10123       T             : constant Entity_Id := Entity (Subtype_Mark (S));
10124       Desig_Type    : constant Entity_Id := Designated_Type (T);
10125       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
10126       Constraint_OK : Boolean := True;
10127
10128       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
10129       --  Simple predicate to test for defaulted discriminants
10130       --  Shouldn't this be in sem_util???
10131
10132       ---------------------------------
10133       -- Has_Defaulted_Discriminants --
10134       ---------------------------------
10135
10136       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
10137       begin
10138          return Has_Discriminants (Typ)
10139           and then Present (First_Discriminant (Typ))
10140           and then Present
10141             (Discriminant_Default_Value (First_Discriminant (Typ)));
10142       end Has_Defaulted_Discriminants;
10143
10144    --  Start of processing for Constrain_Access
10145
10146    begin
10147       if Is_Array_Type (Desig_Type) then
10148          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
10149
10150       elsif (Is_Record_Type (Desig_Type)
10151               or else Is_Incomplete_Or_Private_Type (Desig_Type))
10152         and then not Is_Constrained (Desig_Type)
10153       then
10154          --  ??? The following code is a temporary kludge to ignore a
10155          --  discriminant constraint on access type if it is constraining
10156          --  the current record. Avoid creating the implicit subtype of the
10157          --  record we are currently compiling since right now, we cannot
10158          --  handle these. For now, just return the access type itself.
10159
10160          if Desig_Type = Current_Scope
10161            and then No (Def_Id)
10162          then
10163             Set_Ekind (Desig_Subtype, E_Record_Subtype);
10164             Def_Id := Entity (Subtype_Mark (S));
10165
10166             --  This call added to ensure that the constraint is analyzed
10167             --  (needed for a B test). Note that we still return early from
10168             --  this procedure to avoid recursive processing. ???
10169
10170             Constrain_Discriminated_Type
10171               (Desig_Subtype, S, Related_Nod, For_Access => True);
10172             return;
10173          end if;
10174
10175          if (Ekind (T) = E_General_Access_Type
10176               or else Ada_Version >= Ada_2005)
10177            and then Has_Private_Declaration (Desig_Type)
10178            and then In_Open_Scopes (Scope (Desig_Type))
10179            and then Has_Discriminants (Desig_Type)
10180          then
10181             --  Enforce rule that the constraint is illegal if there is
10182             --  an unconstrained view of the designated type. This means
10183             --  that the partial view (either a private type declaration or
10184             --  a derivation from a private type) has no discriminants.
10185             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
10186             --  by ACATS B371001).
10187
10188             --  Rule updated for Ada 2005: the private type is said to have
10189             --  a constrained partial view, given that objects of the type
10190             --  can be declared. Furthermore, the rule applies to all access
10191             --  types, unlike the rule concerning default discriminants.
10192
10193             declare
10194                Pack  : constant Node_Id :=
10195                          Unit_Declaration_Node (Scope (Desig_Type));
10196                Decls : List_Id;
10197                Decl  : Node_Id;
10198
10199             begin
10200                if Nkind (Pack) = N_Package_Declaration then
10201                   Decls := Visible_Declarations (Specification (Pack));
10202                   Decl := First (Decls);
10203                   while Present (Decl) loop
10204                      if (Nkind (Decl) = N_Private_Type_Declaration
10205                           and then
10206                             Chars (Defining_Identifier (Decl)) =
10207                                                      Chars (Desig_Type))
10208
10209                        or else
10210                         (Nkind (Decl) = N_Full_Type_Declaration
10211                           and then
10212                             Chars (Defining_Identifier (Decl)) =
10213                                                      Chars (Desig_Type)
10214                           and then Is_Derived_Type (Desig_Type)
10215                           and then
10216                             Has_Private_Declaration (Etype (Desig_Type)))
10217                      then
10218                         if No (Discriminant_Specifications (Decl)) then
10219                            Error_Msg_N
10220                             ("cannot constrain general access type if " &
10221                                "designated type has constrained partial view",
10222                                 S);
10223                         end if;
10224
10225                         exit;
10226                      end if;
10227
10228                      Next (Decl);
10229                   end loop;
10230                end if;
10231             end;
10232          end if;
10233
10234          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
10235            For_Access => True);
10236
10237       elsif (Is_Task_Type (Desig_Type)
10238               or else Is_Protected_Type (Desig_Type))
10239         and then not Is_Constrained (Desig_Type)
10240       then
10241          Constrain_Concurrent
10242            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
10243
10244       else
10245          Error_Msg_N ("invalid constraint on access type", S);
10246          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
10247          Constraint_OK := False;
10248       end if;
10249
10250       if No (Def_Id) then
10251          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
10252       else
10253          Set_Ekind (Def_Id, E_Access_Subtype);
10254       end if;
10255
10256       if Constraint_OK then
10257          Set_Etype (Def_Id, Base_Type (T));
10258
10259          if Is_Private_Type (Desig_Type) then
10260             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
10261          end if;
10262       else
10263          Set_Etype (Def_Id, Any_Type);
10264       end if;
10265
10266       Set_Size_Info                (Def_Id, T);
10267       Set_Is_Constrained           (Def_Id, Constraint_OK);
10268       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
10269       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
10270       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
10271
10272       Conditional_Delay (Def_Id, T);
10273
10274       --  AI-363 : Subtypes of general access types whose designated types have
10275       --  default discriminants are disallowed. In instances, the rule has to
10276       --  be checked against the actual, of which T is the subtype. In a
10277       --  generic body, the rule is checked assuming that the actual type has
10278       --  defaulted discriminants.
10279
10280       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
10281          if Ekind (Base_Type (T)) = E_General_Access_Type
10282            and then Has_Defaulted_Discriminants (Desig_Type)
10283          then
10284             if Ada_Version < Ada_2005 then
10285                Error_Msg_N
10286                  ("access subtype of general access type would not " &
10287                   "be allowed in Ada 2005?", S);
10288             else
10289                Error_Msg_N
10290                  ("access subype of general access type not allowed", S);
10291             end if;
10292
10293             Error_Msg_N ("\discriminants have defaults", S);
10294
10295          elsif Is_Access_Type (T)
10296            and then Is_Generic_Type (Desig_Type)
10297            and then Has_Discriminants (Desig_Type)
10298            and then In_Package_Body (Current_Scope)
10299          then
10300             if Ada_Version < Ada_2005 then
10301                Error_Msg_N
10302                  ("access subtype would not be allowed in generic body " &
10303                   "in Ada 2005?", S);
10304             else
10305                Error_Msg_N
10306                  ("access subtype not allowed in generic body", S);
10307             end if;
10308
10309             Error_Msg_N
10310               ("\designated type is a discriminated formal", S);
10311          end if;
10312       end if;
10313    end Constrain_Access;
10314
10315    ---------------------
10316    -- Constrain_Array --
10317    ---------------------
10318
10319    procedure Constrain_Array
10320      (Def_Id      : in out Entity_Id;
10321       SI          : Node_Id;
10322       Related_Nod : Node_Id;
10323       Related_Id  : Entity_Id;
10324       Suffix      : Character)
10325    is
10326       C                     : constant Node_Id := Constraint (SI);
10327       Number_Of_Constraints : Nat := 0;
10328       Index                 : Node_Id;
10329       S, T                  : Entity_Id;
10330       Constraint_OK         : Boolean := True;
10331
10332    begin
10333       T := Entity (Subtype_Mark (SI));
10334
10335       if Ekind (T) in Access_Kind then
10336          T := Designated_Type (T);
10337       end if;
10338
10339       --  If an index constraint follows a subtype mark in a subtype indication
10340       --  then the type or subtype denoted by the subtype mark must not already
10341       --  impose an index constraint. The subtype mark must denote either an
10342       --  unconstrained array type or an access type whose designated type
10343       --  is such an array type... (RM 3.6.1)
10344
10345       if Is_Constrained (T) then
10346          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
10347          Constraint_OK := False;
10348
10349       else
10350          S := First (Constraints (C));
10351          while Present (S) loop
10352             Number_Of_Constraints := Number_Of_Constraints + 1;
10353             Next (S);
10354          end loop;
10355
10356          --  In either case, the index constraint must provide a discrete
10357          --  range for each index of the array type and the type of each
10358          --  discrete range must be the same as that of the corresponding
10359          --  index. (RM 3.6.1)
10360
10361          if Number_Of_Constraints /= Number_Dimensions (T) then
10362             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
10363             Constraint_OK := False;
10364
10365          else
10366             S := First (Constraints (C));
10367             Index := First_Index (T);
10368             Analyze (Index);
10369
10370             --  Apply constraints to each index type
10371
10372             for J in 1 .. Number_Of_Constraints loop
10373                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
10374                Next (Index);
10375                Next (S);
10376             end loop;
10377
10378          end if;
10379       end if;
10380
10381       if No (Def_Id) then
10382          Def_Id :=
10383            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
10384          Set_Parent (Def_Id, Related_Nod);
10385
10386       else
10387          Set_Ekind (Def_Id, E_Array_Subtype);
10388       end if;
10389
10390       Set_Size_Info      (Def_Id,                (T));
10391       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10392       Set_Etype          (Def_Id, Base_Type      (T));
10393
10394       if Constraint_OK then
10395          Set_First_Index (Def_Id, First (Constraints (C)));
10396       else
10397          Set_First_Index (Def_Id, First_Index (T));
10398       end if;
10399
10400       Set_Is_Constrained     (Def_Id, True);
10401       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
10402       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10403
10404       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
10405       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
10406
10407       --  A subtype does not inherit the packed_array_type of is parent. We
10408       --  need to initialize the attribute because if Def_Id is previously
10409       --  analyzed through a limited_with clause, it will have the attributes
10410       --  of an incomplete type, one of which is an Elist that overlaps the
10411       --  Packed_Array_Type field.
10412
10413       Set_Packed_Array_Type (Def_Id, Empty);
10414
10415       --  Build a freeze node if parent still needs one. Also make sure that
10416       --  the Depends_On_Private status is set because the subtype will need
10417       --  reprocessing at the time the base type does, and also we must set a
10418       --  conditional delay.
10419
10420       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
10421       Conditional_Delay (Def_Id, T);
10422    end Constrain_Array;
10423
10424    ------------------------------
10425    -- Constrain_Component_Type --
10426    ------------------------------
10427
10428    function Constrain_Component_Type
10429      (Comp            : Entity_Id;
10430       Constrained_Typ : Entity_Id;
10431       Related_Node    : Node_Id;
10432       Typ             : Entity_Id;
10433       Constraints     : Elist_Id) return Entity_Id
10434    is
10435       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
10436       Compon_Type : constant Entity_Id := Etype (Comp);
10437
10438       function Build_Constrained_Array_Type
10439         (Old_Type : Entity_Id) return Entity_Id;
10440       --  If Old_Type is an array type, one of whose indexes is constrained
10441       --  by a discriminant, build an Itype whose constraint replaces the
10442       --  discriminant with its value in the constraint.
10443
10444       function Build_Constrained_Discriminated_Type
10445         (Old_Type : Entity_Id) return Entity_Id;
10446       --  Ditto for record components
10447
10448       function Build_Constrained_Access_Type
10449         (Old_Type : Entity_Id) return Entity_Id;
10450       --  Ditto for access types. Makes use of previous two functions, to
10451       --  constrain designated type.
10452
10453       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
10454       --  T is an array or discriminated type, C is a list of constraints
10455       --  that apply to T. This routine builds the constrained subtype.
10456
10457       function Is_Discriminant (Expr : Node_Id) return Boolean;
10458       --  Returns True if Expr is a discriminant
10459
10460       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
10461       --  Find the value of discriminant Discrim in Constraint
10462
10463       -----------------------------------
10464       -- Build_Constrained_Access_Type --
10465       -----------------------------------
10466
10467       function Build_Constrained_Access_Type
10468         (Old_Type : Entity_Id) return Entity_Id
10469       is
10470          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
10471          Itype         : Entity_Id;
10472          Desig_Subtype : Entity_Id;
10473          Scop          : Entity_Id;
10474
10475       begin
10476          --  if the original access type was not embedded in the enclosing
10477          --  type definition, there is no need to produce a new access
10478          --  subtype. In fact every access type with an explicit constraint
10479          --  generates an itype whose scope is the enclosing record.
10480
10481          if not Is_Type (Scope (Old_Type)) then
10482             return Old_Type;
10483
10484          elsif Is_Array_Type (Desig_Type) then
10485             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
10486
10487          elsif Has_Discriminants (Desig_Type) then
10488
10489             --  This may be an access type to an enclosing record type for
10490             --  which we are constructing the constrained components. Return
10491             --  the enclosing record subtype. This is not always correct,
10492             --  but avoids infinite recursion. ???
10493
10494             Desig_Subtype := Any_Type;
10495
10496             for J in reverse 0 .. Scope_Stack.Last loop
10497                Scop := Scope_Stack.Table (J).Entity;
10498
10499                if Is_Type (Scop)
10500                  and then Base_Type (Scop) = Base_Type (Desig_Type)
10501                then
10502                   Desig_Subtype := Scop;
10503                end if;
10504
10505                exit when not Is_Type (Scop);
10506             end loop;
10507
10508             if Desig_Subtype = Any_Type then
10509                Desig_Subtype :=
10510                  Build_Constrained_Discriminated_Type (Desig_Type);
10511             end if;
10512
10513          else
10514             return Old_Type;
10515          end if;
10516
10517          if Desig_Subtype /= Desig_Type then
10518
10519             --  The Related_Node better be here or else we won't be able
10520             --  to attach new itypes to a node in the tree.
10521
10522             pragma Assert (Present (Related_Node));
10523
10524             Itype := Create_Itype (E_Access_Subtype, Related_Node);
10525
10526             Set_Etype                    (Itype, Base_Type      (Old_Type));
10527             Set_Size_Info                (Itype,                (Old_Type));
10528             Set_Directly_Designated_Type (Itype, Desig_Subtype);
10529             Set_Depends_On_Private       (Itype, Has_Private_Component
10530                                                                 (Old_Type));
10531             Set_Is_Access_Constant       (Itype, Is_Access_Constant
10532                                                                 (Old_Type));
10533
10534             --  The new itype needs freezing when it depends on a not frozen
10535             --  type and the enclosing subtype needs freezing.
10536
10537             if Has_Delayed_Freeze (Constrained_Typ)
10538               and then not Is_Frozen (Constrained_Typ)
10539             then
10540                Conditional_Delay (Itype, Base_Type (Old_Type));
10541             end if;
10542
10543             return Itype;
10544
10545          else
10546             return Old_Type;
10547          end if;
10548       end Build_Constrained_Access_Type;
10549
10550       ----------------------------------
10551       -- Build_Constrained_Array_Type --
10552       ----------------------------------
10553
10554       function Build_Constrained_Array_Type
10555         (Old_Type : Entity_Id) return Entity_Id
10556       is
10557          Lo_Expr     : Node_Id;
10558          Hi_Expr     : Node_Id;
10559          Old_Index   : Node_Id;
10560          Range_Node  : Node_Id;
10561          Constr_List : List_Id;
10562
10563          Need_To_Create_Itype : Boolean := False;
10564
10565       begin
10566          Old_Index := First_Index (Old_Type);
10567          while Present (Old_Index) loop
10568             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10569
10570             if Is_Discriminant (Lo_Expr)
10571               or else Is_Discriminant (Hi_Expr)
10572             then
10573                Need_To_Create_Itype := True;
10574             end if;
10575
10576             Next_Index (Old_Index);
10577          end loop;
10578
10579          if Need_To_Create_Itype then
10580             Constr_List := New_List;
10581
10582             Old_Index := First_Index (Old_Type);
10583             while Present (Old_Index) loop
10584                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10585
10586                if Is_Discriminant (Lo_Expr) then
10587                   Lo_Expr := Get_Discr_Value (Lo_Expr);
10588                end if;
10589
10590                if Is_Discriminant (Hi_Expr) then
10591                   Hi_Expr := Get_Discr_Value (Hi_Expr);
10592                end if;
10593
10594                Range_Node :=
10595                  Make_Range
10596                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
10597
10598                Append (Range_Node, To => Constr_List);
10599
10600                Next_Index (Old_Index);
10601             end loop;
10602
10603             return Build_Subtype (Old_Type, Constr_List);
10604
10605          else
10606             return Old_Type;
10607          end if;
10608       end Build_Constrained_Array_Type;
10609
10610       ------------------------------------------
10611       -- Build_Constrained_Discriminated_Type --
10612       ------------------------------------------
10613
10614       function Build_Constrained_Discriminated_Type
10615         (Old_Type : Entity_Id) return Entity_Id
10616       is
10617          Expr           : Node_Id;
10618          Constr_List    : List_Id;
10619          Old_Constraint : Elmt_Id;
10620
10621          Need_To_Create_Itype : Boolean := False;
10622
10623       begin
10624          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10625          while Present (Old_Constraint) loop
10626             Expr := Node (Old_Constraint);
10627
10628             if Is_Discriminant (Expr) then
10629                Need_To_Create_Itype := True;
10630             end if;
10631
10632             Next_Elmt (Old_Constraint);
10633          end loop;
10634
10635          if Need_To_Create_Itype then
10636             Constr_List := New_List;
10637
10638             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10639             while Present (Old_Constraint) loop
10640                Expr := Node (Old_Constraint);
10641
10642                if Is_Discriminant (Expr) then
10643                   Expr := Get_Discr_Value (Expr);
10644                end if;
10645
10646                Append (New_Copy_Tree (Expr), To => Constr_List);
10647
10648                Next_Elmt (Old_Constraint);
10649             end loop;
10650
10651             return Build_Subtype (Old_Type, Constr_List);
10652
10653          else
10654             return Old_Type;
10655          end if;
10656       end Build_Constrained_Discriminated_Type;
10657
10658       -------------------
10659       -- Build_Subtype --
10660       -------------------
10661
10662       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
10663          Indic       : Node_Id;
10664          Subtyp_Decl : Node_Id;
10665          Def_Id      : Entity_Id;
10666          Btyp        : Entity_Id := Base_Type (T);
10667
10668       begin
10669          --  The Related_Node better be here or else we won't be able to
10670          --  attach new itypes to a node in the tree.
10671
10672          pragma Assert (Present (Related_Node));
10673
10674          --  If the view of the component's type is incomplete or private
10675          --  with unknown discriminants, then the constraint must be applied
10676          --  to the full type.
10677
10678          if Has_Unknown_Discriminants (Btyp)
10679            and then Present (Underlying_Type (Btyp))
10680          then
10681             Btyp := Underlying_Type (Btyp);
10682          end if;
10683
10684          Indic :=
10685            Make_Subtype_Indication (Loc,
10686              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
10687              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
10688
10689          Def_Id := Create_Itype (Ekind (T), Related_Node);
10690
10691          Subtyp_Decl :=
10692            Make_Subtype_Declaration (Loc,
10693              Defining_Identifier => Def_Id,
10694              Subtype_Indication  => Indic);
10695
10696          Set_Parent (Subtyp_Decl, Parent (Related_Node));
10697
10698          --  Itypes must be analyzed with checks off (see package Itypes)
10699
10700          Analyze (Subtyp_Decl, Suppress => All_Checks);
10701
10702          return Def_Id;
10703       end Build_Subtype;
10704
10705       ---------------------
10706       -- Get_Discr_Value --
10707       ---------------------
10708
10709       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
10710          D : Entity_Id;
10711          E : Elmt_Id;
10712
10713       begin
10714          --  The discriminant may be declared for the type, in which case we
10715          --  find it by iterating over the list of discriminants. If the
10716          --  discriminant is inherited from a parent type, it appears as the
10717          --  corresponding discriminant of the current type. This will be the
10718          --  case when constraining an inherited component whose constraint is
10719          --  given by a discriminant of the parent.
10720
10721          D := First_Discriminant (Typ);
10722          E := First_Elmt (Constraints);
10723
10724          while Present (D) loop
10725             if D = Entity (Discrim)
10726               or else D = CR_Discriminant (Entity (Discrim))
10727               or else Corresponding_Discriminant (D) = Entity (Discrim)
10728             then
10729                return Node (E);
10730             end if;
10731
10732             Next_Discriminant (D);
10733             Next_Elmt (E);
10734          end loop;
10735
10736          --  The corresponding_Discriminant mechanism is incomplete, because
10737          --  the correspondence between new and old discriminants is not one
10738          --  to one: one new discriminant can constrain several old ones. In
10739          --  that case, scan sequentially the stored_constraint, the list of
10740          --  discriminants of the parents, and the constraints.
10741          --  Previous code checked for the present of the Stored_Constraint
10742          --  list for the derived type, but did not use it at all. Should it
10743          --  be present when the component is a discriminated task type?
10744
10745          if Is_Derived_Type (Typ)
10746            and then Scope (Entity (Discrim)) = Etype (Typ)
10747          then
10748             D := First_Discriminant (Etype (Typ));
10749             E := First_Elmt (Constraints);
10750             while Present (D) loop
10751                if D = Entity (Discrim) then
10752                   return Node (E);
10753                end if;
10754
10755                Next_Discriminant (D);
10756                Next_Elmt (E);
10757             end loop;
10758          end if;
10759
10760          --  Something is wrong if we did not find the value
10761
10762          raise Program_Error;
10763       end Get_Discr_Value;
10764
10765       ---------------------
10766       -- Is_Discriminant --
10767       ---------------------
10768
10769       function Is_Discriminant (Expr : Node_Id) return Boolean is
10770          Discrim_Scope : Entity_Id;
10771
10772       begin
10773          if Denotes_Discriminant (Expr) then
10774             Discrim_Scope := Scope (Entity (Expr));
10775
10776             --  Either we have a reference to one of Typ's discriminants,
10777
10778             pragma Assert (Discrim_Scope = Typ
10779
10780                --  or to the discriminants of the parent type, in the case
10781                --  of a derivation of a tagged type with variants.
10782
10783                or else Discrim_Scope = Etype (Typ)
10784                or else Full_View (Discrim_Scope) = Etype (Typ)
10785
10786                --  or same as above for the case where the discriminants
10787                --  were declared in Typ's private view.
10788
10789                or else (Is_Private_Type (Discrim_Scope)
10790                         and then Chars (Discrim_Scope) = Chars (Typ))
10791
10792                --  or else we are deriving from the full view and the
10793                --  discriminant is declared in the private entity.
10794
10795                or else (Is_Private_Type (Typ)
10796                          and then Chars (Discrim_Scope) = Chars (Typ))
10797
10798                --  Or we are constrained the corresponding record of a
10799                --  synchronized type that completes a private declaration.
10800
10801                or else (Is_Concurrent_Record_Type (Typ)
10802                          and then
10803                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
10804
10805                --  or we have a class-wide type, in which case make sure the
10806                --  discriminant found belongs to the root type.
10807
10808                or else (Is_Class_Wide_Type (Typ)
10809                          and then Etype (Typ) = Discrim_Scope));
10810
10811             return True;
10812          end if;
10813
10814          --  In all other cases we have something wrong
10815
10816          return False;
10817       end Is_Discriminant;
10818
10819    --  Start of processing for Constrain_Component_Type
10820
10821    begin
10822       if Nkind (Parent (Comp)) = N_Component_Declaration
10823         and then Comes_From_Source (Parent (Comp))
10824         and then Comes_From_Source
10825           (Subtype_Indication (Component_Definition (Parent (Comp))))
10826         and then
10827           Is_Entity_Name
10828             (Subtype_Indication (Component_Definition (Parent (Comp))))
10829       then
10830          return Compon_Type;
10831
10832       elsif Is_Array_Type (Compon_Type) then
10833          return Build_Constrained_Array_Type (Compon_Type);
10834
10835       elsif Has_Discriminants (Compon_Type) then
10836          return Build_Constrained_Discriminated_Type (Compon_Type);
10837
10838       elsif Is_Access_Type (Compon_Type) then
10839          return Build_Constrained_Access_Type (Compon_Type);
10840
10841       else
10842          return Compon_Type;
10843       end if;
10844    end Constrain_Component_Type;
10845
10846    --------------------------
10847    -- Constrain_Concurrent --
10848    --------------------------
10849
10850    --  For concurrent types, the associated record value type carries the same
10851    --  discriminants, so when we constrain a concurrent type, we must constrain
10852    --  the corresponding record type as well.
10853
10854    procedure Constrain_Concurrent
10855      (Def_Id      : in out Entity_Id;
10856       SI          : Node_Id;
10857       Related_Nod : Node_Id;
10858       Related_Id  : Entity_Id;
10859       Suffix      : Character)
10860    is
10861       T_Ent : Entity_Id := Entity (Subtype_Mark (SI));
10862       T_Val : Entity_Id;
10863
10864    begin
10865       if Ekind (T_Ent) in Access_Kind then
10866          T_Ent := Designated_Type (T_Ent);
10867       end if;
10868
10869       T_Val := Corresponding_Record_Type (T_Ent);
10870
10871       if Present (T_Val) then
10872
10873          if No (Def_Id) then
10874             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
10875          end if;
10876
10877          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
10878
10879          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10880          Set_Corresponding_Record_Type (Def_Id,
10881            Constrain_Corresponding_Record
10882              (Def_Id, T_Val, Related_Nod, Related_Id));
10883
10884       else
10885          --  If there is no associated record, expansion is disabled and this
10886          --  is a generic context. Create a subtype in any case, so that
10887          --  semantic analysis can proceed.
10888
10889          if No (Def_Id) then
10890             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
10891          end if;
10892
10893          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
10894       end if;
10895    end Constrain_Concurrent;
10896
10897    ------------------------------------
10898    -- Constrain_Corresponding_Record --
10899    ------------------------------------
10900
10901    function Constrain_Corresponding_Record
10902      (Prot_Subt   : Entity_Id;
10903       Corr_Rec    : Entity_Id;
10904       Related_Nod : Node_Id;
10905       Related_Id  : Entity_Id) return Entity_Id
10906    is
10907       T_Sub : constant Entity_Id :=
10908                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
10909
10910    begin
10911       Set_Etype             (T_Sub, Corr_Rec);
10912       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
10913       Set_Is_Constrained    (T_Sub, True);
10914       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
10915       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
10916
10917       --  As elsewhere, we do not want to create a freeze node for this itype
10918       --  if it is created for a constrained component of an enclosing record
10919       --  because references to outer discriminants will appear out of scope.
10920
10921       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
10922          Conditional_Delay (T_Sub, Corr_Rec);
10923       else
10924          Set_Is_Frozen (T_Sub);
10925       end if;
10926
10927       if Has_Discriminants (Prot_Subt) then -- False only if errors.
10928          Set_Discriminant_Constraint
10929            (T_Sub, Discriminant_Constraint (Prot_Subt));
10930          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
10931          Create_Constrained_Components
10932            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
10933       end if;
10934
10935       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
10936
10937       return T_Sub;
10938    end Constrain_Corresponding_Record;
10939
10940    -----------------------
10941    -- Constrain_Decimal --
10942    -----------------------
10943
10944    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
10945       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
10946       C           : constant Node_Id    := Constraint (S);
10947       Loc         : constant Source_Ptr := Sloc (C);
10948       Range_Expr  : Node_Id;
10949       Digits_Expr : Node_Id;
10950       Digits_Val  : Uint;
10951       Bound_Val   : Ureal;
10952
10953    begin
10954       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
10955
10956       if Nkind (C) = N_Range_Constraint then
10957          Range_Expr := Range_Expression (C);
10958          Digits_Val := Digits_Value (T);
10959
10960       else
10961          pragma Assert (Nkind (C) = N_Digits_Constraint);
10962          Digits_Expr := Digits_Expression (C);
10963          Analyze_And_Resolve (Digits_Expr, Any_Integer);
10964
10965          Check_Digits_Expression (Digits_Expr);
10966          Digits_Val := Expr_Value (Digits_Expr);
10967
10968          if Digits_Val > Digits_Value (T) then
10969             Error_Msg_N
10970                ("digits expression is incompatible with subtype", C);
10971             Digits_Val := Digits_Value (T);
10972          end if;
10973
10974          if Present (Range_Constraint (C)) then
10975             Range_Expr := Range_Expression (Range_Constraint (C));
10976          else
10977             Range_Expr := Empty;
10978          end if;
10979       end if;
10980
10981       Set_Etype            (Def_Id, Base_Type        (T));
10982       Set_Size_Info        (Def_Id,                  (T));
10983       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
10984       Set_Delta_Value      (Def_Id, Delta_Value      (T));
10985       Set_Scale_Value      (Def_Id, Scale_Value      (T));
10986       Set_Small_Value      (Def_Id, Small_Value      (T));
10987       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
10988       Set_Digits_Value     (Def_Id, Digits_Val);
10989
10990       --  Manufacture range from given digits value if no range present
10991
10992       if No (Range_Expr) then
10993          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
10994          Range_Expr :=
10995            Make_Range (Loc,
10996              Low_Bound =>
10997                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
10998              High_Bound =>
10999                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
11000       end if;
11001
11002       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
11003       Set_Discrete_RM_Size (Def_Id);
11004
11005       --  Unconditionally delay the freeze, since we cannot set size
11006       --  information in all cases correctly until the freeze point.
11007
11008       Set_Has_Delayed_Freeze (Def_Id);
11009    end Constrain_Decimal;
11010
11011    ----------------------------------
11012    -- Constrain_Discriminated_Type --
11013    ----------------------------------
11014
11015    procedure Constrain_Discriminated_Type
11016      (Def_Id      : Entity_Id;
11017       S           : Node_Id;
11018       Related_Nod : Node_Id;
11019       For_Access  : Boolean := False)
11020    is
11021       E     : constant Entity_Id := Entity (Subtype_Mark (S));
11022       T     : Entity_Id;
11023       C     : Node_Id;
11024       Elist : Elist_Id := New_Elmt_List;
11025
11026       procedure Fixup_Bad_Constraint;
11027       --  This is called after finding a bad constraint, and after having
11028       --  posted an appropriate error message. The mission is to leave the
11029       --  entity T in as reasonable state as possible!
11030
11031       --------------------------
11032       -- Fixup_Bad_Constraint --
11033       --------------------------
11034
11035       procedure Fixup_Bad_Constraint is
11036       begin
11037          --  Set a reasonable Ekind for the entity. For an incomplete type,
11038          --  we can't do much, but for other types, we can set the proper
11039          --  corresponding subtype kind.
11040
11041          if Ekind (T) = E_Incomplete_Type then
11042             Set_Ekind (Def_Id, Ekind (T));
11043          else
11044             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
11045          end if;
11046
11047          --  Set Etype to the known type, to reduce chances of cascaded errors
11048
11049          Set_Etype (Def_Id, E);
11050          Set_Error_Posted (Def_Id);
11051       end Fixup_Bad_Constraint;
11052
11053    --  Start of processing for Constrain_Discriminated_Type
11054
11055    begin
11056       C := Constraint (S);
11057
11058       --  A discriminant constraint is only allowed in a subtype indication,
11059       --  after a subtype mark. This subtype mark must denote either a type
11060       --  with discriminants, or an access type whose designated type is a
11061       --  type with discriminants. A discriminant constraint specifies the
11062       --  values of these discriminants (RM 3.7.2(5)).
11063
11064       T := Base_Type (Entity (Subtype_Mark (S)));
11065
11066       if Ekind (T) in Access_Kind then
11067          T := Designated_Type (T);
11068       end if;
11069
11070       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
11071       --  Avoid generating an error for access-to-incomplete subtypes.
11072
11073       if Ada_Version >= Ada_2005
11074         and then Ekind (T) = E_Incomplete_Type
11075         and then Nkind (Parent (S)) = N_Subtype_Declaration
11076         and then not Is_Itype (Def_Id)
11077       then
11078          --  A little sanity check, emit an error message if the type
11079          --  has discriminants to begin with. Type T may be a regular
11080          --  incomplete type or imported via a limited with clause.
11081
11082          if Has_Discriminants (T)
11083            or else
11084              (From_With_Type (T)
11085                 and then Present (Non_Limited_View (T))
11086                 and then Nkind (Parent (Non_Limited_View (T))) =
11087                            N_Full_Type_Declaration
11088                 and then Present (Discriminant_Specifications
11089                           (Parent (Non_Limited_View (T)))))
11090          then
11091             Error_Msg_N
11092               ("(Ada 2005) incomplete subtype may not be constrained", C);
11093          else
11094             Error_Msg_N ("invalid constraint: type has no discriminant", C);
11095          end if;
11096
11097          Fixup_Bad_Constraint;
11098          return;
11099
11100       --  Check that the type has visible discriminants. The type may be
11101       --  a private type with unknown discriminants whose full view has
11102       --  discriminants which are invisible.
11103
11104       elsif not Has_Discriminants (T)
11105         or else
11106           (Has_Unknown_Discriminants (T)
11107              and then Is_Private_Type (T))
11108       then
11109          Error_Msg_N ("invalid constraint: type has no discriminant", C);
11110          Fixup_Bad_Constraint;
11111          return;
11112
11113       elsif Is_Constrained (E)
11114         or else (Ekind (E) = E_Class_Wide_Subtype
11115                   and then Present (Discriminant_Constraint (E)))
11116       then
11117          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
11118          Fixup_Bad_Constraint;
11119          return;
11120       end if;
11121
11122       --  T may be an unconstrained subtype (e.g. a generic actual).
11123       --  Constraint applies to the base type.
11124
11125       T := Base_Type (T);
11126
11127       Elist := Build_Discriminant_Constraints (T, S);
11128
11129       --  If the list returned was empty we had an error in building the
11130       --  discriminant constraint. We have also already signalled an error
11131       --  in the incomplete type case
11132
11133       if Is_Empty_Elmt_List (Elist) then
11134          Fixup_Bad_Constraint;
11135          return;
11136       end if;
11137
11138       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
11139    end Constrain_Discriminated_Type;
11140
11141    ---------------------------
11142    -- Constrain_Enumeration --
11143    ---------------------------
11144
11145    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
11146       T : constant Entity_Id := Entity (Subtype_Mark (S));
11147       C : constant Node_Id   := Constraint (S);
11148
11149    begin
11150       Set_Ekind (Def_Id, E_Enumeration_Subtype);
11151
11152       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
11153
11154       Set_Etype             (Def_Id, Base_Type         (T));
11155       Set_Size_Info         (Def_Id,                   (T));
11156       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
11157       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11158
11159       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11160
11161       Set_Discrete_RM_Size (Def_Id);
11162    end Constrain_Enumeration;
11163
11164    ----------------------
11165    -- Constrain_Float --
11166    ----------------------
11167
11168    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
11169       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11170       C    : Node_Id;
11171       D    : Node_Id;
11172       Rais : Node_Id;
11173
11174    begin
11175       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
11176
11177       Set_Etype          (Def_Id, Base_Type      (T));
11178       Set_Size_Info      (Def_Id,                (T));
11179       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11180
11181       --  Process the constraint
11182
11183       C := Constraint (S);
11184
11185       --  Digits constraint present
11186
11187       if Nkind (C) = N_Digits_Constraint then
11188          Check_Restriction (No_Obsolescent_Features, C);
11189
11190          if Warn_On_Obsolescent_Feature then
11191             Error_Msg_N
11192               ("subtype digits constraint is an " &
11193                "obsolescent feature (RM J.3(8))?", C);
11194          end if;
11195
11196          D := Digits_Expression (C);
11197          Analyze_And_Resolve (D, Any_Integer);
11198          Check_Digits_Expression (D);
11199          Set_Digits_Value (Def_Id, Expr_Value (D));
11200
11201          --  Check that digits value is in range. Obviously we can do this
11202          --  at compile time, but it is strictly a runtime check, and of
11203          --  course there is an ACVC test that checks this!
11204
11205          if Digits_Value (Def_Id) > Digits_Value (T) then
11206             Error_Msg_Uint_1 := Digits_Value (T);
11207             Error_Msg_N ("?digits value is too large, maximum is ^", D);
11208             Rais :=
11209               Make_Raise_Constraint_Error (Sloc (D),
11210                 Reason => CE_Range_Check_Failed);
11211             Insert_Action (Declaration_Node (Def_Id), Rais);
11212          end if;
11213
11214          C := Range_Constraint (C);
11215
11216       --  No digits constraint present
11217
11218       else
11219          Set_Digits_Value (Def_Id, Digits_Value (T));
11220       end if;
11221
11222       --  Range constraint present
11223
11224       if Nkind (C) = N_Range_Constraint then
11225          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11226
11227       --  No range constraint present
11228
11229       else
11230          pragma Assert (No (C));
11231          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11232       end if;
11233
11234       Set_Is_Constrained (Def_Id);
11235    end Constrain_Float;
11236
11237    ---------------------
11238    -- Constrain_Index --
11239    ---------------------
11240
11241    procedure Constrain_Index
11242      (Index        : Node_Id;
11243       S            : Node_Id;
11244       Related_Nod  : Node_Id;
11245       Related_Id   : Entity_Id;
11246       Suffix       : Character;
11247       Suffix_Index : Nat)
11248    is
11249       Def_Id : Entity_Id;
11250       R      : Node_Id := Empty;
11251       T      : constant Entity_Id := Etype (Index);
11252
11253    begin
11254       if Nkind (S) = N_Range
11255         or else
11256           (Nkind (S) = N_Attribute_Reference
11257             and then Attribute_Name (S) = Name_Range)
11258       then
11259          --  A Range attribute will transformed into N_Range by Resolve
11260
11261          Analyze (S);
11262          Set_Etype (S, T);
11263          R := S;
11264
11265          Process_Range_Expr_In_Decl (R, T, Empty_List);
11266
11267          if not Error_Posted (S)
11268            and then
11269              (Nkind (S) /= N_Range
11270                or else not Covers (T, (Etype (Low_Bound (S))))
11271                or else not Covers (T, (Etype (High_Bound (S)))))
11272          then
11273             if Base_Type (T) /= Any_Type
11274               and then Etype (Low_Bound (S)) /= Any_Type
11275               and then Etype (High_Bound (S)) /= Any_Type
11276             then
11277                Error_Msg_N ("range expected", S);
11278             end if;
11279          end if;
11280
11281       elsif Nkind (S) = N_Subtype_Indication then
11282
11283          --  The parser has verified that this is a discrete indication
11284
11285          Resolve_Discrete_Subtype_Indication (S, T);
11286          R := Range_Expression (Constraint (S));
11287
11288       elsif Nkind (S) = N_Discriminant_Association then
11289
11290          --  Syntactically valid in subtype indication
11291
11292          Error_Msg_N ("invalid index constraint", S);
11293          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11294          return;
11295
11296       --  Subtype_Mark case, no anonymous subtypes to construct
11297
11298       else
11299          Analyze (S);
11300
11301          if Is_Entity_Name (S) then
11302             if not Is_Type (Entity (S)) then
11303                Error_Msg_N ("expect subtype mark for index constraint", S);
11304
11305             elsif Base_Type (Entity (S)) /= Base_Type (T) then
11306                Wrong_Type (S, Base_Type (T));
11307             end if;
11308
11309             return;
11310
11311          else
11312             Error_Msg_N ("invalid index constraint", S);
11313             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11314             return;
11315          end if;
11316       end if;
11317
11318       Def_Id :=
11319         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
11320
11321       Set_Etype (Def_Id, Base_Type (T));
11322
11323       if Is_Modular_Integer_Type (T) then
11324          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11325
11326       elsif Is_Integer_Type (T) then
11327          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11328
11329       else
11330          Set_Ekind (Def_Id, E_Enumeration_Subtype);
11331          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11332          Set_First_Literal     (Def_Id, First_Literal (T));
11333       end if;
11334
11335       Set_Size_Info      (Def_Id,                (T));
11336       Set_RM_Size        (Def_Id, RM_Size        (T));
11337       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11338
11339       Set_Scalar_Range   (Def_Id, R);
11340
11341       Set_Etype (S, Def_Id);
11342       Set_Discrete_RM_Size (Def_Id);
11343    end Constrain_Index;
11344
11345    -----------------------
11346    -- Constrain_Integer --
11347    -----------------------
11348
11349    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
11350       T : constant Entity_Id := Entity (Subtype_Mark (S));
11351       C : constant Node_Id   := Constraint (S);
11352
11353    begin
11354       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11355
11356       if Is_Modular_Integer_Type (T) then
11357          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11358       else
11359          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11360       end if;
11361
11362       Set_Etype            (Def_Id, Base_Type        (T));
11363       Set_Size_Info        (Def_Id,                  (T));
11364       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11365       Set_Discrete_RM_Size (Def_Id);
11366    end Constrain_Integer;
11367
11368    ------------------------------
11369    -- Constrain_Ordinary_Fixed --
11370    ------------------------------
11371
11372    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
11373       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11374       C    : Node_Id;
11375       D    : Node_Id;
11376       Rais : Node_Id;
11377
11378    begin
11379       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
11380       Set_Etype          (Def_Id, Base_Type        (T));
11381       Set_Size_Info      (Def_Id,                  (T));
11382       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
11383       Set_Small_Value    (Def_Id, Small_Value      (T));
11384
11385       --  Process the constraint
11386
11387       C := Constraint (S);
11388
11389       --  Delta constraint present
11390
11391       if Nkind (C) = N_Delta_Constraint then
11392          Check_Restriction (No_Obsolescent_Features, C);
11393
11394          if Warn_On_Obsolescent_Feature then
11395             Error_Msg_S
11396               ("subtype delta constraint is an " &
11397                "obsolescent feature (RM J.3(7))?");
11398          end if;
11399
11400          D := Delta_Expression (C);
11401          Analyze_And_Resolve (D, Any_Real);
11402          Check_Delta_Expression (D);
11403          Set_Delta_Value (Def_Id, Expr_Value_R (D));
11404
11405          --  Check that delta value is in range. Obviously we can do this
11406          --  at compile time, but it is strictly a runtime check, and of
11407          --  course there is an ACVC test that checks this!
11408
11409          if Delta_Value (Def_Id) < Delta_Value (T) then
11410             Error_Msg_N ("?delta value is too small", D);
11411             Rais :=
11412               Make_Raise_Constraint_Error (Sloc (D),
11413                 Reason => CE_Range_Check_Failed);
11414             Insert_Action (Declaration_Node (Def_Id), Rais);
11415          end if;
11416
11417          C := Range_Constraint (C);
11418
11419       --  No delta constraint present
11420
11421       else
11422          Set_Delta_Value (Def_Id, Delta_Value (T));
11423       end if;
11424
11425       --  Range constraint present
11426
11427       if Nkind (C) = N_Range_Constraint then
11428          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11429
11430       --  No range constraint present
11431
11432       else
11433          pragma Assert (No (C));
11434          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11435
11436       end if;
11437
11438       Set_Discrete_RM_Size (Def_Id);
11439
11440       --  Unconditionally delay the freeze, since we cannot set size
11441       --  information in all cases correctly until the freeze point.
11442
11443       Set_Has_Delayed_Freeze (Def_Id);
11444    end Constrain_Ordinary_Fixed;
11445
11446    -----------------------
11447    -- Contain_Interface --
11448    -----------------------
11449
11450    function Contain_Interface
11451      (Iface  : Entity_Id;
11452       Ifaces : Elist_Id) return Boolean
11453    is
11454       Iface_Elmt : Elmt_Id;
11455
11456    begin
11457       if Present (Ifaces) then
11458          Iface_Elmt := First_Elmt (Ifaces);
11459          while Present (Iface_Elmt) loop
11460             if Node (Iface_Elmt) = Iface then
11461                return True;
11462             end if;
11463
11464             Next_Elmt (Iface_Elmt);
11465          end loop;
11466       end if;
11467
11468       return False;
11469    end Contain_Interface;
11470
11471    ---------------------------
11472    -- Convert_Scalar_Bounds --
11473    ---------------------------
11474
11475    procedure Convert_Scalar_Bounds
11476      (N            : Node_Id;
11477       Parent_Type  : Entity_Id;
11478       Derived_Type : Entity_Id;
11479       Loc          : Source_Ptr)
11480    is
11481       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
11482
11483       Lo  : Node_Id;
11484       Hi  : Node_Id;
11485       Rng : Node_Id;
11486
11487    begin
11488       --  Defend against previous errors
11489
11490       if No (Scalar_Range (Derived_Type)) then
11491          return;
11492       end if;
11493
11494       Lo := Build_Scalar_Bound
11495               (Type_Low_Bound (Derived_Type),
11496                Parent_Type, Implicit_Base);
11497
11498       Hi := Build_Scalar_Bound
11499               (Type_High_Bound (Derived_Type),
11500                Parent_Type, Implicit_Base);
11501
11502       Rng :=
11503         Make_Range (Loc,
11504           Low_Bound  => Lo,
11505           High_Bound => Hi);
11506
11507       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
11508
11509       Set_Parent (Rng, N);
11510       Set_Scalar_Range (Derived_Type, Rng);
11511
11512       --  Analyze the bounds
11513
11514       Analyze_And_Resolve (Lo, Implicit_Base);
11515       Analyze_And_Resolve (Hi, Implicit_Base);
11516
11517       --  Analyze the range itself, except that we do not analyze it if
11518       --  the bounds are real literals, and we have a fixed-point type.
11519       --  The reason for this is that we delay setting the bounds in this
11520       --  case till we know the final Small and Size values (see circuit
11521       --  in Freeze.Freeze_Fixed_Point_Type for further details).
11522
11523       if Is_Fixed_Point_Type (Parent_Type)
11524         and then Nkind (Lo) = N_Real_Literal
11525         and then Nkind (Hi) = N_Real_Literal
11526       then
11527          return;
11528
11529       --  Here we do the analysis of the range
11530
11531       --  Note: we do this manually, since if we do a normal Analyze and
11532       --  Resolve call, there are problems with the conversions used for
11533       --  the derived type range.
11534
11535       else
11536          Set_Etype    (Rng, Implicit_Base);
11537          Set_Analyzed (Rng, True);
11538       end if;
11539    end Convert_Scalar_Bounds;
11540
11541    -------------------
11542    -- Copy_And_Swap --
11543    -------------------
11544
11545    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
11546    begin
11547       --  Initialize new full declaration entity by copying the pertinent
11548       --  fields of the corresponding private declaration entity.
11549
11550       --  We temporarily set Ekind to a value appropriate for a type to
11551       --  avoid assert failures in Einfo from checking for setting type
11552       --  attributes on something that is not a type. Ekind (Priv) is an
11553       --  appropriate choice, since it allowed the attributes to be set
11554       --  in the first place. This Ekind value will be modified later.
11555
11556       Set_Ekind (Full, Ekind (Priv));
11557
11558       --  Also set Etype temporarily to Any_Type, again, in the absence
11559       --  of errors, it will be properly reset, and if there are errors,
11560       --  then we want a value of Any_Type to remain.
11561
11562       Set_Etype (Full, Any_Type);
11563
11564       --  Now start copying attributes
11565
11566       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
11567
11568       if Has_Discriminants (Full) then
11569          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
11570          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
11571       end if;
11572
11573       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
11574       Set_Homonym                    (Full, Homonym                 (Priv));
11575       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
11576       Set_Is_Public                  (Full, Is_Public               (Priv));
11577       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
11578       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
11579       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
11580       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
11581       Set_Has_Pragma_Unreferenced_Objects
11582                                      (Full, Has_Pragma_Unreferenced_Objects
11583                                                                     (Priv));
11584
11585       Conditional_Delay              (Full,                          Priv);
11586
11587       if Is_Tagged_Type (Full) then
11588          Set_Direct_Primitive_Operations (Full,
11589            Direct_Primitive_Operations (Priv));
11590
11591          if Priv = Base_Type (Priv) then
11592             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
11593          end if;
11594       end if;
11595
11596       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
11597       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
11598       Set_Scope                      (Full, Scope                   (Priv));
11599       Set_Next_Entity                (Full, Next_Entity             (Priv));
11600       Set_First_Entity               (Full, First_Entity            (Priv));
11601       Set_Last_Entity                (Full, Last_Entity             (Priv));
11602
11603       --  If access types have been recorded for later handling, keep them in
11604       --  the full view so that they get handled when the full view freeze
11605       --  node is expanded.
11606
11607       if Present (Freeze_Node (Priv))
11608         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
11609       then
11610          Ensure_Freeze_Node (Full);
11611          Set_Access_Types_To_Process
11612            (Freeze_Node (Full),
11613             Access_Types_To_Process (Freeze_Node (Priv)));
11614       end if;
11615
11616       --  Swap the two entities. Now Privat is the full type entity and Full is
11617       --  the private one. They will be swapped back at the end of the private
11618       --  part. This swapping ensures that the entity that is visible in the
11619       --  private part is the full declaration.
11620
11621       Exchange_Entities (Priv, Full);
11622       Append_Entity (Full, Scope (Full));
11623    end Copy_And_Swap;
11624
11625    -------------------------------------
11626    -- Copy_Array_Base_Type_Attributes --
11627    -------------------------------------
11628
11629    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
11630    begin
11631       Set_Component_Alignment      (T1, Component_Alignment      (T2));
11632       Set_Component_Type           (T1, Component_Type           (T2));
11633       Set_Component_Size           (T1, Component_Size           (T2));
11634       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
11635       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
11636       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
11637       Set_Has_Task                 (T1, Has_Task                 (T2));
11638       Set_Is_Packed                (T1, Is_Packed                (T2));
11639       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
11640       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
11641       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
11642    end Copy_Array_Base_Type_Attributes;
11643
11644    -----------------------------------
11645    -- Copy_Array_Subtype_Attributes --
11646    -----------------------------------
11647
11648    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
11649    begin
11650       Set_Size_Info (T1, T2);
11651
11652       Set_First_Index          (T1, First_Index           (T2));
11653       Set_Is_Aliased           (T1, Is_Aliased            (T2));
11654       Set_Is_Atomic            (T1, Is_Atomic             (T2));
11655       Set_Is_Volatile          (T1, Is_Volatile           (T2));
11656       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
11657       Set_Is_Constrained       (T1, Is_Constrained        (T2));
11658       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
11659       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
11660       Set_Convention           (T1, Convention            (T2));
11661       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
11662       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
11663       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
11664    end Copy_Array_Subtype_Attributes;
11665
11666    -----------------------------------
11667    -- Create_Constrained_Components --
11668    -----------------------------------
11669
11670    procedure Create_Constrained_Components
11671      (Subt        : Entity_Id;
11672       Decl_Node   : Node_Id;
11673       Typ         : Entity_Id;
11674       Constraints : Elist_Id)
11675    is
11676       Loc         : constant Source_Ptr := Sloc (Subt);
11677       Comp_List   : constant Elist_Id   := New_Elmt_List;
11678       Parent_Type : constant Entity_Id  := Etype (Typ);
11679       Assoc_List  : constant List_Id    := New_List;
11680       Discr_Val   : Elmt_Id;
11681       Errors      : Boolean;
11682       New_C       : Entity_Id;
11683       Old_C       : Entity_Id;
11684       Is_Static   : Boolean := True;
11685
11686       procedure Collect_Fixed_Components (Typ : Entity_Id);
11687       --  Collect parent type components that do not appear in a variant part
11688
11689       procedure Create_All_Components;
11690       --  Iterate over Comp_List to create the components of the subtype
11691
11692       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
11693       --  Creates a new component from Old_Compon, copying all the fields from
11694       --  it, including its Etype, inserts the new component in the Subt entity
11695       --  chain and returns the new component.
11696
11697       function Is_Variant_Record (T : Entity_Id) return Boolean;
11698       --  If true, and discriminants are static, collect only components from
11699       --  variants selected by discriminant values.
11700
11701       ------------------------------
11702       -- Collect_Fixed_Components --
11703       ------------------------------
11704
11705       procedure Collect_Fixed_Components (Typ : Entity_Id) is
11706       begin
11707       --  Build association list for discriminants, and find components of the
11708       --  variant part selected by the values of the discriminants.
11709
11710          Old_C := First_Discriminant (Typ);
11711          Discr_Val := First_Elmt (Constraints);
11712          while Present (Old_C) loop
11713             Append_To (Assoc_List,
11714               Make_Component_Association (Loc,
11715                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
11716                  Expression => New_Copy (Node (Discr_Val))));
11717
11718             Next_Elmt (Discr_Val);
11719             Next_Discriminant (Old_C);
11720          end loop;
11721
11722          --  The tag, and the possible parent and controller components
11723          --  are unconditionally in the subtype.
11724
11725          if Is_Tagged_Type (Typ)
11726            or else Has_Controlled_Component (Typ)
11727          then
11728             Old_C := First_Component (Typ);
11729             while Present (Old_C) loop
11730                if Chars ((Old_C)) = Name_uTag
11731                  or else Chars ((Old_C)) = Name_uParent
11732                  or else Chars ((Old_C)) = Name_uController
11733                then
11734                   Append_Elmt (Old_C, Comp_List);
11735                end if;
11736
11737                Next_Component (Old_C);
11738             end loop;
11739          end if;
11740       end Collect_Fixed_Components;
11741
11742       ---------------------------
11743       -- Create_All_Components --
11744       ---------------------------
11745
11746       procedure Create_All_Components is
11747          Comp : Elmt_Id;
11748
11749       begin
11750          Comp := First_Elmt (Comp_List);
11751          while Present (Comp) loop
11752             Old_C := Node (Comp);
11753             New_C := Create_Component (Old_C);
11754
11755             Set_Etype
11756               (New_C,
11757                Constrain_Component_Type
11758                  (Old_C, Subt, Decl_Node, Typ, Constraints));
11759             Set_Is_Public (New_C, Is_Public (Subt));
11760
11761             Next_Elmt (Comp);
11762          end loop;
11763       end Create_All_Components;
11764
11765       ----------------------
11766       -- Create_Component --
11767       ----------------------
11768
11769       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
11770          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
11771
11772       begin
11773          if Ekind (Old_Compon) = E_Discriminant
11774            and then Is_Completely_Hidden (Old_Compon)
11775          then
11776             --  This is a shadow discriminant created for a discriminant of
11777             --  the parent type, which needs to be present in the subtype.
11778             --  Give the shadow discriminant an internal name that cannot
11779             --  conflict with that of visible components.
11780
11781             Set_Chars (New_Compon, New_Internal_Name ('C'));
11782          end if;
11783
11784          --  Set the parent so we have a proper link for freezing etc. This is
11785          --  not a real parent pointer, since of course our parent does not own
11786          --  up to us and reference us, we are an illegitimate child of the
11787          --  original parent!
11788
11789          Set_Parent (New_Compon, Parent (Old_Compon));
11790
11791          --  If the old component's Esize was already determined and is a
11792          --  static value, then the new component simply inherits it. Otherwise
11793          --  the old component's size may require run-time determination, but
11794          --  the new component's size still might be statically determinable
11795          --  (if, for example it has a static constraint). In that case we want
11796          --  Layout_Type to recompute the component's size, so we reset its
11797          --  size and positional fields.
11798
11799          if Frontend_Layout_On_Target
11800            and then not Known_Static_Esize (Old_Compon)
11801          then
11802             Set_Esize (New_Compon, Uint_0);
11803             Init_Normalized_First_Bit    (New_Compon);
11804             Init_Normalized_Position     (New_Compon);
11805             Init_Normalized_Position_Max (New_Compon);
11806          end if;
11807
11808          --  We do not want this node marked as Comes_From_Source, since
11809          --  otherwise it would get first class status and a separate cross-
11810          --  reference line would be generated. Illegitimate children do not
11811          --  rate such recognition.
11812
11813          Set_Comes_From_Source (New_Compon, False);
11814
11815          --  But it is a real entity, and a birth certificate must be properly
11816          --  registered by entering it into the entity list.
11817
11818          Enter_Name (New_Compon);
11819
11820          return New_Compon;
11821       end Create_Component;
11822
11823       -----------------------
11824       -- Is_Variant_Record --
11825       -----------------------
11826
11827       function Is_Variant_Record (T : Entity_Id) return Boolean is
11828       begin
11829          return Nkind (Parent (T)) = N_Full_Type_Declaration
11830            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
11831            and then Present (Component_List (Type_Definition (Parent (T))))
11832            and then
11833              Present
11834                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
11835       end Is_Variant_Record;
11836
11837    --  Start of processing for Create_Constrained_Components
11838
11839    begin
11840       pragma Assert (Subt /= Base_Type (Subt));
11841       pragma Assert (Typ = Base_Type (Typ));
11842
11843       Set_First_Entity (Subt, Empty);
11844       Set_Last_Entity  (Subt, Empty);
11845
11846       --  Check whether constraint is fully static, in which case we can
11847       --  optimize the list of components.
11848
11849       Discr_Val := First_Elmt (Constraints);
11850       while Present (Discr_Val) loop
11851          if not Is_OK_Static_Expression (Node (Discr_Val)) then
11852             Is_Static := False;
11853             exit;
11854          end if;
11855
11856          Next_Elmt (Discr_Val);
11857       end loop;
11858
11859       Set_Has_Static_Discriminants (Subt, Is_Static);
11860
11861       Push_Scope (Subt);
11862
11863       --  Inherit the discriminants of the parent type
11864
11865       Add_Discriminants : declare
11866          Num_Disc : Int;
11867          Num_Gird : Int;
11868
11869       begin
11870          Num_Disc := 0;
11871          Old_C := First_Discriminant (Typ);
11872
11873          while Present (Old_C) loop
11874             Num_Disc := Num_Disc + 1;
11875             New_C := Create_Component (Old_C);
11876             Set_Is_Public (New_C, Is_Public (Subt));
11877             Next_Discriminant (Old_C);
11878          end loop;
11879
11880          --  For an untagged derived subtype, the number of discriminants may
11881          --  be smaller than the number of inherited discriminants, because
11882          --  several of them may be renamed by a single new discriminant or
11883          --  constrained. In this case, add the hidden discriminants back into
11884          --  the subtype, because they need to be present if the optimizer of
11885          --  the GCC 4.x back-end decides to break apart assignments between
11886          --  objects using the parent view into member-wise assignments.
11887
11888          Num_Gird := 0;
11889
11890          if Is_Derived_Type (Typ)
11891            and then not Is_Tagged_Type (Typ)
11892          then
11893             Old_C := First_Stored_Discriminant (Typ);
11894
11895             while Present (Old_C) loop
11896                Num_Gird := Num_Gird + 1;
11897                Next_Stored_Discriminant (Old_C);
11898             end loop;
11899          end if;
11900
11901          if Num_Gird > Num_Disc then
11902
11903             --  Find out multiple uses of new discriminants, and add hidden
11904             --  components for the extra renamed discriminants. We recognize
11905             --  multiple uses through the Corresponding_Discriminant of a
11906             --  new discriminant: if it constrains several old discriminants,
11907             --  this field points to the last one in the parent type. The
11908             --  stored discriminants of the derived type have the same name
11909             --  as those of the parent.
11910
11911             declare
11912                Constr    : Elmt_Id;
11913                New_Discr : Entity_Id;
11914                Old_Discr : Entity_Id;
11915
11916             begin
11917                Constr    := First_Elmt (Stored_Constraint (Typ));
11918                Old_Discr := First_Stored_Discriminant (Typ);
11919                while Present (Constr) loop
11920                   if Is_Entity_Name (Node (Constr))
11921                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
11922                   then
11923                      New_Discr := Entity (Node (Constr));
11924
11925                      if Chars (Corresponding_Discriminant (New_Discr)) /=
11926                         Chars (Old_Discr)
11927                      then
11928                         --  The new discriminant has been used to rename a
11929                         --  subsequent old discriminant. Introduce a shadow
11930                         --  component for the current old discriminant.
11931
11932                         New_C := Create_Component (Old_Discr);
11933                         Set_Original_Record_Component (New_C, Old_Discr);
11934                      end if;
11935
11936                   else
11937                      --  The constraint has eliminated the old discriminant.
11938                      --  Introduce a shadow component.
11939
11940                      New_C := Create_Component (Old_Discr);
11941                      Set_Original_Record_Component (New_C, Old_Discr);
11942                   end if;
11943
11944                   Next_Elmt (Constr);
11945                   Next_Stored_Discriminant (Old_Discr);
11946                end loop;
11947             end;
11948          end if;
11949       end Add_Discriminants;
11950
11951       if Is_Static
11952         and then Is_Variant_Record (Typ)
11953       then
11954          Collect_Fixed_Components (Typ);
11955
11956          Gather_Components (
11957            Typ,
11958            Component_List (Type_Definition (Parent (Typ))),
11959            Governed_By   => Assoc_List,
11960            Into          => Comp_List,
11961            Report_Errors => Errors);
11962          pragma Assert (not Errors);
11963
11964          Create_All_Components;
11965
11966       --  If the subtype declaration is created for a tagged type derivation
11967       --  with constraints, we retrieve the record definition of the parent
11968       --  type to select the components of the proper variant.
11969
11970       elsif Is_Static
11971         and then Is_Tagged_Type (Typ)
11972         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
11973         and then
11974           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
11975         and then Is_Variant_Record (Parent_Type)
11976       then
11977          Collect_Fixed_Components (Typ);
11978
11979          Gather_Components (
11980            Typ,
11981            Component_List (Type_Definition (Parent (Parent_Type))),
11982            Governed_By   => Assoc_List,
11983            Into          => Comp_List,
11984            Report_Errors => Errors);
11985          pragma Assert (not Errors);
11986
11987          --  If the tagged derivation has a type extension, collect all the
11988          --  new components therein.
11989
11990          if Present
11991               (Record_Extension_Part (Type_Definition (Parent (Typ))))
11992          then
11993             Old_C := First_Component (Typ);
11994             while Present (Old_C) loop
11995                if Original_Record_Component (Old_C) = Old_C
11996                 and then Chars (Old_C) /= Name_uTag
11997                 and then Chars (Old_C) /= Name_uParent
11998                 and then Chars (Old_C) /= Name_uController
11999                then
12000                   Append_Elmt (Old_C, Comp_List);
12001                end if;
12002
12003                Next_Component (Old_C);
12004             end loop;
12005          end if;
12006
12007          Create_All_Components;
12008
12009       else
12010          --  If discriminants are not static, or if this is a multi-level type
12011          --  extension, we have to include all components of the parent type.
12012
12013          Old_C := First_Component (Typ);
12014          while Present (Old_C) loop
12015             New_C := Create_Component (Old_C);
12016
12017             Set_Etype
12018               (New_C,
12019                Constrain_Component_Type
12020                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12021             Set_Is_Public (New_C, Is_Public (Subt));
12022
12023             Next_Component (Old_C);
12024          end loop;
12025       end if;
12026
12027       End_Scope;
12028    end Create_Constrained_Components;
12029
12030    ------------------------------------------
12031    -- Decimal_Fixed_Point_Type_Declaration --
12032    ------------------------------------------
12033
12034    procedure Decimal_Fixed_Point_Type_Declaration
12035      (T   : Entity_Id;
12036       Def : Node_Id)
12037    is
12038       Loc           : constant Source_Ptr := Sloc (Def);
12039       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
12040       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
12041       Implicit_Base : Entity_Id;
12042       Digs_Val      : Uint;
12043       Delta_Val     : Ureal;
12044       Scale_Val     : Uint;
12045       Bound_Val     : Ureal;
12046
12047    begin
12048       Check_Restriction (No_Fixed_Point, Def);
12049
12050       --  Create implicit base type
12051
12052       Implicit_Base :=
12053         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
12054       Set_Etype (Implicit_Base, Implicit_Base);
12055
12056       --  Analyze and process delta expression
12057
12058       Analyze_And_Resolve (Delta_Expr, Universal_Real);
12059
12060       Check_Delta_Expression (Delta_Expr);
12061       Delta_Val := Expr_Value_R (Delta_Expr);
12062
12063       --  Check delta is power of 10, and determine scale value from it
12064
12065       declare
12066          Val : Ureal;
12067
12068       begin
12069          Scale_Val := Uint_0;
12070          Val := Delta_Val;
12071
12072          if Val < Ureal_1 then
12073             while Val < Ureal_1 loop
12074                Val := Val * Ureal_10;
12075                Scale_Val := Scale_Val + 1;
12076             end loop;
12077
12078             if Scale_Val > 18 then
12079                Error_Msg_N ("scale exceeds maximum value of 18", Def);
12080                Scale_Val := UI_From_Int (+18);
12081             end if;
12082
12083          else
12084             while Val > Ureal_1 loop
12085                Val := Val / Ureal_10;
12086                Scale_Val := Scale_Val - 1;
12087             end loop;
12088
12089             if Scale_Val < -18 then
12090                Error_Msg_N ("scale is less than minimum value of -18", Def);
12091                Scale_Val := UI_From_Int (-18);
12092             end if;
12093          end if;
12094
12095          if Val /= Ureal_1 then
12096             Error_Msg_N ("delta expression must be a power of 10", Def);
12097             Delta_Val := Ureal_10 ** (-Scale_Val);
12098          end if;
12099       end;
12100
12101       --  Set delta, scale and small (small = delta for decimal type)
12102
12103       Set_Delta_Value (Implicit_Base, Delta_Val);
12104       Set_Scale_Value (Implicit_Base, Scale_Val);
12105       Set_Small_Value (Implicit_Base, Delta_Val);
12106
12107       --  Analyze and process digits expression
12108
12109       Analyze_And_Resolve (Digs_Expr, Any_Integer);
12110       Check_Digits_Expression (Digs_Expr);
12111       Digs_Val := Expr_Value (Digs_Expr);
12112
12113       if Digs_Val > 18 then
12114          Digs_Val := UI_From_Int (+18);
12115          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
12116       end if;
12117
12118       Set_Digits_Value (Implicit_Base, Digs_Val);
12119       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
12120
12121       --  Set range of base type from digits value for now. This will be
12122       --  expanded to represent the true underlying base range by Freeze.
12123
12124       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
12125
12126       --  Note: We leave size as zero for now, size will be set at freeze
12127       --  time. We have to do this for ordinary fixed-point, because the size
12128       --  depends on the specified small, and we might as well do the same for
12129       --  decimal fixed-point.
12130
12131       pragma Assert (Esize (Implicit_Base) = Uint_0);
12132
12133       --  If there are bounds given in the declaration use them as the
12134       --  bounds of the first named subtype.
12135
12136       if Present (Real_Range_Specification (Def)) then
12137          declare
12138             RRS      : constant Node_Id := Real_Range_Specification (Def);
12139             Low      : constant Node_Id := Low_Bound (RRS);
12140             High     : constant Node_Id := High_Bound (RRS);
12141             Low_Val  : Ureal;
12142             High_Val : Ureal;
12143
12144          begin
12145             Analyze_And_Resolve (Low, Any_Real);
12146             Analyze_And_Resolve (High, Any_Real);
12147             Check_Real_Bound (Low);
12148             Check_Real_Bound (High);
12149             Low_Val := Expr_Value_R (Low);
12150             High_Val := Expr_Value_R (High);
12151
12152             if Low_Val < (-Bound_Val) then
12153                Error_Msg_N
12154                  ("range low bound too small for digits value", Low);
12155                Low_Val := -Bound_Val;
12156             end if;
12157
12158             if High_Val > Bound_Val then
12159                Error_Msg_N
12160                  ("range high bound too large for digits value", High);
12161                High_Val := Bound_Val;
12162             end if;
12163
12164             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
12165          end;
12166
12167       --  If no explicit range, use range that corresponds to given
12168       --  digits value. This will end up as the final range for the
12169       --  first subtype.
12170
12171       else
12172          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
12173       end if;
12174
12175       --  Complete entity for first subtype
12176
12177       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
12178       Set_Etype          (T, Implicit_Base);
12179       Set_Size_Info      (T, Implicit_Base);
12180       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
12181       Set_Digits_Value   (T, Digs_Val);
12182       Set_Delta_Value    (T, Delta_Val);
12183       Set_Small_Value    (T, Delta_Val);
12184       Set_Scale_Value    (T, Scale_Val);
12185       Set_Is_Constrained (T);
12186    end Decimal_Fixed_Point_Type_Declaration;
12187
12188    -----------------------------------
12189    -- Derive_Progenitor_Subprograms --
12190    -----------------------------------
12191
12192    procedure Derive_Progenitor_Subprograms
12193      (Parent_Type : Entity_Id;
12194       Tagged_Type : Entity_Id)
12195    is
12196       E          : Entity_Id;
12197       Elmt       : Elmt_Id;
12198       Iface      : Entity_Id;
12199       Iface_Elmt : Elmt_Id;
12200       Iface_Subp : Entity_Id;
12201       New_Subp   : Entity_Id := Empty;
12202       Prim_Elmt  : Elmt_Id;
12203       Subp       : Entity_Id;
12204       Typ        : Entity_Id;
12205
12206    begin
12207       pragma Assert (Ada_Version >= Ada_2005
12208         and then Is_Record_Type (Tagged_Type)
12209         and then Is_Tagged_Type (Tagged_Type)
12210         and then Has_Interfaces (Tagged_Type));
12211
12212       --  Step 1: Transfer to the full-view primitives associated with the
12213       --  partial-view that cover interface primitives. Conceptually this
12214       --  work should be done later by Process_Full_View; done here to
12215       --  simplify its implementation at later stages. It can be safely
12216       --  done here because interfaces must be visible in the partial and
12217       --  private view (RM 7.3(7.3/2)).
12218
12219       --  Small optimization: This work is only required if the parent is
12220       --  abstract. If the tagged type is not abstract, it cannot have
12221       --  abstract primitives (the only entities in the list of primitives of
12222       --  non-abstract tagged types that can reference abstract primitives
12223       --  through its Alias attribute are the internal entities that have
12224       --  attribute Interface_Alias, and these entities are generated later
12225       --  by Add_Internal_Interface_Entities).
12226
12227       if In_Private_Part (Current_Scope)
12228         and then Is_Abstract_Type (Parent_Type)
12229       then
12230          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
12231          while Present (Elmt) loop
12232             Subp := Node (Elmt);
12233
12234             --  At this stage it is not possible to have entities in the list
12235             --  of primitives that have attribute Interface_Alias
12236
12237             pragma Assert (No (Interface_Alias (Subp)));
12238
12239             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
12240
12241             if Is_Interface (Typ) then
12242                E := Find_Primitive_Covering_Interface
12243                       (Tagged_Type => Tagged_Type,
12244                        Iface_Prim  => Subp);
12245
12246                if Present (E)
12247                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
12248                then
12249                   Replace_Elmt (Elmt, E);
12250                   Remove_Homonym (Subp);
12251                end if;
12252             end if;
12253
12254             Next_Elmt (Elmt);
12255          end loop;
12256       end if;
12257
12258       --  Step 2: Add primitives of progenitors that are not implemented by
12259       --  parents of Tagged_Type
12260
12261       if Present (Interfaces (Base_Type (Tagged_Type))) then
12262          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
12263          while Present (Iface_Elmt) loop
12264             Iface := Node (Iface_Elmt);
12265
12266             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
12267             while Present (Prim_Elmt) loop
12268                Iface_Subp := Node (Prim_Elmt);
12269
12270                --  Exclude derivation of predefined primitives except those
12271                --  that come from source. Required to catch declarations of
12272                --  equality operators of interfaces. For example:
12273
12274                --     type Iface is interface;
12275                --     function "=" (Left, Right : Iface) return Boolean;
12276
12277                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
12278                  or else Comes_From_Source (Iface_Subp)
12279                then
12280                   E := Find_Primitive_Covering_Interface
12281                          (Tagged_Type => Tagged_Type,
12282                           Iface_Prim  => Iface_Subp);
12283
12284                   --  If not found we derive a new primitive leaving its alias
12285                   --  attribute referencing the interface primitive
12286
12287                   if No (E) then
12288                      Derive_Subprogram
12289                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12290
12291                   --  Propagate to the full view interface entities associated
12292                   --  with the partial view
12293
12294                   elsif In_Private_Part (Current_Scope)
12295                     and then Present (Alias (E))
12296                     and then Alias (E) = Iface_Subp
12297                     and then
12298                       List_Containing (Parent (E)) /=
12299                         Private_Declarations
12300                           (Specification
12301                             (Unit_Declaration_Node (Current_Scope)))
12302                   then
12303                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
12304                   end if;
12305                end if;
12306
12307                Next_Elmt (Prim_Elmt);
12308             end loop;
12309
12310             Next_Elmt (Iface_Elmt);
12311          end loop;
12312       end if;
12313    end Derive_Progenitor_Subprograms;
12314
12315    -----------------------
12316    -- Derive_Subprogram --
12317    -----------------------
12318
12319    procedure Derive_Subprogram
12320      (New_Subp     : in out Entity_Id;
12321       Parent_Subp  : Entity_Id;
12322       Derived_Type : Entity_Id;
12323       Parent_Type  : Entity_Id;
12324       Actual_Subp  : Entity_Id := Empty)
12325    is
12326       Formal : Entity_Id;
12327       --  Formal parameter of parent primitive operation
12328
12329       Formal_Of_Actual : Entity_Id;
12330       --  Formal parameter of actual operation, when the derivation is to
12331       --  create a renaming for a primitive operation of an actual in an
12332       --  instantiation.
12333
12334       New_Formal : Entity_Id;
12335       --  Formal of inherited operation
12336
12337       Visible_Subp : Entity_Id := Parent_Subp;
12338
12339       function Is_Private_Overriding return Boolean;
12340       --  If Subp is a private overriding of a visible operation, the inherited
12341       --  operation derives from the overridden op (even though its body is the
12342       --  overriding one) and the inherited operation is visible now. See
12343       --  sem_disp to see the full details of the handling of the overridden
12344       --  subprogram, which is removed from the list of primitive operations of
12345       --  the type. The overridden subprogram is saved locally in Visible_Subp,
12346       --  and used to diagnose abstract operations that need overriding in the
12347       --  derived type.
12348
12349       procedure Replace_Type (Id, New_Id : Entity_Id);
12350       --  When the type is an anonymous access type, create a new access type
12351       --  designating the derived type.
12352
12353       procedure Set_Derived_Name;
12354       --  This procedure sets the appropriate Chars name for New_Subp. This
12355       --  is normally just a copy of the parent name. An exception arises for
12356       --  type support subprograms, where the name is changed to reflect the
12357       --  name of the derived type, e.g. if type foo is derived from type bar,
12358       --  then a procedure barDA is derived with a name fooDA.
12359
12360       ---------------------------
12361       -- Is_Private_Overriding --
12362       ---------------------------
12363
12364       function Is_Private_Overriding return Boolean is
12365          Prev : Entity_Id;
12366
12367       begin
12368          --  If the parent is not a dispatching operation there is no
12369          --  need to investigate overridings
12370
12371          if not Is_Dispatching_Operation (Parent_Subp) then
12372             return False;
12373          end if;
12374
12375          --  The visible operation that is overridden is a homonym of the
12376          --  parent subprogram. We scan the homonym chain to find the one
12377          --  whose alias is the subprogram we are deriving.
12378
12379          Prev := Current_Entity (Parent_Subp);
12380          while Present (Prev) loop
12381             if Ekind (Prev) = Ekind (Parent_Subp)
12382               and then Alias (Prev) = Parent_Subp
12383               and then Scope (Parent_Subp) = Scope (Prev)
12384               and then not Is_Hidden (Prev)
12385             then
12386                Visible_Subp := Prev;
12387                return True;
12388             end if;
12389
12390             Prev := Homonym (Prev);
12391          end loop;
12392
12393          return False;
12394       end Is_Private_Overriding;
12395
12396       ------------------
12397       -- Replace_Type --
12398       ------------------
12399
12400       procedure Replace_Type (Id, New_Id : Entity_Id) is
12401          Acc_Type : Entity_Id;
12402          Par      : constant Node_Id := Parent (Derived_Type);
12403
12404       begin
12405          --  When the type is an anonymous access type, create a new access
12406          --  type designating the derived type. This itype must be elaborated
12407          --  at the point of the derivation, not on subsequent calls that may
12408          --  be out of the proper scope for Gigi, so we insert a reference to
12409          --  it after the derivation.
12410
12411          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
12412             declare
12413                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
12414
12415             begin
12416                if Ekind (Desig_Typ) = E_Record_Type_With_Private
12417                  and then Present (Full_View (Desig_Typ))
12418                  and then not Is_Private_Type (Parent_Type)
12419                then
12420                   Desig_Typ := Full_View (Desig_Typ);
12421                end if;
12422
12423                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
12424
12425                   --  Ada 2005 (AI-251): Handle also derivations of abstract
12426                   --  interface primitives.
12427
12428                  or else (Is_Interface (Desig_Typ)
12429                           and then not Is_Class_Wide_Type (Desig_Typ))
12430                then
12431                   Acc_Type := New_Copy (Etype (Id));
12432                   Set_Etype (Acc_Type, Acc_Type);
12433                   Set_Scope (Acc_Type, New_Subp);
12434
12435                   --  Compute size of anonymous access type
12436
12437                   if Is_Array_Type (Desig_Typ)
12438                     and then not Is_Constrained (Desig_Typ)
12439                   then
12440                      Init_Size (Acc_Type, 2 * System_Address_Size);
12441                   else
12442                      Init_Size (Acc_Type, System_Address_Size);
12443                   end if;
12444
12445                   Init_Alignment (Acc_Type);
12446                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
12447
12448                   Set_Etype (New_Id, Acc_Type);
12449                   Set_Scope (New_Id, New_Subp);
12450
12451                   --  Create a reference to it
12452                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
12453
12454                else
12455                   Set_Etype (New_Id, Etype (Id));
12456                end if;
12457             end;
12458
12459          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
12460            or else
12461              (Ekind (Etype (Id)) = E_Record_Type_With_Private
12462                and then Present (Full_View (Etype (Id)))
12463                and then
12464                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
12465          then
12466             --  Constraint checks on formals are generated during expansion,
12467             --  based on the signature of the original subprogram. The bounds
12468             --  of the derived type are not relevant, and thus we can use
12469             --  the base type for the formals. However, the return type may be
12470             --  used in a context that requires that the proper static bounds
12471             --  be used (a case statement, for example)  and for those cases
12472             --  we must use the derived type (first subtype), not its base.
12473
12474             --  If the derived_type_definition has no constraints, we know that
12475             --  the derived type has the same constraints as the first subtype
12476             --  of the parent, and we can also use it rather than its base,
12477             --  which can lead to more efficient code.
12478
12479             if Etype (Id) = Parent_Type then
12480                if Is_Scalar_Type (Parent_Type)
12481                  and then
12482                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
12483                then
12484                   Set_Etype (New_Id, Derived_Type);
12485
12486                elsif Nkind (Par) = N_Full_Type_Declaration
12487                  and then
12488                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
12489                  and then
12490                    Is_Entity_Name
12491                      (Subtype_Indication (Type_Definition (Par)))
12492                then
12493                   Set_Etype (New_Id, Derived_Type);
12494
12495                else
12496                   Set_Etype (New_Id, Base_Type (Derived_Type));
12497                end if;
12498
12499             else
12500                Set_Etype (New_Id, Base_Type (Derived_Type));
12501             end if;
12502
12503          else
12504             Set_Etype (New_Id, Etype (Id));
12505          end if;
12506       end Replace_Type;
12507
12508       ----------------------
12509       -- Set_Derived_Name --
12510       ----------------------
12511
12512       procedure Set_Derived_Name is
12513          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
12514       begin
12515          if Nm = TSS_Null then
12516             Set_Chars (New_Subp, Chars (Parent_Subp));
12517          else
12518             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
12519          end if;
12520       end Set_Derived_Name;
12521
12522    --  Start of processing for Derive_Subprogram
12523
12524    begin
12525       New_Subp :=
12526          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
12527       Set_Ekind (New_Subp, Ekind (Parent_Subp));
12528
12529       --  Check whether the inherited subprogram is a private operation that
12530       --  should be inherited but not yet made visible. Such subprograms can
12531       --  become visible at a later point (e.g., the private part of a public
12532       --  child unit) via Declare_Inherited_Private_Subprograms. If the
12533       --  following predicate is true, then this is not such a private
12534       --  operation and the subprogram simply inherits the name of the parent
12535       --  subprogram. Note the special check for the names of controlled
12536       --  operations, which are currently exempted from being inherited with
12537       --  a hidden name because they must be findable for generation of
12538       --  implicit run-time calls.
12539
12540       if not Is_Hidden (Parent_Subp)
12541         or else Is_Internal (Parent_Subp)
12542         or else Is_Private_Overriding
12543         or else Is_Internal_Name (Chars (Parent_Subp))
12544         or else Chars (Parent_Subp) = Name_Initialize
12545         or else Chars (Parent_Subp) = Name_Adjust
12546         or else Chars (Parent_Subp) = Name_Finalize
12547       then
12548          Set_Derived_Name;
12549
12550       --  An inherited dispatching equality will be overridden by an internally
12551       --  generated one, or by an explicit one, so preserve its name and thus
12552       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
12553       --  private operation it may become invisible if the full view has
12554       --  progenitors, and the dispatch table will be malformed.
12555       --  We check that the type is limited to handle the anomalous declaration
12556       --  of Limited_Controlled, which is derived from a non-limited type, and
12557       --  which is handled specially elsewhere as well.
12558
12559       elsif Chars (Parent_Subp) = Name_Op_Eq
12560         and then Is_Dispatching_Operation (Parent_Subp)
12561         and then Etype (Parent_Subp) = Standard_Boolean
12562         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
12563         and then
12564           Etype (First_Formal (Parent_Subp)) =
12565             Etype (Next_Formal (First_Formal (Parent_Subp)))
12566       then
12567          Set_Derived_Name;
12568
12569       --  If parent is hidden, this can be a regular derivation if the
12570       --  parent is immediately visible in a non-instantiating context,
12571       --  or if we are in the private part of an instance. This test
12572       --  should still be refined ???
12573
12574       --  The test for In_Instance_Not_Visible avoids inheriting the derived
12575       --  operation as a non-visible operation in cases where the parent
12576       --  subprogram might not be visible now, but was visible within the
12577       --  original generic, so it would be wrong to make the inherited
12578       --  subprogram non-visible now. (Not clear if this test is fully
12579       --  correct; are there any cases where we should declare the inherited
12580       --  operation as not visible to avoid it being overridden, e.g., when
12581       --  the parent type is a generic actual with private primitives ???)
12582
12583       --  (they should be treated the same as other private inherited
12584       --  subprograms, but it's not clear how to do this cleanly). ???
12585
12586       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
12587               and then Is_Immediately_Visible (Parent_Subp)
12588               and then not In_Instance)
12589         or else In_Instance_Not_Visible
12590       then
12591          Set_Derived_Name;
12592
12593       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
12594       --  overrides an interface primitive because interface primitives
12595       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
12596
12597       elsif Ada_Version >= Ada_2005
12598          and then Is_Dispatching_Operation (Parent_Subp)
12599          and then Covers_Some_Interface (Parent_Subp)
12600       then
12601          Set_Derived_Name;
12602
12603       --  Otherwise, the type is inheriting a private operation, so enter
12604       --  it with a special name so it can't be overridden.
12605
12606       else
12607          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
12608       end if;
12609
12610       Set_Parent (New_Subp, Parent (Derived_Type));
12611
12612       if Present (Actual_Subp) then
12613          Replace_Type (Actual_Subp, New_Subp);
12614       else
12615          Replace_Type (Parent_Subp, New_Subp);
12616       end if;
12617
12618       Conditional_Delay (New_Subp, Parent_Subp);
12619
12620       --  If we are creating a renaming for a primitive operation of an
12621       --  actual of a generic derived type, we must examine the signature
12622       --  of the actual primitive, not that of the generic formal, which for
12623       --  example may be an interface. However the name and initial value
12624       --  of the inherited operation are those of the formal primitive.
12625
12626       Formal := First_Formal (Parent_Subp);
12627
12628       if Present (Actual_Subp) then
12629          Formal_Of_Actual := First_Formal (Actual_Subp);
12630       else
12631          Formal_Of_Actual := Empty;
12632       end if;
12633
12634       while Present (Formal) loop
12635          New_Formal := New_Copy (Formal);
12636
12637          --  Normally we do not go copying parents, but in the case of
12638          --  formals, we need to link up to the declaration (which is the
12639          --  parameter specification), and it is fine to link up to the
12640          --  original formal's parameter specification in this case.
12641
12642          Set_Parent (New_Formal, Parent (Formal));
12643          Append_Entity (New_Formal, New_Subp);
12644
12645          if Present (Formal_Of_Actual) then
12646             Replace_Type (Formal_Of_Actual, New_Formal);
12647             Next_Formal (Formal_Of_Actual);
12648          else
12649             Replace_Type (Formal, New_Formal);
12650          end if;
12651
12652          Next_Formal (Formal);
12653       end loop;
12654
12655       --  If this derivation corresponds to a tagged generic actual, then
12656       --  primitive operations rename those of the actual. Otherwise the
12657       --  primitive operations rename those of the parent type, If the parent
12658       --  renames an intrinsic operator, so does the new subprogram. We except
12659       --  concatenation, which is always properly typed, and does not get
12660       --  expanded as other intrinsic operations.
12661
12662       if No (Actual_Subp) then
12663          if Is_Intrinsic_Subprogram (Parent_Subp) then
12664             Set_Is_Intrinsic_Subprogram (New_Subp);
12665
12666             if Present (Alias (Parent_Subp))
12667               and then Chars (Parent_Subp) /= Name_Op_Concat
12668             then
12669                Set_Alias (New_Subp, Alias (Parent_Subp));
12670             else
12671                Set_Alias (New_Subp, Parent_Subp);
12672             end if;
12673
12674          else
12675             Set_Alias (New_Subp, Parent_Subp);
12676          end if;
12677
12678       else
12679          Set_Alias (New_Subp, Actual_Subp);
12680       end if;
12681
12682       --  Derived subprograms of a tagged type must inherit the convention
12683       --  of the parent subprogram (a requirement of AI-117). Derived
12684       --  subprograms of untagged types simply get convention Ada by default.
12685
12686       if Is_Tagged_Type (Derived_Type) then
12687          Set_Convention (New_Subp, Convention (Parent_Subp));
12688       end if;
12689
12690       --  Predefined controlled operations retain their name even if the parent
12691       --  is hidden (see above), but they are not primitive operations if the
12692       --  ancestor is not visible, for example if the parent is a private
12693       --  extension completed with a controlled extension. Note that a full
12694       --  type that is controlled can break privacy: the flag Is_Controlled is
12695       --  set on both views of the type.
12696
12697       if Is_Controlled (Parent_Type)
12698         and then
12699           (Chars (Parent_Subp) = Name_Initialize
12700             or else Chars (Parent_Subp) = Name_Adjust
12701             or else Chars (Parent_Subp) = Name_Finalize)
12702         and then Is_Hidden (Parent_Subp)
12703         and then not Is_Visibly_Controlled (Parent_Type)
12704       then
12705          Set_Is_Hidden (New_Subp);
12706       end if;
12707
12708       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
12709       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
12710
12711       if Ekind (Parent_Subp) = E_Procedure then
12712          Set_Is_Valued_Procedure
12713            (New_Subp, Is_Valued_Procedure (Parent_Subp));
12714       else
12715          Set_Has_Controlling_Result
12716            (New_Subp, Has_Controlling_Result (Parent_Subp));
12717       end if;
12718
12719       --  No_Return must be inherited properly. If this is overridden in the
12720       --  case of a dispatching operation, then a check is made in Sem_Disp
12721       --  that the overriding operation is also No_Return (no such check is
12722       --  required for the case of non-dispatching operation.
12723
12724       Set_No_Return (New_Subp, No_Return (Parent_Subp));
12725
12726       --  A derived function with a controlling result is abstract. If the
12727       --  Derived_Type is a nonabstract formal generic derived type, then
12728       --  inherited operations are not abstract: the required check is done at
12729       --  instantiation time. If the derivation is for a generic actual, the
12730       --  function is not abstract unless the actual is.
12731
12732       if Is_Generic_Type (Derived_Type)
12733         and then not Is_Abstract_Type (Derived_Type)
12734       then
12735          null;
12736
12737       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
12738       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
12739
12740       elsif Ada_Version >= Ada_2005
12741         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12742                    or else (Is_Tagged_Type (Derived_Type)
12743                             and then Etype (New_Subp) = Derived_Type
12744                             and then not Is_Null_Extension (Derived_Type))
12745                    or else (Is_Tagged_Type (Derived_Type)
12746                             and then Ekind (Etype (New_Subp)) =
12747                                                        E_Anonymous_Access_Type
12748                             and then Designated_Type (Etype (New_Subp)) =
12749                                                        Derived_Type
12750                             and then not Is_Null_Extension (Derived_Type)))
12751         and then No (Actual_Subp)
12752       then
12753          if not Is_Tagged_Type (Derived_Type)
12754            or else Is_Abstract_Type (Derived_Type)
12755            or else Is_Abstract_Subprogram (Alias (New_Subp))
12756          then
12757             Set_Is_Abstract_Subprogram (New_Subp);
12758          else
12759             Set_Requires_Overriding (New_Subp);
12760          end if;
12761
12762       elsif Ada_Version < Ada_2005
12763         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12764                    or else (Is_Tagged_Type (Derived_Type)
12765                              and then Etype (New_Subp) = Derived_Type
12766                              and then No (Actual_Subp)))
12767       then
12768          Set_Is_Abstract_Subprogram (New_Subp);
12769
12770       --  AI05-0097 : an inherited operation that dispatches on result is
12771       --  abstract if the derived type is abstract, even if the parent type
12772       --  is concrete and the derived type is a null extension.
12773
12774       elsif Has_Controlling_Result (Alias (New_Subp))
12775         and then Is_Abstract_Type (Etype (New_Subp))
12776       then
12777          Set_Is_Abstract_Subprogram (New_Subp);
12778
12779       --  Finally, if the parent type is abstract we must verify that all
12780       --  inherited operations are either non-abstract or overridden, or that
12781       --  the derived type itself is abstract (this check is performed at the
12782       --  end of a package declaration, in Check_Abstract_Overriding). A
12783       --  private overriding in the parent type will not be visible in the
12784       --  derivation if we are not in an inner package or in a child unit of
12785       --  the parent type, in which case the abstractness of the inherited
12786       --  operation is carried to the new subprogram.
12787
12788       elsif Is_Abstract_Type (Parent_Type)
12789         and then not In_Open_Scopes (Scope (Parent_Type))
12790         and then Is_Private_Overriding
12791         and then Is_Abstract_Subprogram (Visible_Subp)
12792       then
12793          if No (Actual_Subp) then
12794             Set_Alias (New_Subp, Visible_Subp);
12795             Set_Is_Abstract_Subprogram (New_Subp, True);
12796
12797          else
12798             --  If this is a derivation for an instance of a formal derived
12799             --  type, abstractness comes from the primitive operation of the
12800             --  actual, not from the operation inherited from the ancestor.
12801
12802             Set_Is_Abstract_Subprogram
12803               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
12804          end if;
12805       end if;
12806
12807       New_Overloaded_Entity (New_Subp, Derived_Type);
12808
12809       --  Check for case of a derived subprogram for the instantiation of a
12810       --  formal derived tagged type, if so mark the subprogram as dispatching
12811       --  and inherit the dispatching attributes of the parent subprogram. The
12812       --  derived subprogram is effectively renaming of the actual subprogram,
12813       --  so it needs to have the same attributes as the actual.
12814
12815       if Present (Actual_Subp)
12816         and then Is_Dispatching_Operation (Parent_Subp)
12817       then
12818          Set_Is_Dispatching_Operation (New_Subp);
12819
12820          if Present (DTC_Entity (Parent_Subp)) then
12821             Set_DTC_Entity (New_Subp, DTC_Entity (Parent_Subp));
12822             Set_DT_Position (New_Subp, DT_Position (Parent_Subp));
12823          end if;
12824       end if;
12825
12826       --  Indicate that a derived subprogram does not require a body and that
12827       --  it does not require processing of default expressions.
12828
12829       Set_Has_Completion (New_Subp);
12830       Set_Default_Expressions_Processed (New_Subp);
12831
12832       if Ekind (New_Subp) = E_Function then
12833          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
12834       end if;
12835    end Derive_Subprogram;
12836
12837    ------------------------
12838    -- Derive_Subprograms --
12839    ------------------------
12840
12841    procedure Derive_Subprograms
12842      (Parent_Type    : Entity_Id;
12843       Derived_Type   : Entity_Id;
12844       Generic_Actual : Entity_Id := Empty)
12845    is
12846       Op_List : constant Elist_Id :=
12847                   Collect_Primitive_Operations (Parent_Type);
12848
12849       function Check_Derived_Type return Boolean;
12850       --  Check that all primitive inherited from Parent_Type are found in
12851       --  the list of primitives of Derived_Type exactly in the same order.
12852
12853       function Check_Derived_Type return Boolean is
12854          E        : Entity_Id;
12855          Elmt     : Elmt_Id;
12856          List     : Elist_Id;
12857          New_Subp : Entity_Id;
12858          Op_Elmt  : Elmt_Id;
12859          Subp     : Entity_Id;
12860
12861       begin
12862          --  Traverse list of entities in the current scope searching for
12863          --  an incomplete type whose full-view is derived type
12864
12865          E := First_Entity (Scope (Derived_Type));
12866          while Present (E)
12867            and then E /= Derived_Type
12868          loop
12869             if Ekind (E) = E_Incomplete_Type
12870               and then Present (Full_View (E))
12871               and then Full_View (E) = Derived_Type
12872             then
12873                --  Disable this test if Derived_Type completes an incomplete
12874                --  type because in such case more primitives can be added
12875                --  later to the list of primitives of Derived_Type by routine
12876                --  Process_Incomplete_Dependents
12877
12878                return True;
12879             end if;
12880
12881             E := Next_Entity (E);
12882          end loop;
12883
12884          List := Collect_Primitive_Operations (Derived_Type);
12885          Elmt := First_Elmt (List);
12886
12887          Op_Elmt := First_Elmt (Op_List);
12888          while Present (Op_Elmt) loop
12889             Subp     := Node (Op_Elmt);
12890             New_Subp := Node (Elmt);
12891
12892             --  At this early stage Derived_Type has no entities with attribute
12893             --  Interface_Alias. In addition, such primitives are always
12894             --  located at the end of the list of primitives of Parent_Type.
12895             --  Therefore, if found we can safely stop processing pending
12896             --  entities.
12897
12898             exit when Present (Interface_Alias (Subp));
12899
12900             --  Handle hidden entities
12901
12902             if not Is_Predefined_Dispatching_Operation (Subp)
12903               and then Is_Hidden (Subp)
12904             then
12905                if Present (New_Subp)
12906                  and then Primitive_Names_Match (Subp, New_Subp)
12907                then
12908                   Next_Elmt (Elmt);
12909                end if;
12910
12911             else
12912                if not Present (New_Subp)
12913                  or else Ekind (Subp) /= Ekind (New_Subp)
12914                  or else not Primitive_Names_Match (Subp, New_Subp)
12915                then
12916                   return False;
12917                end if;
12918
12919                Next_Elmt (Elmt);
12920             end if;
12921
12922             Next_Elmt (Op_Elmt);
12923          end loop;
12924
12925          return True;
12926       end Check_Derived_Type;
12927
12928       --  Local variables
12929
12930       Alias_Subp   : Entity_Id;
12931       Act_List     : Elist_Id;
12932       Act_Elmt     : Elmt_Id   := No_Elmt;
12933       Act_Subp     : Entity_Id := Empty;
12934       Elmt         : Elmt_Id;
12935       Need_Search  : Boolean   := False;
12936       New_Subp     : Entity_Id := Empty;
12937       Parent_Base  : Entity_Id;
12938       Subp         : Entity_Id;
12939
12940    --  Start of processing for Derive_Subprograms
12941
12942    begin
12943       if Ekind (Parent_Type) = E_Record_Type_With_Private
12944         and then Has_Discriminants (Parent_Type)
12945         and then Present (Full_View (Parent_Type))
12946       then
12947          Parent_Base := Full_View (Parent_Type);
12948       else
12949          Parent_Base := Parent_Type;
12950       end if;
12951
12952       if Present (Generic_Actual) then
12953          Act_List := Collect_Primitive_Operations (Generic_Actual);
12954          Act_Elmt := First_Elmt (Act_List);
12955       end if;
12956
12957       --  Derive primitives inherited from the parent. Note that if the generic
12958       --  actual is present, this is not really a type derivation, it is a
12959       --  completion within an instance.
12960
12961       --  Case 1: Derived_Type does not implement interfaces
12962
12963       if not Is_Tagged_Type (Derived_Type)
12964         or else (not Has_Interfaces (Derived_Type)
12965                   and then not (Present (Generic_Actual)
12966                                   and then
12967                                 Has_Interfaces (Generic_Actual)))
12968       then
12969          Elmt := First_Elmt (Op_List);
12970          while Present (Elmt) loop
12971             Subp := Node (Elmt);
12972
12973             --  Literals are derived earlier in the process of building the
12974             --  derived type, and are skipped here.
12975
12976             if Ekind (Subp) = E_Enumeration_Literal then
12977                null;
12978
12979             --  The actual is a direct descendant and the common primitive
12980             --  operations appear in the same order.
12981
12982             --  If the generic parent type is present, the derived type is an
12983             --  instance of a formal derived type, and within the instance its
12984             --  operations are those of the actual. We derive from the formal
12985             --  type but make the inherited operations aliases of the
12986             --  corresponding operations of the actual.
12987
12988             else
12989                pragma Assert (No (Node (Act_Elmt))
12990                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
12991                             and then
12992                           Type_Conformant (Subp, Node (Act_Elmt),
12993                                            Skip_Controlling_Formals => True)));
12994
12995                Derive_Subprogram
12996                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
12997
12998                if Present (Act_Elmt) then
12999                   Next_Elmt (Act_Elmt);
13000                end if;
13001             end if;
13002
13003             Next_Elmt (Elmt);
13004          end loop;
13005
13006       --  Case 2: Derived_Type implements interfaces
13007
13008       else
13009          --  If the parent type has no predefined primitives we remove
13010          --  predefined primitives from the list of primitives of generic
13011          --  actual to simplify the complexity of this algorithm.
13012
13013          if Present (Generic_Actual) then
13014             declare
13015                Has_Predefined_Primitives : Boolean := False;
13016
13017             begin
13018                --  Check if the parent type has predefined primitives
13019
13020                Elmt := First_Elmt (Op_List);
13021                while Present (Elmt) loop
13022                   Subp := Node (Elmt);
13023
13024                   if Is_Predefined_Dispatching_Operation (Subp)
13025                     and then not Comes_From_Source (Ultimate_Alias (Subp))
13026                   then
13027                      Has_Predefined_Primitives := True;
13028                      exit;
13029                   end if;
13030
13031                   Next_Elmt (Elmt);
13032                end loop;
13033
13034                --  Remove predefined primitives of Generic_Actual. We must use
13035                --  an auxiliary list because in case of tagged types the value
13036                --  returned by Collect_Primitive_Operations is the value stored
13037                --  in its Primitive_Operations attribute (and we don't want to
13038                --  modify its current contents).
13039
13040                if not Has_Predefined_Primitives then
13041                   declare
13042                      Aux_List : constant Elist_Id := New_Elmt_List;
13043
13044                   begin
13045                      Elmt := First_Elmt (Act_List);
13046                      while Present (Elmt) loop
13047                         Subp := Node (Elmt);
13048
13049                         if not Is_Predefined_Dispatching_Operation (Subp)
13050                           or else Comes_From_Source (Subp)
13051                         then
13052                            Append_Elmt (Subp, Aux_List);
13053                         end if;
13054
13055                         Next_Elmt (Elmt);
13056                      end loop;
13057
13058                      Act_List := Aux_List;
13059                   end;
13060                end if;
13061
13062                Act_Elmt := First_Elmt (Act_List);
13063                Act_Subp := Node (Act_Elmt);
13064             end;
13065          end if;
13066
13067          --  Stage 1: If the generic actual is not present we derive the
13068          --  primitives inherited from the parent type. If the generic parent
13069          --  type is present, the derived type is an instance of a formal
13070          --  derived type, and within the instance its operations are those of
13071          --  the actual. We derive from the formal type but make the inherited
13072          --  operations aliases of the corresponding operations of the actual.
13073
13074          Elmt := First_Elmt (Op_List);
13075          while Present (Elmt) loop
13076             Subp       := Node (Elmt);
13077             Alias_Subp := Ultimate_Alias (Subp);
13078
13079             --  Do not derive internal entities of the parent that link
13080             --  interface primitives and its covering primitive. These
13081             --  entities will be added to this type when frozen.
13082
13083             if Present (Interface_Alias (Subp)) then
13084                goto Continue;
13085             end if;
13086
13087             --  If the generic actual is present find the corresponding
13088             --  operation in the generic actual. If the parent type is a
13089             --  direct ancestor of the derived type then, even if it is an
13090             --  interface, the operations are inherited from the primary
13091             --  dispatch table and are in the proper order. If we detect here
13092             --  that primitives are not in the same order we traverse the list
13093             --  of primitive operations of the actual to find the one that
13094             --  implements the interface primitive.
13095
13096             if Need_Search
13097               or else
13098                 (Present (Generic_Actual)
13099                   and then Present (Act_Subp)
13100                   and then not
13101                     (Primitive_Names_Match (Subp, Act_Subp)
13102                        and then
13103                      Type_Conformant (Subp, Act_Subp,
13104                                       Skip_Controlling_Formals => True)))
13105             then
13106                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual));
13107
13108                --  Remember that we need searching for all pending primitives
13109
13110                Need_Search := True;
13111
13112                --  Handle entities associated with interface primitives
13113
13114                if Present (Alias_Subp)
13115                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13116                  and then not Is_Predefined_Dispatching_Operation (Subp)
13117                then
13118                   --  Search for the primitive in the homonym chain
13119
13120                   Act_Subp :=
13121                     Find_Primitive_Covering_Interface
13122                       (Tagged_Type => Generic_Actual,
13123                        Iface_Prim  => Alias_Subp);
13124
13125                   --  Previous search may not locate primitives covering
13126                   --  interfaces defined in generics units or instantiations.
13127                   --  (it fails if the covering primitive has formals whose
13128                   --  type is also defined in generics or instantiations).
13129                   --  In such case we search in the list of primitives of the
13130                   --  generic actual for the internal entity that links the
13131                   --  interface primitive and the covering primitive.
13132
13133                   if No (Act_Subp)
13134                     and then Is_Generic_Type (Parent_Type)
13135                   then
13136                      --  This code has been designed to handle only generic
13137                      --  formals that implement interfaces that are defined
13138                      --  in a generic unit or instantiation. If this code is
13139                      --  needed for other cases we must review it because
13140                      --  (given that it relies on Original_Location to locate
13141                      --  the primitive of Generic_Actual that covers the
13142                      --  interface) it could leave linked through attribute
13143                      --  Alias entities of unrelated instantiations).
13144
13145                      pragma Assert
13146                        (Is_Generic_Unit
13147                           (Scope (Find_Dispatching_Type (Alias_Subp)))
13148                        or else
13149                         Instantiation_Depth
13150                           (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
13151
13152                      declare
13153                         Iface_Prim_Loc : constant Source_Ptr :=
13154                                          Original_Location (Sloc (Alias_Subp));
13155                         Elmt      : Elmt_Id;
13156                         Prim      : Entity_Id;
13157                      begin
13158                         Elmt :=
13159                           First_Elmt (Primitive_Operations (Generic_Actual));
13160
13161                         Search : while Present (Elmt) loop
13162                            Prim := Node (Elmt);
13163
13164                            if Present (Interface_Alias (Prim))
13165                              and then Original_Location
13166                                         (Sloc (Interface_Alias (Prim)))
13167                                        = Iface_Prim_Loc
13168                            then
13169                               Act_Subp := Alias (Prim);
13170                               exit Search;
13171                            end if;
13172
13173                            Next_Elmt (Elmt);
13174                         end loop Search;
13175                      end;
13176                   end if;
13177
13178                   pragma Assert (Present (Act_Subp)
13179                     or else Is_Abstract_Type (Generic_Actual)
13180                     or else Serious_Errors_Detected > 0);
13181
13182                --  Handle predefined primitives plus the rest of user-defined
13183                --  primitives
13184
13185                else
13186                   Act_Elmt := First_Elmt (Act_List);
13187                   while Present (Act_Elmt) loop
13188                      Act_Subp := Node (Act_Elmt);
13189
13190                      exit when Primitive_Names_Match (Subp, Act_Subp)
13191                        and then Type_Conformant
13192                                   (Subp, Act_Subp,
13193                                    Skip_Controlling_Formals => True)
13194                        and then No (Interface_Alias (Act_Subp));
13195
13196                      Next_Elmt (Act_Elmt);
13197                   end loop;
13198
13199                   if No (Act_Elmt) then
13200                      Act_Subp := Empty;
13201                   end if;
13202                end if;
13203             end if;
13204
13205             --   Case 1: If the parent is a limited interface then it has the
13206             --   predefined primitives of synchronized interfaces. However, the
13207             --   actual type may be a non-limited type and hence it does not
13208             --   have such primitives.
13209
13210             if Present (Generic_Actual)
13211               and then not Present (Act_Subp)
13212               and then Is_Limited_Interface (Parent_Base)
13213               and then Is_Predefined_Interface_Primitive (Subp)
13214             then
13215                null;
13216
13217             --  Case 2: Inherit entities associated with interfaces that were
13218             --  not covered by the parent type. We exclude here null interface
13219             --  primitives because they do not need special management.
13220
13221             --  We also exclude interface operations that are renamings. If the
13222             --  subprogram is an explicit renaming of an interface primitive,
13223             --  it is a regular primitive operation, and the presence of its
13224             --  alias is not relevant: it has to be derived like any other
13225             --  primitive.
13226
13227             elsif Present (Alias (Subp))
13228               and then Nkind (Unit_Declaration_Node (Subp)) /=
13229                                             N_Subprogram_Renaming_Declaration
13230               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13231               and then not
13232                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
13233                   and then Null_Present (Parent (Alias_Subp)))
13234             then
13235                Derive_Subprogram
13236                  (New_Subp     => New_Subp,
13237                   Parent_Subp  => Alias_Subp,
13238                   Derived_Type => Derived_Type,
13239                   Parent_Type  => Find_Dispatching_Type (Alias_Subp),
13240                   Actual_Subp  => Act_Subp);
13241
13242                if No (Generic_Actual) then
13243                   Set_Alias (New_Subp, Subp);
13244                end if;
13245
13246             --  Case 3: Common derivation
13247
13248             else
13249                Derive_Subprogram
13250                  (New_Subp     => New_Subp,
13251                   Parent_Subp  => Subp,
13252                   Derived_Type => Derived_Type,
13253                   Parent_Type  => Parent_Base,
13254                   Actual_Subp  => Act_Subp);
13255             end if;
13256
13257             --  No need to update Act_Elm if we must search for the
13258             --  corresponding operation in the generic actual
13259
13260             if not Need_Search
13261               and then Present (Act_Elmt)
13262             then
13263                Next_Elmt (Act_Elmt);
13264                Act_Subp := Node (Act_Elmt);
13265             end if;
13266
13267             <<Continue>>
13268             Next_Elmt (Elmt);
13269          end loop;
13270
13271          --  Inherit additional operations from progenitors. If the derived
13272          --  type is a generic actual, there are not new primitive operations
13273          --  for the type because it has those of the actual, and therefore
13274          --  nothing needs to be done. The renamings generated above are not
13275          --  primitive operations, and their purpose is simply to make the
13276          --  proper operations visible within an instantiation.
13277
13278          if No (Generic_Actual) then
13279             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
13280          end if;
13281       end if;
13282
13283       --  Final check: Direct descendants must have their primitives in the
13284       --  same order. We exclude from this test untagged types and instances
13285       --  of formal derived types. We skip this test if we have already
13286       --  reported serious errors in the sources.
13287
13288       pragma Assert (not Is_Tagged_Type (Derived_Type)
13289         or else Present (Generic_Actual)
13290         or else Serious_Errors_Detected > 0
13291         or else Check_Derived_Type);
13292    end Derive_Subprograms;
13293
13294    --------------------------------
13295    -- Derived_Standard_Character --
13296    --------------------------------
13297
13298    procedure Derived_Standard_Character
13299      (N            : Node_Id;
13300       Parent_Type  : Entity_Id;
13301       Derived_Type : Entity_Id)
13302    is
13303       Loc           : constant Source_Ptr := Sloc (N);
13304       Def           : constant Node_Id    := Type_Definition (N);
13305       Indic         : constant Node_Id    := Subtype_Indication (Def);
13306       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
13307       Implicit_Base : constant Entity_Id  :=
13308                         Create_Itype
13309                           (E_Enumeration_Type, N, Derived_Type, 'B');
13310
13311       Lo : Node_Id;
13312       Hi : Node_Id;
13313
13314    begin
13315       Discard_Node (Process_Subtype (Indic, N));
13316
13317       Set_Etype     (Implicit_Base, Parent_Base);
13318       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
13319       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
13320
13321       Set_Is_Character_Type  (Implicit_Base, True);
13322       Set_Has_Delayed_Freeze (Implicit_Base);
13323
13324       --  The bounds of the implicit base are the bounds of the parent base.
13325       --  Note that their type is the parent base.
13326
13327       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
13328       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
13329
13330       Set_Scalar_Range (Implicit_Base,
13331         Make_Range (Loc,
13332           Low_Bound  => Lo,
13333           High_Bound => Hi));
13334
13335       Conditional_Delay (Derived_Type, Parent_Type);
13336
13337       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
13338       Set_Etype (Derived_Type, Implicit_Base);
13339       Set_Size_Info         (Derived_Type, Parent_Type);
13340
13341       if Unknown_RM_Size (Derived_Type) then
13342          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
13343       end if;
13344
13345       Set_Is_Character_Type (Derived_Type, True);
13346
13347       if Nkind (Indic) /= N_Subtype_Indication then
13348
13349          --  If no explicit constraint, the bounds are those
13350          --  of the parent type.
13351
13352          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
13353          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
13354          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
13355       end if;
13356
13357       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
13358
13359       --  Because the implicit base is used in the conversion of the bounds, we
13360       --  have to freeze it now. This is similar to what is done for numeric
13361       --  types, and it equally suspicious, but otherwise a non-static bound
13362       --  will have a reference to an unfrozen type, which is rejected by Gigi
13363       --  (???). This requires specific care for definition of stream
13364       --  attributes. For details, see comments at the end of
13365       --  Build_Derived_Numeric_Type.
13366
13367       Freeze_Before (N, Implicit_Base);
13368    end Derived_Standard_Character;
13369
13370    ------------------------------
13371    -- Derived_Type_Declaration --
13372    ------------------------------
13373
13374    procedure Derived_Type_Declaration
13375      (T             : Entity_Id;
13376       N             : Node_Id;
13377       Is_Completion : Boolean)
13378    is
13379       Parent_Type  : Entity_Id;
13380
13381       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
13382       --  Check whether the parent type is a generic formal, or derives
13383       --  directly or indirectly from one.
13384
13385       ------------------------
13386       -- Comes_From_Generic --
13387       ------------------------
13388
13389       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
13390       begin
13391          if Is_Generic_Type (Typ) then
13392             return True;
13393
13394          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
13395             return True;
13396
13397          elsif Is_Private_Type (Typ)
13398            and then Present (Full_View (Typ))
13399            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
13400          then
13401             return True;
13402
13403          elsif Is_Generic_Actual_Type (Typ) then
13404             return True;
13405
13406          else
13407             return False;
13408          end if;
13409       end Comes_From_Generic;
13410
13411       --  Local variables
13412
13413       Def          : constant Node_Id := Type_Definition (N);
13414       Iface_Def    : Node_Id;
13415       Indic        : constant Node_Id := Subtype_Indication (Def);
13416       Extension    : constant Node_Id := Record_Extension_Part (Def);
13417       Parent_Node  : Node_Id;
13418       Parent_Scope : Entity_Id;
13419       Taggd        : Boolean;
13420
13421    --  Start of processing for Derived_Type_Declaration
13422
13423    begin
13424       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
13425
13426       --  Ada 2005 (AI-251): In case of interface derivation check that the
13427       --  parent is also an interface.
13428
13429       if Interface_Present (Def) then
13430          if not Is_Interface (Parent_Type) then
13431             Diagnose_Interface (Indic, Parent_Type);
13432
13433          else
13434             Parent_Node := Parent (Base_Type (Parent_Type));
13435             Iface_Def   := Type_Definition (Parent_Node);
13436
13437             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
13438             --  other limited interfaces.
13439
13440             if Limited_Present (Def) then
13441                if Limited_Present (Iface_Def) then
13442                   null;
13443
13444                elsif Protected_Present (Iface_Def) then
13445                   Error_Msg_NE
13446                     ("descendant of& must be declared"
13447                        & " as a protected interface",
13448                          N, Parent_Type);
13449
13450                elsif Synchronized_Present (Iface_Def) then
13451                   Error_Msg_NE
13452                     ("descendant of& must be declared"
13453                        & " as a synchronized interface",
13454                          N, Parent_Type);
13455
13456                elsif Task_Present (Iface_Def) then
13457                   Error_Msg_NE
13458                     ("descendant of& must be declared as a task interface",
13459                        N, Parent_Type);
13460
13461                else
13462                   Error_Msg_N
13463                     ("(Ada 2005) limited interface cannot "
13464                      & "inherit from non-limited interface", Indic);
13465                end if;
13466
13467             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
13468             --  from non-limited or limited interfaces.
13469
13470             elsif not Protected_Present (Def)
13471               and then not Synchronized_Present (Def)
13472               and then not Task_Present (Def)
13473             then
13474                if Limited_Present (Iface_Def) then
13475                   null;
13476
13477                elsif Protected_Present (Iface_Def) then
13478                   Error_Msg_NE
13479                     ("descendant of& must be declared"
13480                        & " as a protected interface",
13481                          N, Parent_Type);
13482
13483                elsif Synchronized_Present (Iface_Def) then
13484                   Error_Msg_NE
13485                     ("descendant of& must be declared"
13486                        & " as a synchronized interface",
13487                          N, Parent_Type);
13488
13489                elsif Task_Present (Iface_Def) then
13490                   Error_Msg_NE
13491                     ("descendant of& must be declared as a task interface",
13492                        N, Parent_Type);
13493                else
13494                   null;
13495                end if;
13496             end if;
13497          end if;
13498       end if;
13499
13500       if Is_Tagged_Type (Parent_Type)
13501         and then Is_Concurrent_Type (Parent_Type)
13502         and then not Is_Interface (Parent_Type)
13503       then
13504          Error_Msg_N
13505            ("parent type of a record extension cannot be "
13506             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
13507          Set_Etype (T, Any_Type);
13508          return;
13509       end if;
13510
13511       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
13512       --  interfaces
13513
13514       if Is_Tagged_Type (Parent_Type)
13515         and then Is_Non_Empty_List (Interface_List (Def))
13516       then
13517          declare
13518             Intf : Node_Id;
13519             T    : Entity_Id;
13520
13521          begin
13522             Intf := First (Interface_List (Def));
13523             while Present (Intf) loop
13524                T := Find_Type_Of_Subtype_Indic (Intf);
13525
13526                if not Is_Interface (T) then
13527                   Diagnose_Interface (Intf, T);
13528
13529                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
13530                --  a limited type from having a nonlimited progenitor.
13531
13532                elsif (Limited_Present (Def)
13533                        or else (not Is_Interface (Parent_Type)
13534                                  and then Is_Limited_Type (Parent_Type)))
13535                  and then not Is_Limited_Interface (T)
13536                then
13537                   Error_Msg_NE
13538                    ("progenitor interface& of limited type must be limited",
13539                      N, T);
13540                end if;
13541
13542                Next (Intf);
13543             end loop;
13544          end;
13545       end if;
13546
13547       if Parent_Type = Any_Type
13548         or else Etype (Parent_Type) = Any_Type
13549         or else (Is_Class_Wide_Type (Parent_Type)
13550                    and then Etype (Parent_Type) = T)
13551       then
13552          --  If Parent_Type is undefined or illegal, make new type into a
13553          --  subtype of Any_Type, and set a few attributes to prevent cascaded
13554          --  errors. If this is a self-definition, emit error now.
13555
13556          if T = Parent_Type
13557            or else T = Etype (Parent_Type)
13558          then
13559             Error_Msg_N ("type cannot be used in its own definition", Indic);
13560          end if;
13561
13562          Set_Ekind        (T, Ekind (Parent_Type));
13563          Set_Etype        (T, Any_Type);
13564          Set_Scalar_Range (T, Scalar_Range (Any_Type));
13565
13566          if Is_Tagged_Type (T)
13567            and then Is_Record_Type (T)
13568          then
13569             Set_Direct_Primitive_Operations (T, New_Elmt_List);
13570          end if;
13571
13572          return;
13573       end if;
13574
13575       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
13576       --  an interface is special because the list of interfaces in the full
13577       --  view can be given in any order. For example:
13578
13579       --     type A is interface;
13580       --     type B is interface and A;
13581       --     type D is new B with private;
13582       --   private
13583       --     type D is new A and B with null record; -- 1 --
13584
13585       --  In this case we perform the following transformation of -1-:
13586
13587       --     type D is new B and A with null record;
13588
13589       --  If the parent of the full-view covers the parent of the partial-view
13590       --  we have two possible cases:
13591
13592       --     1) They have the same parent
13593       --     2) The parent of the full-view implements some further interfaces
13594
13595       --  In both cases we do not need to perform the transformation. In the
13596       --  first case the source program is correct and the transformation is
13597       --  not needed; in the second case the source program does not fulfill
13598       --  the no-hidden interfaces rule (AI-396) and the error will be reported
13599       --  later.
13600
13601       --  This transformation not only simplifies the rest of the analysis of
13602       --  this type declaration but also simplifies the correct generation of
13603       --  the object layout to the expander.
13604
13605       if In_Private_Part (Current_Scope)
13606         and then Is_Interface (Parent_Type)
13607       then
13608          declare
13609             Iface               : Node_Id;
13610             Partial_View        : Entity_Id;
13611             Partial_View_Parent : Entity_Id;
13612             New_Iface           : Node_Id;
13613
13614          begin
13615             --  Look for the associated private type declaration
13616
13617             Partial_View := First_Entity (Current_Scope);
13618             loop
13619                exit when No (Partial_View)
13620                  or else (Has_Private_Declaration (Partial_View)
13621                            and then Full_View (Partial_View) = T);
13622
13623                Next_Entity (Partial_View);
13624             end loop;
13625
13626             --  If the partial view was not found then the source code has
13627             --  errors and the transformation is not needed.
13628
13629             if Present (Partial_View) then
13630                Partial_View_Parent := Etype (Partial_View);
13631
13632                --  If the parent of the full-view covers the parent of the
13633                --  partial-view we have nothing else to do.
13634
13635                if Interface_Present_In_Ancestor
13636                     (Parent_Type, Partial_View_Parent)
13637                then
13638                   null;
13639
13640                --  Traverse the list of interfaces of the full-view to look
13641                --  for the parent of the partial-view and perform the tree
13642                --  transformation.
13643
13644                else
13645                   Iface := First (Interface_List (Def));
13646                   while Present (Iface) loop
13647                      if Etype (Iface) = Etype (Partial_View) then
13648                         Rewrite (Subtype_Indication (Def),
13649                           New_Copy (Subtype_Indication
13650                                      (Parent (Partial_View))));
13651
13652                         New_Iface := Make_Identifier (Sloc (N),
13653                                        Chars (Parent_Type));
13654                         Append (New_Iface, Interface_List (Def));
13655
13656                         --  Analyze the transformed code
13657
13658                         Derived_Type_Declaration (T, N, Is_Completion);
13659                         return;
13660                      end if;
13661
13662                      Next (Iface);
13663                   end loop;
13664                end if;
13665             end if;
13666          end;
13667       end if;
13668
13669       --  Only composite types other than array types are allowed to have
13670       --  discriminants.
13671
13672       if Present (Discriminant_Specifications (N))
13673         and then (Is_Elementary_Type (Parent_Type)
13674                   or else Is_Array_Type (Parent_Type))
13675         and then not Error_Posted (N)
13676       then
13677          Error_Msg_N
13678            ("elementary or array type cannot have discriminants",
13679             Defining_Identifier (First (Discriminant_Specifications (N))));
13680          Set_Has_Discriminants (T, False);
13681       end if;
13682
13683       --  In Ada 83, a derived type defined in a package specification cannot
13684       --  be used for further derivation until the end of its visible part.
13685       --  Note that derivation in the private part of the package is allowed.
13686
13687       if Ada_Version = Ada_83
13688         and then Is_Derived_Type (Parent_Type)
13689         and then In_Visible_Part (Scope (Parent_Type))
13690       then
13691          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
13692             Error_Msg_N
13693               ("(Ada 83): premature use of type for derivation", Indic);
13694          end if;
13695       end if;
13696
13697       --  Check for early use of incomplete or private type
13698
13699       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
13700          Error_Msg_N ("premature derivation of incomplete type", Indic);
13701          return;
13702
13703       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
13704               and then not Comes_From_Generic (Parent_Type))
13705         or else Has_Private_Component (Parent_Type)
13706       then
13707          --  The ancestor type of a formal type can be incomplete, in which
13708          --  case only the operations of the partial view are available in
13709          --  the generic. Subsequent checks may be required when the full
13710          --  view is analyzed, to verify that derivation from a tagged type
13711          --  has an extension.
13712
13713          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
13714             null;
13715
13716          elsif No (Underlying_Type (Parent_Type))
13717            or else Has_Private_Component (Parent_Type)
13718          then
13719             Error_Msg_N
13720               ("premature derivation of derived or private type", Indic);
13721
13722             --  Flag the type itself as being in error, this prevents some
13723             --  nasty problems with subsequent uses of the malformed type.
13724
13725             Set_Error_Posted (T);
13726
13727          --  Check that within the immediate scope of an untagged partial
13728          --  view it's illegal to derive from the partial view if the
13729          --  full view is tagged. (7.3(7))
13730
13731          --  We verify that the Parent_Type is a partial view by checking
13732          --  that it is not a Full_Type_Declaration (i.e. a private type or
13733          --  private extension declaration), to distinguish a partial view
13734          --  from  a derivation from a private type which also appears as
13735          --  E_Private_Type.
13736
13737          elsif Present (Full_View (Parent_Type))
13738            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
13739            and then not Is_Tagged_Type (Parent_Type)
13740            and then Is_Tagged_Type (Full_View (Parent_Type))
13741          then
13742             Parent_Scope := Scope (T);
13743             while Present (Parent_Scope)
13744               and then Parent_Scope /= Standard_Standard
13745             loop
13746                if Parent_Scope = Scope (Parent_Type) then
13747                   Error_Msg_N
13748                     ("premature derivation from type with tagged full view",
13749                      Indic);
13750                end if;
13751
13752                Parent_Scope := Scope (Parent_Scope);
13753             end loop;
13754          end if;
13755       end if;
13756
13757       --  Check that form of derivation is appropriate
13758
13759       Taggd := Is_Tagged_Type (Parent_Type);
13760
13761       --  Perhaps the parent type should be changed to the class-wide type's
13762       --  specific type in this case to prevent cascading errors ???
13763
13764       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
13765          Error_Msg_N ("parent type must not be a class-wide type", Indic);
13766          return;
13767       end if;
13768
13769       if Present (Extension) and then not Taggd then
13770          Error_Msg_N
13771            ("type derived from untagged type cannot have extension", Indic);
13772
13773       elsif No (Extension) and then Taggd then
13774
13775          --  If this declaration is within a private part (or body) of a
13776          --  generic instantiation then the derivation is allowed (the parent
13777          --  type can only appear tagged in this case if it's a generic actual
13778          --  type, since it would otherwise have been rejected in the analysis
13779          --  of the generic template).
13780
13781          if not Is_Generic_Actual_Type (Parent_Type)
13782            or else In_Visible_Part (Scope (Parent_Type))
13783          then
13784             if Is_Class_Wide_Type (Parent_Type) then
13785                Error_Msg_N
13786                  ("parent type must not be a class-wide type", Indic);
13787
13788                --  Use specific type to prevent cascaded errors.
13789
13790                Parent_Type := Etype (Parent_Type);
13791
13792             else
13793                Error_Msg_N
13794                  ("type derived from tagged type must have extension", Indic);
13795             end if;
13796          end if;
13797       end if;
13798
13799       --  AI-443: Synchronized formal derived types require a private
13800       --  extension. There is no point in checking the ancestor type or
13801       --  the progenitors since the construct is wrong to begin with.
13802
13803       if Ada_Version >= Ada_2005
13804         and then Is_Generic_Type (T)
13805         and then Present (Original_Node (N))
13806       then
13807          declare
13808             Decl : constant Node_Id := Original_Node (N);
13809
13810          begin
13811             if Nkind (Decl) = N_Formal_Type_Declaration
13812               and then Nkind (Formal_Type_Definition (Decl)) =
13813                          N_Formal_Derived_Type_Definition
13814               and then Synchronized_Present (Formal_Type_Definition (Decl))
13815               and then No (Extension)
13816
13817                --  Avoid emitting a duplicate error message
13818
13819               and then not Error_Posted (Indic)
13820             then
13821                Error_Msg_N
13822                  ("synchronized derived type must have extension", N);
13823             end if;
13824          end;
13825       end if;
13826
13827       if Null_Exclusion_Present (Def)
13828         and then not Is_Access_Type (Parent_Type)
13829       then
13830          Error_Msg_N ("null exclusion can only apply to an access type", N);
13831       end if;
13832
13833       --  Avoid deriving parent primitives of underlying record views
13834
13835       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
13836         Derive_Subps => not Is_Underlying_Record_View (T));
13837
13838       --  AI-419: The parent type of an explicitly limited derived type must
13839       --  be a limited type or a limited interface.
13840
13841       if Limited_Present (Def) then
13842          Set_Is_Limited_Record (T);
13843
13844          if Is_Interface (T) then
13845             Set_Is_Limited_Interface (T);
13846          end if;
13847
13848          if not Is_Limited_Type (Parent_Type)
13849            and then
13850              (not Is_Interface (Parent_Type)
13851                or else not Is_Limited_Interface (Parent_Type))
13852          then
13853             --  AI05-0096: a derivation in the private part of an instance is
13854             --  legal if the generic formal is untagged limited, and the actual
13855             --  is non-limited.
13856
13857             if Is_Generic_Actual_Type (Parent_Type)
13858               and then In_Private_Part (Current_Scope)
13859               and then
13860                 not Is_Tagged_Type
13861                       (Generic_Parent_Type (Parent (Parent_Type)))
13862             then
13863                null;
13864
13865             else
13866                Error_Msg_NE
13867                  ("parent type& of limited type must be limited",
13868                   N, Parent_Type);
13869             end if;
13870          end if;
13871       end if;
13872    end Derived_Type_Declaration;
13873
13874    ------------------------
13875    -- Diagnose_Interface --
13876    ------------------------
13877
13878    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
13879    begin
13880       if not Is_Interface (E)
13881         and then  E /= Any_Type
13882       then
13883          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
13884       end if;
13885    end Diagnose_Interface;
13886
13887    ----------------------------------
13888    -- Enumeration_Type_Declaration --
13889    ----------------------------------
13890
13891    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
13892       Ev     : Uint;
13893       L      : Node_Id;
13894       R_Node : Node_Id;
13895       B_Node : Node_Id;
13896
13897    begin
13898       --  Create identifier node representing lower bound
13899
13900       B_Node := New_Node (N_Identifier, Sloc (Def));
13901       L := First (Literals (Def));
13902       Set_Chars (B_Node, Chars (L));
13903       Set_Entity (B_Node,  L);
13904       Set_Etype (B_Node, T);
13905       Set_Is_Static_Expression (B_Node, True);
13906
13907       R_Node := New_Node (N_Range, Sloc (Def));
13908       Set_Low_Bound  (R_Node, B_Node);
13909
13910       Set_Ekind (T, E_Enumeration_Type);
13911       Set_First_Literal (T, L);
13912       Set_Etype (T, T);
13913       Set_Is_Constrained (T);
13914
13915       Ev := Uint_0;
13916
13917       --  Loop through literals of enumeration type setting pos and rep values
13918       --  except that if the Ekind is already set, then it means the literal
13919       --  was already constructed (case of a derived type declaration and we
13920       --  should not disturb the Pos and Rep values.
13921
13922       while Present (L) loop
13923          if Ekind (L) /= E_Enumeration_Literal then
13924             Set_Ekind (L, E_Enumeration_Literal);
13925             Set_Enumeration_Pos (L, Ev);
13926             Set_Enumeration_Rep (L, Ev);
13927             Set_Is_Known_Valid  (L, True);
13928          end if;
13929
13930          Set_Etype (L, T);
13931          New_Overloaded_Entity (L);
13932          Generate_Definition (L);
13933          Set_Convention (L, Convention_Intrinsic);
13934
13935          --  Case of character literal
13936
13937          if Nkind (L) = N_Defining_Character_Literal then
13938             Set_Is_Character_Type (T, True);
13939
13940             --  Check violation of No_Wide_Characters
13941
13942             if Restriction_Check_Required (No_Wide_Characters) then
13943                Get_Name_String (Chars (L));
13944
13945                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
13946                   Check_Restriction (No_Wide_Characters, L);
13947                end if;
13948             end if;
13949          end if;
13950
13951          Ev := Ev + 1;
13952          Next (L);
13953       end loop;
13954
13955       --  Now create a node representing upper bound
13956
13957       B_Node := New_Node (N_Identifier, Sloc (Def));
13958       Set_Chars (B_Node, Chars (Last (Literals (Def))));
13959       Set_Entity (B_Node,  Last (Literals (Def)));
13960       Set_Etype (B_Node, T);
13961       Set_Is_Static_Expression (B_Node, True);
13962
13963       Set_High_Bound (R_Node, B_Node);
13964
13965       --  Initialize various fields of the type. Some of this information
13966       --  may be overwritten later through rep.clauses.
13967
13968       Set_Scalar_Range    (T, R_Node);
13969       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
13970       Set_Enum_Esize      (T);
13971       Set_Enum_Pos_To_Rep (T, Empty);
13972
13973       --  Set Discard_Names if configuration pragma set, or if there is
13974       --  a parameterless pragma in the current declarative region
13975
13976       if Global_Discard_Names
13977         or else Discard_Names (Scope (T))
13978       then
13979          Set_Discard_Names (T);
13980       end if;
13981
13982       --  Process end label if there is one
13983
13984       if Present (Def) then
13985          Process_End_Label (Def, 'e', T);
13986       end if;
13987    end Enumeration_Type_Declaration;
13988
13989    ---------------------------------
13990    -- Expand_To_Stored_Constraint --
13991    ---------------------------------
13992
13993    function Expand_To_Stored_Constraint
13994      (Typ        : Entity_Id;
13995       Constraint : Elist_Id) return Elist_Id
13996    is
13997       Explicitly_Discriminated_Type : Entity_Id;
13998       Expansion    : Elist_Id;
13999       Discriminant : Entity_Id;
14000
14001       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
14002       --  Find the nearest type that actually specifies discriminants
14003
14004       ---------------------------------
14005       -- Type_With_Explicit_Discrims --
14006       ---------------------------------
14007
14008       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
14009          Typ : constant E := Base_Type (Id);
14010
14011       begin
14012          if Ekind (Typ) in Incomplete_Or_Private_Kind then
14013             if Present (Full_View (Typ)) then
14014                return Type_With_Explicit_Discrims (Full_View (Typ));
14015             end if;
14016
14017          else
14018             if Has_Discriminants (Typ) then
14019                return Typ;
14020             end if;
14021          end if;
14022
14023          if Etype (Typ) = Typ then
14024             return Empty;
14025          elsif Has_Discriminants (Typ) then
14026             return Typ;
14027          else
14028             return Type_With_Explicit_Discrims (Etype (Typ));
14029          end if;
14030
14031       end Type_With_Explicit_Discrims;
14032
14033    --  Start of processing for Expand_To_Stored_Constraint
14034
14035    begin
14036       if No (Constraint)
14037         or else Is_Empty_Elmt_List (Constraint)
14038       then
14039          return No_Elist;
14040       end if;
14041
14042       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
14043
14044       if No (Explicitly_Discriminated_Type) then
14045          return No_Elist;
14046       end if;
14047
14048       Expansion := New_Elmt_List;
14049
14050       Discriminant :=
14051          First_Stored_Discriminant (Explicitly_Discriminated_Type);
14052       while Present (Discriminant) loop
14053          Append_Elmt (
14054            Get_Discriminant_Value (
14055              Discriminant, Explicitly_Discriminated_Type, Constraint),
14056            Expansion);
14057          Next_Stored_Discriminant (Discriminant);
14058       end loop;
14059
14060       return Expansion;
14061    end Expand_To_Stored_Constraint;
14062
14063    ---------------------------
14064    -- Find_Hidden_Interface --
14065    ---------------------------
14066
14067    function Find_Hidden_Interface
14068      (Src  : Elist_Id;
14069       Dest : Elist_Id) return Entity_Id
14070    is
14071       Iface      : Entity_Id;
14072       Iface_Elmt : Elmt_Id;
14073
14074    begin
14075       if Present (Src) and then Present (Dest) then
14076          Iface_Elmt := First_Elmt (Src);
14077          while Present (Iface_Elmt) loop
14078             Iface := Node (Iface_Elmt);
14079
14080             if Is_Interface (Iface)
14081               and then not Contain_Interface (Iface, Dest)
14082             then
14083                return Iface;
14084             end if;
14085
14086             Next_Elmt (Iface_Elmt);
14087          end loop;
14088       end if;
14089
14090       return Empty;
14091    end Find_Hidden_Interface;
14092
14093    --------------------
14094    -- Find_Type_Name --
14095    --------------------
14096
14097    function Find_Type_Name (N : Node_Id) return Entity_Id is
14098       Id       : constant Entity_Id := Defining_Identifier (N);
14099       Prev     : Entity_Id;
14100       New_Id   : Entity_Id;
14101       Prev_Par : Node_Id;
14102
14103       procedure Tag_Mismatch;
14104       --  Diagnose a tagged partial view whose full view is untagged.
14105       --  We post the message on the full view, with a reference to
14106       --  the previous partial view. The partial view can be private
14107       --  or incomplete, and these are handled in a different manner,
14108       --  so we determine the position of the error message from the
14109       --  respective slocs of both.
14110
14111       ------------------
14112       -- Tag_Mismatch --
14113       ------------------
14114
14115       procedure Tag_Mismatch is
14116       begin
14117          if Sloc (Prev) < Sloc (Id) then
14118             if Ada_Version >= Ada_2012
14119               and then Nkind (N) = N_Private_Type_Declaration
14120             then
14121                Error_Msg_NE
14122                  ("declaration of private } must be a tagged type ", Id, Prev);
14123             else
14124                Error_Msg_NE
14125                  ("full declaration of } must be a tagged type ", Id, Prev);
14126             end if;
14127          else
14128             if Ada_Version >= Ada_2012
14129               and then Nkind (N) = N_Private_Type_Declaration
14130             then
14131                Error_Msg_NE
14132                  ("declaration of private } must be a tagged type ", Prev, Id);
14133             else
14134                Error_Msg_NE
14135                  ("full declaration of } must be a tagged type ", Prev, Id);
14136             end if;
14137          end if;
14138       end Tag_Mismatch;
14139
14140    --  Start of processing for Find_Type_Name
14141
14142    begin
14143       --  Find incomplete declaration, if one was given
14144
14145       Prev := Current_Entity_In_Scope (Id);
14146
14147       --  New type declaration
14148
14149       if No (Prev) then
14150          Enter_Name (Id);
14151          return Id;
14152
14153       --  Previous declaration exists
14154
14155       else
14156          Prev_Par := Parent (Prev);
14157
14158          --  Error if not incomplete/private case except if previous
14159          --  declaration is implicit, etc. Enter_Name will emit error if
14160          --  appropriate.
14161
14162          if not Is_Incomplete_Or_Private_Type (Prev) then
14163             Enter_Name (Id);
14164             New_Id := Id;
14165
14166          --  Check invalid completion of private or incomplete type
14167
14168          elsif not Nkind_In (N, N_Full_Type_Declaration,
14169                                 N_Task_Type_Declaration,
14170                                 N_Protected_Type_Declaration)
14171            and then
14172              (Ada_Version < Ada_2012
14173                 or else not Is_Incomplete_Type (Prev)
14174                 or else not Nkind_In (N, N_Private_Type_Declaration,
14175                                          N_Private_Extension_Declaration))
14176          then
14177             --  Completion must be a full type declarations (RM 7.3(4))
14178
14179             Error_Msg_Sloc := Sloc (Prev);
14180             Error_Msg_NE ("invalid completion of }", Id, Prev);
14181
14182             --  Set scope of Id to avoid cascaded errors. Entity is never
14183             --  examined again, except when saving globals in generics.
14184
14185             Set_Scope (Id, Current_Scope);
14186             New_Id := Id;
14187
14188             --  If this is a repeated incomplete declaration, no further
14189             --  checks are possible.
14190
14191             if Nkind (N) = N_Incomplete_Type_Declaration then
14192                return Prev;
14193             end if;
14194
14195          --  Case of full declaration of incomplete type
14196
14197          elsif Ekind (Prev) = E_Incomplete_Type
14198            and then (Ada_Version < Ada_2012
14199                       or else No (Full_View (Prev))
14200                       or else not Is_Private_Type (Full_View (Prev)))
14201          then
14202
14203             --  Indicate that the incomplete declaration has a matching full
14204             --  declaration. The defining occurrence of the incomplete
14205             --  declaration remains the visible one, and the procedure
14206             --  Get_Full_View dereferences it whenever the type is used.
14207
14208             if Present (Full_View (Prev)) then
14209                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14210             end if;
14211
14212             Set_Full_View (Prev,  Id);
14213             Append_Entity (Id, Current_Scope);
14214             Set_Is_Public (Id, Is_Public (Prev));
14215             Set_Is_Internal (Id);
14216             New_Id := Prev;
14217
14218             --  If the incomplete view is tagged, a class_wide type has been
14219             --  created already. Use it for the private type as well, in order
14220             --  to prevent multiple incompatible class-wide types that may be
14221             --  created for self-referential anonymous access components.
14222
14223             if Is_Tagged_Type (Prev)
14224               and then Present (Class_Wide_Type (Prev))
14225             then
14226                Set_Ekind (Id, Ekind (Prev));         --  will be reset later
14227                Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
14228                Set_Etype (Class_Wide_Type (Id), Id);
14229             end if;
14230
14231          --  Case of full declaration of private type
14232
14233          else
14234             --  If the private type was a completion of an incomplete type then
14235             --  update Prev to reference the private type
14236
14237             if Ada_Version >= Ada_2012
14238               and then Ekind (Prev) = E_Incomplete_Type
14239               and then Present (Full_View (Prev))
14240               and then Is_Private_Type (Full_View (Prev))
14241             then
14242                Prev := Full_View (Prev);
14243                Prev_Par := Parent (Prev);
14244             end if;
14245
14246             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
14247                if Etype (Prev) /= Prev then
14248
14249                   --  Prev is a private subtype or a derived type, and needs
14250                   --  no completion.
14251
14252                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14253                   New_Id := Id;
14254
14255                elsif Ekind (Prev) = E_Private_Type
14256                  and then Nkind_In (N, N_Task_Type_Declaration,
14257                                        N_Protected_Type_Declaration)
14258                then
14259                   Error_Msg_N
14260                    ("completion of nonlimited type cannot be limited", N);
14261
14262                elsif Ekind (Prev) = E_Record_Type_With_Private
14263                  and then Nkind_In (N, N_Task_Type_Declaration,
14264                                        N_Protected_Type_Declaration)
14265                then
14266                   if not Is_Limited_Record (Prev) then
14267                      Error_Msg_N
14268                         ("completion of nonlimited type cannot be limited", N);
14269
14270                   elsif No (Interface_List (N)) then
14271                      Error_Msg_N
14272                         ("completion of tagged private type must be tagged",
14273                          N);
14274                   end if;
14275
14276                elsif Nkind (N) = N_Full_Type_Declaration
14277                  and then
14278                    Nkind (Type_Definition (N)) = N_Record_Definition
14279                  and then Interface_Present (Type_Definition (N))
14280                then
14281                   Error_Msg_N
14282                     ("completion of private type cannot be an interface", N);
14283                end if;
14284
14285             --  Ada 2005 (AI-251): Private extension declaration of a task
14286             --  type or a protected type. This case arises when covering
14287             --  interface types.
14288
14289             elsif Nkind_In (N, N_Task_Type_Declaration,
14290                                N_Protected_Type_Declaration)
14291             then
14292                null;
14293
14294             elsif Nkind (N) /= N_Full_Type_Declaration
14295               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
14296             then
14297                Error_Msg_N
14298                  ("full view of private extension must be an extension", N);
14299
14300             elsif not (Abstract_Present (Parent (Prev)))
14301               and then Abstract_Present (Type_Definition (N))
14302             then
14303                Error_Msg_N
14304                  ("full view of non-abstract extension cannot be abstract", N);
14305             end if;
14306
14307             if not In_Private_Part (Current_Scope) then
14308                Error_Msg_N
14309                  ("declaration of full view must appear in private part", N);
14310             end if;
14311
14312             Copy_And_Swap (Prev, Id);
14313             Set_Has_Private_Declaration (Prev);
14314             Set_Has_Private_Declaration (Id);
14315
14316             --  If no error, propagate freeze_node from private to full view.
14317             --  It may have been generated for an early operational item.
14318
14319             if Present (Freeze_Node (Id))
14320               and then Serious_Errors_Detected = 0
14321               and then No (Full_View (Id))
14322             then
14323                Set_Freeze_Node (Prev, Freeze_Node (Id));
14324                Set_Freeze_Node (Id, Empty);
14325                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
14326             end if;
14327
14328             Set_Full_View (Id, Prev);
14329             New_Id := Prev;
14330          end if;
14331
14332          --  Verify that full declaration conforms to partial one
14333
14334          if Is_Incomplete_Or_Private_Type (Prev)
14335            and then Present (Discriminant_Specifications (Prev_Par))
14336          then
14337             if Present (Discriminant_Specifications (N)) then
14338                if Ekind (Prev) = E_Incomplete_Type then
14339                   Check_Discriminant_Conformance (N, Prev, Prev);
14340                else
14341                   Check_Discriminant_Conformance (N, Prev, Id);
14342                end if;
14343
14344             else
14345                Error_Msg_N
14346                  ("missing discriminants in full type declaration", N);
14347
14348                --  To avoid cascaded errors on subsequent use, share the
14349                --  discriminants of the partial view.
14350
14351                Set_Discriminant_Specifications (N,
14352                  Discriminant_Specifications (Prev_Par));
14353             end if;
14354          end if;
14355
14356          --  A prior untagged partial view can have an associated class-wide
14357          --  type due to use of the class attribute, and in this case the full
14358          --  type must also be tagged. This Ada 95 usage is deprecated in favor
14359          --  of incomplete tagged declarations, but we check for it.
14360
14361          if Is_Type (Prev)
14362            and then (Is_Tagged_Type (Prev)
14363                        or else Present (Class_Wide_Type (Prev)))
14364          then
14365             --  Ada 2012 (AI05-0162): A private type may be the completion of
14366             --  an incomplete type
14367
14368             if Ada_Version >= Ada_2012
14369               and then Is_Incomplete_Type (Prev)
14370               and then Nkind_In (N, N_Private_Type_Declaration,
14371                                     N_Private_Extension_Declaration)
14372             then
14373                --  No need to check private extensions since they are tagged
14374
14375                if Nkind (N) = N_Private_Type_Declaration
14376                  and then not Tagged_Present (N)
14377                then
14378                   Tag_Mismatch;
14379                end if;
14380
14381             --  The full declaration is either a tagged type (including
14382             --  a synchronized type that implements interfaces) or a
14383             --  type extension, otherwise this is an error.
14384
14385             elsif Nkind_In (N, N_Task_Type_Declaration,
14386                                N_Protected_Type_Declaration)
14387             then
14388                if No (Interface_List (N))
14389                  and then not Error_Posted (N)
14390                then
14391                   Tag_Mismatch;
14392                end if;
14393
14394             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
14395
14396                --  Indicate that the previous declaration (tagged incomplete
14397                --  or private declaration) requires the same on the full one.
14398
14399                if not Tagged_Present (Type_Definition (N)) then
14400                   Tag_Mismatch;
14401                   Set_Is_Tagged_Type (Id);
14402                end if;
14403
14404             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
14405                if No (Record_Extension_Part (Type_Definition (N))) then
14406                   Error_Msg_NE
14407                     ("full declaration of } must be a record extension",
14408                      Prev, Id);
14409
14410                   --  Set some attributes to produce a usable full view
14411
14412                   Set_Is_Tagged_Type (Id);
14413                end if;
14414
14415             else
14416                Tag_Mismatch;
14417             end if;
14418          end if;
14419
14420          return New_Id;
14421       end if;
14422    end Find_Type_Name;
14423
14424    -------------------------
14425    -- Find_Type_Of_Object --
14426    -------------------------
14427
14428    function Find_Type_Of_Object
14429      (Obj_Def     : Node_Id;
14430       Related_Nod : Node_Id) return Entity_Id
14431    is
14432       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
14433       P        : Node_Id := Parent (Obj_Def);
14434       T        : Entity_Id;
14435       Nam      : Name_Id;
14436
14437    begin
14438       --  If the parent is a component_definition node we climb to the
14439       --  component_declaration node
14440
14441       if Nkind (P) = N_Component_Definition then
14442          P := Parent (P);
14443       end if;
14444
14445       --  Case of an anonymous array subtype
14446
14447       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
14448                              N_Unconstrained_Array_Definition)
14449       then
14450          T := Empty;
14451          Array_Type_Declaration (T, Obj_Def);
14452
14453       --  Create an explicit subtype whenever possible
14454
14455       elsif Nkind (P) /= N_Component_Declaration
14456         and then Def_Kind = N_Subtype_Indication
14457       then
14458          --  Base name of subtype on object name, which will be unique in
14459          --  the current scope.
14460
14461          --  If this is a duplicate declaration, return base type, to avoid
14462          --  generating duplicate anonymous types.
14463
14464          if Error_Posted (P) then
14465             Analyze (Subtype_Mark (Obj_Def));
14466             return Entity (Subtype_Mark (Obj_Def));
14467          end if;
14468
14469          Nam :=
14470             New_External_Name
14471              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
14472
14473          T := Make_Defining_Identifier (Sloc (P), Nam);
14474
14475          Insert_Action (Obj_Def,
14476            Make_Subtype_Declaration (Sloc (P),
14477              Defining_Identifier => T,
14478              Subtype_Indication  => Relocate_Node (Obj_Def)));
14479
14480          --  This subtype may need freezing, and this will not be done
14481          --  automatically if the object declaration is not in declarative
14482          --  part. Since this is an object declaration, the type cannot always
14483          --  be frozen here. Deferred constants do not freeze their type
14484          --  (which often enough will be private).
14485
14486          if Nkind (P) = N_Object_Declaration
14487            and then Constant_Present (P)
14488            and then No (Expression (P))
14489          then
14490             null;
14491          else
14492             Insert_Actions (Obj_Def, Freeze_Entity (T, P));
14493          end if;
14494
14495       --  Ada 2005 AI-406: the object definition in an object declaration
14496       --  can be an access definition.
14497
14498       elsif Def_Kind = N_Access_Definition then
14499          T := Access_Definition (Related_Nod, Obj_Def);
14500          Set_Is_Local_Anonymous_Access (T);
14501
14502       --  Otherwise, the object definition is just a subtype_mark
14503
14504       else
14505          T := Process_Subtype (Obj_Def, Related_Nod);
14506       end if;
14507
14508       return T;
14509    end Find_Type_Of_Object;
14510
14511    --------------------------------
14512    -- Find_Type_Of_Subtype_Indic --
14513    --------------------------------
14514
14515    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
14516       Typ : Entity_Id;
14517
14518    begin
14519       --  Case of subtype mark with a constraint
14520
14521       if Nkind (S) = N_Subtype_Indication then
14522          Find_Type (Subtype_Mark (S));
14523          Typ := Entity (Subtype_Mark (S));
14524
14525          if not
14526            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
14527          then
14528             Error_Msg_N
14529               ("incorrect constraint for this kind of type", Constraint (S));
14530             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
14531          end if;
14532
14533       --  Otherwise we have a subtype mark without a constraint
14534
14535       elsif Error_Posted (S) then
14536          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
14537          return Any_Type;
14538
14539       else
14540          Find_Type (S);
14541          Typ := Entity (S);
14542       end if;
14543
14544       --  Check No_Wide_Characters restriction
14545
14546       Check_Wide_Character_Restriction (Typ, S);
14547
14548       return Typ;
14549    end Find_Type_Of_Subtype_Indic;
14550
14551    -------------------------------------
14552    -- Floating_Point_Type_Declaration --
14553    -------------------------------------
14554
14555    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14556       Digs          : constant Node_Id := Digits_Expression (Def);
14557       Digs_Val      : Uint;
14558       Base_Typ      : Entity_Id;
14559       Implicit_Base : Entity_Id;
14560       Bound         : Node_Id;
14561
14562       function Can_Derive_From (E : Entity_Id) return Boolean;
14563       --  Find if given digits value allows derivation from specified type
14564
14565       ---------------------
14566       -- Can_Derive_From --
14567       ---------------------
14568
14569       function Can_Derive_From (E : Entity_Id) return Boolean is
14570          Spec : constant Entity_Id := Real_Range_Specification (Def);
14571
14572       begin
14573          if Digs_Val > Digits_Value (E) then
14574             return False;
14575          end if;
14576
14577          if Present (Spec) then
14578             if Expr_Value_R (Type_Low_Bound (E)) >
14579                Expr_Value_R (Low_Bound (Spec))
14580             then
14581                return False;
14582             end if;
14583
14584             if Expr_Value_R (Type_High_Bound (E)) <
14585                Expr_Value_R (High_Bound (Spec))
14586             then
14587                return False;
14588             end if;
14589          end if;
14590
14591          return True;
14592       end Can_Derive_From;
14593
14594    --  Start of processing for Floating_Point_Type_Declaration
14595
14596    begin
14597       Check_Restriction (No_Floating_Point, Def);
14598
14599       --  Create an implicit base type
14600
14601       Implicit_Base :=
14602         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
14603
14604       --  Analyze and verify digits value
14605
14606       Analyze_And_Resolve (Digs, Any_Integer);
14607       Check_Digits_Expression (Digs);
14608       Digs_Val := Expr_Value (Digs);
14609
14610       --  Process possible range spec and find correct type to derive from
14611
14612       Process_Real_Range_Specification (Def);
14613
14614       if Can_Derive_From (Standard_Short_Float) then
14615          Base_Typ := Standard_Short_Float;
14616       elsif Can_Derive_From (Standard_Float) then
14617          Base_Typ := Standard_Float;
14618       elsif Can_Derive_From (Standard_Long_Float) then
14619          Base_Typ := Standard_Long_Float;
14620       elsif Can_Derive_From (Standard_Long_Long_Float) then
14621          Base_Typ := Standard_Long_Long_Float;
14622
14623       --  If we can't derive from any existing type, use long_long_float
14624       --  and give appropriate message explaining the problem.
14625
14626       else
14627          Base_Typ := Standard_Long_Long_Float;
14628
14629          if Digs_Val >= Digits_Value (Standard_Long_Long_Float) then
14630             Error_Msg_Uint_1 := Digits_Value (Standard_Long_Long_Float);
14631             Error_Msg_N ("digits value out of range, maximum is ^", Digs);
14632
14633          else
14634             Error_Msg_N
14635               ("range too large for any predefined type",
14636                Real_Range_Specification (Def));
14637          end if;
14638       end if;
14639
14640       --  If there are bounds given in the declaration use them as the bounds
14641       --  of the type, otherwise use the bounds of the predefined base type
14642       --  that was chosen based on the Digits value.
14643
14644       if Present (Real_Range_Specification (Def)) then
14645          Set_Scalar_Range (T, Real_Range_Specification (Def));
14646          Set_Is_Constrained (T);
14647
14648          --  The bounds of this range must be converted to machine numbers
14649          --  in accordance with RM 4.9(38).
14650
14651          Bound := Type_Low_Bound (T);
14652
14653          if Nkind (Bound) = N_Real_Literal then
14654             Set_Realval
14655               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14656             Set_Is_Machine_Number (Bound);
14657          end if;
14658
14659          Bound := Type_High_Bound (T);
14660
14661          if Nkind (Bound) = N_Real_Literal then
14662             Set_Realval
14663               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14664             Set_Is_Machine_Number (Bound);
14665          end if;
14666
14667       else
14668          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
14669       end if;
14670
14671       --  Complete definition of implicit base and declared first subtype
14672
14673       Set_Etype          (Implicit_Base, Base_Typ);
14674
14675       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
14676       Set_Size_Info      (Implicit_Base,                (Base_Typ));
14677       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
14678       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
14679       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
14680       Set_Vax_Float      (Implicit_Base, Vax_Float      (Base_Typ));
14681
14682       Set_Ekind          (T, E_Floating_Point_Subtype);
14683       Set_Etype          (T, Implicit_Base);
14684
14685       Set_Size_Info      (T,                (Implicit_Base));
14686       Set_RM_Size        (T, RM_Size        (Implicit_Base));
14687       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
14688       Set_Digits_Value   (T, Digs_Val);
14689    end Floating_Point_Type_Declaration;
14690
14691    ----------------------------
14692    -- Get_Discriminant_Value --
14693    ----------------------------
14694
14695    --  This is the situation:
14696
14697    --  There is a non-derived type
14698
14699    --       type T0 (Dx, Dy, Dz...)
14700
14701    --  There are zero or more levels of derivation, with each derivation
14702    --  either purely inheriting the discriminants, or defining its own.
14703
14704    --       type Ti      is new Ti-1
14705    --  or
14706    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
14707    --  or
14708    --       subtype Ti is ...
14709
14710    --  The subtype issue is avoided by the use of Original_Record_Component,
14711    --  and the fact that derived subtypes also derive the constraints.
14712
14713    --  This chain leads back from
14714
14715    --       Typ_For_Constraint
14716
14717    --  Typ_For_Constraint has discriminants, and the value for each
14718    --  discriminant is given by its corresponding Elmt of Constraints.
14719
14720    --  Discriminant is some discriminant in this hierarchy
14721
14722    --  We need to return its value
14723
14724    --  We do this by recursively searching each level, and looking for
14725    --  Discriminant. Once we get to the bottom, we start backing up
14726    --  returning the value for it which may in turn be a discriminant
14727    --  further up, so on the backup we continue the substitution.
14728
14729    function Get_Discriminant_Value
14730      (Discriminant       : Entity_Id;
14731       Typ_For_Constraint : Entity_Id;
14732       Constraint         : Elist_Id) return Node_Id
14733    is
14734       function Search_Derivation_Levels
14735         (Ti                    : Entity_Id;
14736          Discrim_Values        : Elist_Id;
14737          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
14738       --  This is the routine that performs the recursive search of levels
14739       --  as described above.
14740
14741       ------------------------------
14742       -- Search_Derivation_Levels --
14743       ------------------------------
14744
14745       function Search_Derivation_Levels
14746         (Ti                    : Entity_Id;
14747          Discrim_Values        : Elist_Id;
14748          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
14749       is
14750          Assoc          : Elmt_Id;
14751          Disc           : Entity_Id;
14752          Result         : Node_Or_Entity_Id;
14753          Result_Entity  : Node_Id;
14754
14755       begin
14756          --  If inappropriate type, return Error, this happens only in
14757          --  cascaded error situations, and we want to avoid a blow up.
14758
14759          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
14760             return Error;
14761          end if;
14762
14763          --  Look deeper if possible. Use Stored_Constraints only for
14764          --  untagged types. For tagged types use the given constraint.
14765          --  This asymmetry needs explanation???
14766
14767          if not Stored_Discrim_Values
14768            and then Present (Stored_Constraint (Ti))
14769            and then not Is_Tagged_Type (Ti)
14770          then
14771             Result :=
14772               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
14773          else
14774             declare
14775                Td : constant Entity_Id := Etype (Ti);
14776
14777             begin
14778                if Td = Ti then
14779                   Result := Discriminant;
14780
14781                else
14782                   if Present (Stored_Constraint (Ti)) then
14783                      Result :=
14784                         Search_Derivation_Levels
14785                           (Td, Stored_Constraint (Ti), True);
14786                   else
14787                      Result :=
14788                         Search_Derivation_Levels
14789                           (Td, Discrim_Values, Stored_Discrim_Values);
14790                   end if;
14791                end if;
14792             end;
14793          end if;
14794
14795          --  Extra underlying places to search, if not found above. For
14796          --  concurrent types, the relevant discriminant appears in the
14797          --  corresponding record. For a type derived from a private type
14798          --  without discriminant, the full view inherits the discriminants
14799          --  of the full view of the parent.
14800
14801          if Result = Discriminant then
14802             if Is_Concurrent_Type (Ti)
14803               and then Present (Corresponding_Record_Type (Ti))
14804             then
14805                Result :=
14806                  Search_Derivation_Levels (
14807                    Corresponding_Record_Type (Ti),
14808                    Discrim_Values,
14809                    Stored_Discrim_Values);
14810
14811             elsif Is_Private_Type (Ti)
14812               and then not Has_Discriminants (Ti)
14813               and then Present (Full_View (Ti))
14814               and then Etype (Full_View (Ti)) /= Ti
14815             then
14816                Result :=
14817                  Search_Derivation_Levels (
14818                    Full_View (Ti),
14819                    Discrim_Values,
14820                    Stored_Discrim_Values);
14821             end if;
14822          end if;
14823
14824          --  If Result is not a (reference to a) discriminant, return it,
14825          --  otherwise set Result_Entity to the discriminant.
14826
14827          if Nkind (Result) = N_Defining_Identifier then
14828             pragma Assert (Result = Discriminant);
14829             Result_Entity := Result;
14830
14831          else
14832             if not Denotes_Discriminant (Result) then
14833                return Result;
14834             end if;
14835
14836             Result_Entity := Entity (Result);
14837          end if;
14838
14839          --  See if this level of derivation actually has discriminants
14840          --  because tagged derivations can add them, hence the lower
14841          --  levels need not have any.
14842
14843          if not Has_Discriminants (Ti) then
14844             return Result;
14845          end if;
14846
14847          --  Scan Ti's discriminants for Result_Entity,
14848          --  and return its corresponding value, if any.
14849
14850          Result_Entity := Original_Record_Component (Result_Entity);
14851
14852          Assoc := First_Elmt (Discrim_Values);
14853
14854          if Stored_Discrim_Values then
14855             Disc := First_Stored_Discriminant (Ti);
14856          else
14857             Disc := First_Discriminant (Ti);
14858          end if;
14859
14860          while Present (Disc) loop
14861             pragma Assert (Present (Assoc));
14862
14863             if Original_Record_Component (Disc) = Result_Entity then
14864                return Node (Assoc);
14865             end if;
14866
14867             Next_Elmt (Assoc);
14868
14869             if Stored_Discrim_Values then
14870                Next_Stored_Discriminant (Disc);
14871             else
14872                Next_Discriminant (Disc);
14873             end if;
14874          end loop;
14875
14876          --  Could not find it
14877          --
14878          return Result;
14879       end Search_Derivation_Levels;
14880
14881       --  Local Variables
14882
14883       Result : Node_Or_Entity_Id;
14884
14885    --  Start of processing for Get_Discriminant_Value
14886
14887    begin
14888       --  ??? This routine is a gigantic mess and will be deleted. For the
14889       --  time being just test for the trivial case before calling recurse.
14890
14891       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
14892          declare
14893             D : Entity_Id;
14894             E : Elmt_Id;
14895
14896          begin
14897             D := First_Discriminant (Typ_For_Constraint);
14898             E := First_Elmt (Constraint);
14899             while Present (D) loop
14900                if Chars (D) = Chars (Discriminant) then
14901                   return Node (E);
14902                end if;
14903
14904                Next_Discriminant (D);
14905                Next_Elmt (E);
14906             end loop;
14907          end;
14908       end if;
14909
14910       Result := Search_Derivation_Levels
14911         (Typ_For_Constraint, Constraint, False);
14912
14913       --  ??? hack to disappear when this routine is gone
14914
14915       if  Nkind (Result) = N_Defining_Identifier then
14916          declare
14917             D : Entity_Id;
14918             E : Elmt_Id;
14919
14920          begin
14921             D := First_Discriminant (Typ_For_Constraint);
14922             E := First_Elmt (Constraint);
14923             while Present (D) loop
14924                if Corresponding_Discriminant (D) = Discriminant then
14925                   return Node (E);
14926                end if;
14927
14928                Next_Discriminant (D);
14929                Next_Elmt (E);
14930             end loop;
14931          end;
14932       end if;
14933
14934       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
14935       return Result;
14936    end Get_Discriminant_Value;
14937
14938    --------------------------
14939    -- Has_Range_Constraint --
14940    --------------------------
14941
14942    function Has_Range_Constraint (N : Node_Id) return Boolean is
14943       C : constant Node_Id := Constraint (N);
14944
14945    begin
14946       if Nkind (C) = N_Range_Constraint then
14947          return True;
14948
14949       elsif Nkind (C) = N_Digits_Constraint then
14950          return
14951             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
14952               or else
14953             Present (Range_Constraint (C));
14954
14955       elsif Nkind (C) = N_Delta_Constraint then
14956          return Present (Range_Constraint (C));
14957
14958       else
14959          return False;
14960       end if;
14961    end Has_Range_Constraint;
14962
14963    ------------------------
14964    -- Inherit_Components --
14965    ------------------------
14966
14967    function Inherit_Components
14968      (N             : Node_Id;
14969       Parent_Base   : Entity_Id;
14970       Derived_Base  : Entity_Id;
14971       Is_Tagged     : Boolean;
14972       Inherit_Discr : Boolean;
14973       Discs         : Elist_Id) return Elist_Id
14974    is
14975       Assoc_List : constant Elist_Id := New_Elmt_List;
14976
14977       procedure Inherit_Component
14978         (Old_C          : Entity_Id;
14979          Plain_Discrim  : Boolean := False;
14980          Stored_Discrim : Boolean := False);
14981       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
14982       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
14983       --  True, Old_C is a stored discriminant. If they are both false then
14984       --  Old_C is a regular component.
14985
14986       -----------------------
14987       -- Inherit_Component --
14988       -----------------------
14989
14990       procedure Inherit_Component
14991         (Old_C          : Entity_Id;
14992          Plain_Discrim  : Boolean := False;
14993          Stored_Discrim : Boolean := False)
14994       is
14995          New_C : constant Entity_Id := New_Copy (Old_C);
14996
14997          Discrim      : Entity_Id;
14998          Corr_Discrim : Entity_Id;
14999
15000       begin
15001          pragma Assert (not Is_Tagged or else not Stored_Discrim);
15002
15003          Set_Parent (New_C, Parent (Old_C));
15004
15005          --  Regular discriminants and components must be inserted in the scope
15006          --  of the Derived_Base. Do it here.
15007
15008          if not Stored_Discrim then
15009             Enter_Name (New_C);
15010          end if;
15011
15012          --  For tagged types the Original_Record_Component must point to
15013          --  whatever this field was pointing to in the parent type. This has
15014          --  already been achieved by the call to New_Copy above.
15015
15016          if not Is_Tagged then
15017             Set_Original_Record_Component (New_C, New_C);
15018          end if;
15019
15020          --  If we have inherited a component then see if its Etype contains
15021          --  references to Parent_Base discriminants. In this case, replace
15022          --  these references with the constraints given in Discs. We do not
15023          --  do this for the partial view of private types because this is
15024          --  not needed (only the components of the full view will be used
15025          --  for code generation) and cause problem. We also avoid this
15026          --  transformation in some error situations.
15027
15028          if Ekind (New_C) = E_Component then
15029             if (Is_Private_Type (Derived_Base)
15030                  and then not Is_Generic_Type (Derived_Base))
15031               or else (Is_Empty_Elmt_List (Discs)
15032                         and then  not Expander_Active)
15033             then
15034                Set_Etype (New_C, Etype (Old_C));
15035
15036             else
15037                --  The current component introduces a circularity of the
15038                --  following kind:
15039
15040                --     limited with Pack_2;
15041                --     package Pack_1 is
15042                --        type T_1 is tagged record
15043                --           Comp : access Pack_2.T_2;
15044                --           ...
15045                --        end record;
15046                --     end Pack_1;
15047
15048                --     with Pack_1;
15049                --     package Pack_2 is
15050                --        type T_2 is new Pack_1.T_1 with ...;
15051                --     end Pack_2;
15052
15053                Set_Etype
15054                  (New_C,
15055                   Constrain_Component_Type
15056                   (Old_C, Derived_Base, N, Parent_Base, Discs));
15057             end if;
15058          end if;
15059
15060          --  In derived tagged types it is illegal to reference a non
15061          --  discriminant component in the parent type. To catch this, mark
15062          --  these components with an Ekind of E_Void. This will be reset in
15063          --  Record_Type_Definition after processing the record extension of
15064          --  the derived type.
15065
15066          --  If the declaration is a private extension, there is no further
15067          --  record extension to process, and the components retain their
15068          --  current kind, because they are visible at this point.
15069
15070          if Is_Tagged and then Ekind (New_C) = E_Component
15071            and then Nkind (N) /= N_Private_Extension_Declaration
15072          then
15073             Set_Ekind (New_C, E_Void);
15074          end if;
15075
15076          if Plain_Discrim then
15077             Set_Corresponding_Discriminant (New_C, Old_C);
15078             Build_Discriminal (New_C);
15079
15080          --  If we are explicitly inheriting a stored discriminant it will be
15081          --  completely hidden.
15082
15083          elsif Stored_Discrim then
15084             Set_Corresponding_Discriminant (New_C, Empty);
15085             Set_Discriminal (New_C, Empty);
15086             Set_Is_Completely_Hidden (New_C);
15087
15088             --  Set the Original_Record_Component of each discriminant in the
15089             --  derived base to point to the corresponding stored that we just
15090             --  created.
15091
15092             Discrim := First_Discriminant (Derived_Base);
15093             while Present (Discrim) loop
15094                Corr_Discrim := Corresponding_Discriminant (Discrim);
15095
15096                --  Corr_Discrim could be missing in an error situation
15097
15098                if Present (Corr_Discrim)
15099                  and then Original_Record_Component (Corr_Discrim) = Old_C
15100                then
15101                   Set_Original_Record_Component (Discrim, New_C);
15102                end if;
15103
15104                Next_Discriminant (Discrim);
15105             end loop;
15106
15107             Append_Entity (New_C, Derived_Base);
15108          end if;
15109
15110          if not Is_Tagged then
15111             Append_Elmt (Old_C, Assoc_List);
15112             Append_Elmt (New_C, Assoc_List);
15113          end if;
15114       end Inherit_Component;
15115
15116       --  Variables local to Inherit_Component
15117
15118       Loc : constant Source_Ptr := Sloc (N);
15119
15120       Parent_Discrim : Entity_Id;
15121       Stored_Discrim : Entity_Id;
15122       D              : Entity_Id;
15123       Component      : Entity_Id;
15124
15125    --  Start of processing for Inherit_Components
15126
15127    begin
15128       if not Is_Tagged then
15129          Append_Elmt (Parent_Base,  Assoc_List);
15130          Append_Elmt (Derived_Base, Assoc_List);
15131       end if;
15132
15133       --  Inherit parent discriminants if needed
15134
15135       if Inherit_Discr then
15136          Parent_Discrim := First_Discriminant (Parent_Base);
15137          while Present (Parent_Discrim) loop
15138             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
15139             Next_Discriminant (Parent_Discrim);
15140          end loop;
15141       end if;
15142
15143       --  Create explicit stored discrims for untagged types when necessary
15144
15145       if not Has_Unknown_Discriminants (Derived_Base)
15146         and then Has_Discriminants (Parent_Base)
15147         and then not Is_Tagged
15148         and then
15149           (not Inherit_Discr
15150              or else First_Discriminant (Parent_Base) /=
15151                      First_Stored_Discriminant (Parent_Base))
15152       then
15153          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
15154          while Present (Stored_Discrim) loop
15155             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
15156             Next_Stored_Discriminant (Stored_Discrim);
15157          end loop;
15158       end if;
15159
15160       --  See if we can apply the second transformation for derived types, as
15161       --  explained in point 6. in the comments above Build_Derived_Record_Type
15162       --  This is achieved by appending Derived_Base discriminants into Discs,
15163       --  which has the side effect of returning a non empty Discs list to the
15164       --  caller of Inherit_Components, which is what we want. This must be
15165       --  done for private derived types if there are explicit stored
15166       --  discriminants, to ensure that we can retrieve the values of the
15167       --  constraints provided in the ancestors.
15168
15169       if Inherit_Discr
15170         and then Is_Empty_Elmt_List (Discs)
15171         and then Present (First_Discriminant (Derived_Base))
15172         and then
15173           (not Is_Private_Type (Derived_Base)
15174              or else Is_Completely_Hidden
15175                (First_Stored_Discriminant (Derived_Base))
15176              or else Is_Generic_Type (Derived_Base))
15177       then
15178          D := First_Discriminant (Derived_Base);
15179          while Present (D) loop
15180             Append_Elmt (New_Reference_To (D, Loc), Discs);
15181             Next_Discriminant (D);
15182          end loop;
15183       end if;
15184
15185       --  Finally, inherit non-discriminant components unless they are not
15186       --  visible because defined or inherited from the full view of the
15187       --  parent. Don't inherit the _parent field of the parent type.
15188
15189       Component := First_Entity (Parent_Base);
15190       while Present (Component) loop
15191
15192          --  Ada 2005 (AI-251): Do not inherit components associated with
15193          --  secondary tags of the parent.
15194
15195          if Ekind (Component) = E_Component
15196            and then Present (Related_Type (Component))
15197          then
15198             null;
15199
15200          elsif Ekind (Component) /= E_Component
15201            or else Chars (Component) = Name_uParent
15202          then
15203             null;
15204
15205          --  If the derived type is within the parent type's declarative
15206          --  region, then the components can still be inherited even though
15207          --  they aren't visible at this point. This can occur for cases
15208          --  such as within public child units where the components must
15209          --  become visible upon entering the child unit's private part.
15210
15211          elsif not Is_Visible_Component (Component)
15212            and then not In_Open_Scopes (Scope (Parent_Base))
15213          then
15214             null;
15215
15216          elsif Ekind_In (Derived_Base, E_Private_Type,
15217                                        E_Limited_Private_Type)
15218          then
15219             null;
15220
15221          else
15222             Inherit_Component (Component);
15223          end if;
15224
15225          Next_Entity (Component);
15226       end loop;
15227
15228       --  For tagged derived types, inherited discriminants cannot be used in
15229       --  component declarations of the record extension part. To achieve this
15230       --  we mark the inherited discriminants as not visible.
15231
15232       if Is_Tagged and then Inherit_Discr then
15233          D := First_Discriminant (Derived_Base);
15234          while Present (D) loop
15235             Set_Is_Immediately_Visible (D, False);
15236             Next_Discriminant (D);
15237          end loop;
15238       end if;
15239
15240       return Assoc_List;
15241    end Inherit_Components;
15242
15243    -----------------------
15244    -- Is_Null_Extension --
15245    -----------------------
15246
15247    function Is_Null_Extension (T : Entity_Id) return Boolean is
15248       Type_Decl : constant Node_Id := Parent (Base_Type (T));
15249       Comp_List : Node_Id;
15250       Comp      : Node_Id;
15251
15252    begin
15253       if Nkind (Type_Decl) /= N_Full_Type_Declaration
15254         or else not Is_Tagged_Type (T)
15255         or else Nkind (Type_Definition (Type_Decl)) /=
15256                                               N_Derived_Type_Definition
15257         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
15258       then
15259          return False;
15260       end if;
15261
15262       Comp_List :=
15263         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
15264
15265       if Present (Discriminant_Specifications (Type_Decl)) then
15266          return False;
15267
15268       elsif Present (Comp_List)
15269         and then Is_Non_Empty_List (Component_Items (Comp_List))
15270       then
15271          Comp := First (Component_Items (Comp_List));
15272
15273          --  Only user-defined components are relevant. The component list
15274          --  may also contain a parent component and internal components
15275          --  corresponding to secondary tags, but these do not determine
15276          --  whether this is a null extension.
15277
15278          while Present (Comp) loop
15279             if Comes_From_Source (Comp) then
15280                return False;
15281             end if;
15282
15283             Next (Comp);
15284          end loop;
15285
15286          return True;
15287       else
15288          return True;
15289       end if;
15290    end Is_Null_Extension;
15291
15292    ------------------------------
15293    -- Is_Valid_Constraint_Kind --
15294    ------------------------------
15295
15296    function Is_Valid_Constraint_Kind
15297      (T_Kind          : Type_Kind;
15298       Constraint_Kind : Node_Kind) return Boolean
15299    is
15300    begin
15301       case T_Kind is
15302          when Enumeration_Kind |
15303               Integer_Kind =>
15304             return Constraint_Kind = N_Range_Constraint;
15305
15306          when Decimal_Fixed_Point_Kind =>
15307             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
15308                                               N_Range_Constraint);
15309
15310          when Ordinary_Fixed_Point_Kind =>
15311             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
15312                                               N_Range_Constraint);
15313
15314          when Float_Kind =>
15315             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
15316                                               N_Range_Constraint);
15317
15318          when Access_Kind       |
15319               Array_Kind        |
15320               E_Record_Type     |
15321               E_Record_Subtype  |
15322               Class_Wide_Kind   |
15323               E_Incomplete_Type |
15324               Private_Kind      |
15325               Concurrent_Kind  =>
15326             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
15327
15328          when others =>
15329             return True; -- Error will be detected later
15330       end case;
15331    end Is_Valid_Constraint_Kind;
15332
15333    --------------------------
15334    -- Is_Visible_Component --
15335    --------------------------
15336
15337    function Is_Visible_Component (C : Entity_Id) return Boolean is
15338       Original_Comp  : Entity_Id := Empty;
15339       Original_Scope : Entity_Id;
15340       Type_Scope     : Entity_Id;
15341
15342       function Is_Local_Type (Typ : Entity_Id) return Boolean;
15343       --  Check whether parent type of inherited component is declared locally,
15344       --  possibly within a nested package or instance. The current scope is
15345       --  the derived record itself.
15346
15347       -------------------
15348       -- Is_Local_Type --
15349       -------------------
15350
15351       function Is_Local_Type (Typ : Entity_Id) return Boolean is
15352          Scop : Entity_Id;
15353
15354       begin
15355          Scop := Scope (Typ);
15356          while Present (Scop)
15357            and then Scop /= Standard_Standard
15358          loop
15359             if Scop = Scope (Current_Scope) then
15360                return True;
15361             end if;
15362
15363             Scop := Scope (Scop);
15364          end loop;
15365
15366          return False;
15367       end Is_Local_Type;
15368
15369    --  Start of processing for Is_Visible_Component
15370
15371    begin
15372       if Ekind_In (C, E_Component, E_Discriminant) then
15373          Original_Comp := Original_Record_Component (C);
15374       end if;
15375
15376       if No (Original_Comp) then
15377
15378          --  Premature usage, or previous error
15379
15380          return False;
15381
15382       else
15383          Original_Scope := Scope (Original_Comp);
15384          Type_Scope     := Scope (Base_Type (Scope (C)));
15385       end if;
15386
15387       --  This test only concerns tagged types
15388
15389       if not Is_Tagged_Type (Original_Scope) then
15390          return True;
15391
15392       --  If it is _Parent or _Tag, there is no visibility issue
15393
15394       elsif not Comes_From_Source (Original_Comp) then
15395          return True;
15396
15397       --  If we are in the body of an instantiation, the component is visible
15398       --  even when the parent type (possibly defined in an enclosing unit or
15399       --  in a parent unit) might not.
15400
15401       elsif In_Instance_Body then
15402          return True;
15403
15404       --  Discriminants are always visible
15405
15406       elsif Ekind (Original_Comp) = E_Discriminant
15407         and then not Has_Unknown_Discriminants (Original_Scope)
15408       then
15409          return True;
15410
15411       --  If the component has been declared in an ancestor which is currently
15412       --  a private type, then it is not visible. The same applies if the
15413       --  component's containing type is not in an open scope and the original
15414       --  component's enclosing type is a visible full view of a private type
15415       --  (which can occur in cases where an attempt is being made to reference
15416       --  a component in a sibling package that is inherited from a visible
15417       --  component of a type in an ancestor package; the component in the
15418       --  sibling package should not be visible even though the component it
15419       --  inherited from is visible). This does not apply however in the case
15420       --  where the scope of the type is a private child unit, or when the
15421       --  parent comes from a local package in which the ancestor is currently
15422       --  visible. The latter suppression of visibility is needed for cases
15423       --  that are tested in B730006.
15424
15425       elsif Is_Private_Type (Original_Scope)
15426         or else
15427           (not Is_Private_Descendant (Type_Scope)
15428             and then not In_Open_Scopes (Type_Scope)
15429             and then Has_Private_Declaration (Original_Scope))
15430       then
15431          --  If the type derives from an entity in a formal package, there
15432          --  are no additional visible components.
15433
15434          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
15435             N_Formal_Package_Declaration
15436          then
15437             return False;
15438
15439          --  if we are not in the private part of the current package, there
15440          --  are no additional visible components.
15441
15442          elsif Ekind (Scope (Current_Scope)) = E_Package
15443            and then not In_Private_Part (Scope (Current_Scope))
15444          then
15445             return False;
15446          else
15447             return
15448               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
15449                 and then In_Open_Scopes (Scope (Original_Scope))
15450                 and then Is_Local_Type (Type_Scope);
15451          end if;
15452
15453       --  There is another weird way in which a component may be invisible
15454       --  when the private and the full view are not derived from the same
15455       --  ancestor. Here is an example :
15456
15457       --       type A1 is tagged      record F1 : integer; end record;
15458       --       type A2 is new A1 with record F2 : integer; end record;
15459       --       type T is new A1 with private;
15460       --     private
15461       --       type T is new A2 with null record;
15462
15463       --  In this case, the full view of T inherits F1 and F2 but the private
15464       --  view inherits only F1
15465
15466       else
15467          declare
15468             Ancestor : Entity_Id := Scope (C);
15469
15470          begin
15471             loop
15472                if Ancestor = Original_Scope then
15473                   return True;
15474                elsif Ancestor = Etype (Ancestor) then
15475                   return False;
15476                end if;
15477
15478                Ancestor := Etype (Ancestor);
15479             end loop;
15480          end;
15481       end if;
15482    end Is_Visible_Component;
15483
15484    --------------------------
15485    -- Make_Class_Wide_Type --
15486    --------------------------
15487
15488    procedure Make_Class_Wide_Type (T : Entity_Id) is
15489       CW_Type : Entity_Id;
15490       CW_Name : Name_Id;
15491       Next_E  : Entity_Id;
15492
15493    begin
15494       --  The class wide type can have been defined by the partial view, in
15495       --  which case everything is already done.
15496
15497       if Present (Class_Wide_Type (T)) then
15498          return;
15499       end if;
15500
15501       CW_Type :=
15502         New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
15503
15504       --  Inherit root type characteristics
15505
15506       CW_Name := Chars (CW_Type);
15507       Next_E  := Next_Entity (CW_Type);
15508       Copy_Node (T, CW_Type);
15509       Set_Comes_From_Source (CW_Type, False);
15510       Set_Chars (CW_Type, CW_Name);
15511       Set_Parent (CW_Type, Parent (T));
15512       Set_Next_Entity (CW_Type, Next_E);
15513
15514       --  Ensure we have a new freeze node for the class-wide type. The partial
15515       --  view may have freeze action of its own, requiring a proper freeze
15516       --  node, and the same freeze node cannot be shared between the two
15517       --  types.
15518
15519       Set_Has_Delayed_Freeze (CW_Type);
15520       Set_Freeze_Node (CW_Type, Empty);
15521
15522       --  Customize the class-wide type: It has no prim. op., it cannot be
15523       --  abstract and its Etype points back to the specific root type.
15524
15525       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
15526       Set_Is_Tagged_Type              (CW_Type, True);
15527       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
15528       Set_Is_Abstract_Type            (CW_Type, False);
15529       Set_Is_Constrained              (CW_Type, False);
15530       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
15531
15532       if Ekind (T) = E_Class_Wide_Subtype then
15533          Set_Etype             (CW_Type, Etype (Base_Type (T)));
15534       else
15535          Set_Etype             (CW_Type, T);
15536       end if;
15537
15538       --  If this is the class_wide type of a constrained subtype, it does
15539       --  not have discriminants.
15540
15541       Set_Has_Discriminants (CW_Type,
15542         Has_Discriminants (T) and then not Is_Constrained (T));
15543
15544       Set_Has_Unknown_Discriminants (CW_Type, True);
15545       Set_Class_Wide_Type (T, CW_Type);
15546       Set_Equivalent_Type (CW_Type, Empty);
15547
15548       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
15549
15550       Set_Class_Wide_Type (CW_Type, CW_Type);
15551    end Make_Class_Wide_Type;
15552
15553    ----------------
15554    -- Make_Index --
15555    ----------------
15556
15557    procedure Make_Index
15558      (I            : Node_Id;
15559       Related_Nod  : Node_Id;
15560       Related_Id   : Entity_Id := Empty;
15561       Suffix_Index : Nat := 1)
15562    is
15563       R      : Node_Id;
15564       T      : Entity_Id;
15565       Def_Id : Entity_Id := Empty;
15566       Found  : Boolean := False;
15567
15568    begin
15569       --  For a discrete range used in a constrained array definition and
15570       --  defined by a range, an implicit conversion to the predefined type
15571       --  INTEGER is assumed if each bound is either a numeric literal, a named
15572       --  number, or an attribute, and the type of both bounds (prior to the
15573       --  implicit conversion) is the type universal_integer. Otherwise, both
15574       --  bounds must be of the same discrete type, other than universal
15575       --  integer; this type must be determinable independently of the
15576       --  context, but using the fact that the type must be discrete and that
15577       --  both bounds must have the same type.
15578
15579       --  Character literals also have a universal type in the absence of
15580       --  of additional context,  and are resolved to Standard_Character.
15581
15582       if Nkind (I) = N_Range then
15583
15584          --  The index is given by a range constraint. The bounds are known
15585          --  to be of a consistent type.
15586
15587          if not Is_Overloaded (I) then
15588             T := Etype (I);
15589
15590             --  For universal bounds, choose the specific predefined type
15591
15592             if T = Universal_Integer then
15593                T := Standard_Integer;
15594
15595             elsif T = Any_Character then
15596                Ambiguous_Character (Low_Bound (I));
15597
15598                T := Standard_Character;
15599             end if;
15600
15601          --  The node may be overloaded because some user-defined operators
15602          --  are available, but if a universal interpretation exists it is
15603          --  also the selected one.
15604
15605          elsif Universal_Interpretation (I) = Universal_Integer then
15606             T := Standard_Integer;
15607
15608          else
15609             T := Any_Type;
15610
15611             declare
15612                Ind : Interp_Index;
15613                It  : Interp;
15614
15615             begin
15616                Get_First_Interp (I, Ind, It);
15617                while Present (It.Typ) loop
15618                   if Is_Discrete_Type (It.Typ) then
15619
15620                      if Found
15621                        and then not Covers (It.Typ, T)
15622                        and then not Covers (T, It.Typ)
15623                      then
15624                         Error_Msg_N ("ambiguous bounds in discrete range", I);
15625                         exit;
15626                      else
15627                         T := It.Typ;
15628                         Found := True;
15629                      end if;
15630                   end if;
15631
15632                   Get_Next_Interp (Ind, It);
15633                end loop;
15634
15635                if T = Any_Type then
15636                   Error_Msg_N ("discrete type required for range", I);
15637                   Set_Etype (I, Any_Type);
15638                   return;
15639
15640                elsif T = Universal_Integer then
15641                   T := Standard_Integer;
15642                end if;
15643             end;
15644          end if;
15645
15646          if not Is_Discrete_Type (T) then
15647             Error_Msg_N ("discrete type required for range", I);
15648             Set_Etype (I, Any_Type);
15649             return;
15650          end if;
15651
15652          if Nkind (Low_Bound (I)) = N_Attribute_Reference
15653            and then Attribute_Name (Low_Bound (I)) = Name_First
15654            and then Is_Entity_Name (Prefix (Low_Bound (I)))
15655            and then Is_Type (Entity (Prefix (Low_Bound (I))))
15656            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
15657          then
15658             --  The type of the index will be the type of the prefix, as long
15659             --  as the upper bound is 'Last of the same type.
15660
15661             Def_Id := Entity (Prefix (Low_Bound (I)));
15662
15663             if Nkind (High_Bound (I)) /= N_Attribute_Reference
15664               or else Attribute_Name (High_Bound (I)) /= Name_Last
15665               or else not Is_Entity_Name (Prefix (High_Bound (I)))
15666               or else Entity (Prefix (High_Bound (I))) /= Def_Id
15667             then
15668                Def_Id := Empty;
15669             end if;
15670          end if;
15671
15672          R := I;
15673          Process_Range_Expr_In_Decl (R, T);
15674
15675       elsif Nkind (I) = N_Subtype_Indication then
15676
15677          --  The index is given by a subtype with a range constraint
15678
15679          T :=  Base_Type (Entity (Subtype_Mark (I)));
15680
15681          if not Is_Discrete_Type (T) then
15682             Error_Msg_N ("discrete type required for range", I);
15683             Set_Etype (I, Any_Type);
15684             return;
15685          end if;
15686
15687          R := Range_Expression (Constraint (I));
15688
15689          Resolve (R, T);
15690          Process_Range_Expr_In_Decl (R, Entity (Subtype_Mark (I)));
15691
15692       elsif Nkind (I) = N_Attribute_Reference then
15693
15694          --  The parser guarantees that the attribute is a RANGE attribute
15695
15696          --  If the node denotes the range of a type mark, that is also the
15697          --  resulting type, and we do no need to create an Itype for it.
15698
15699          if Is_Entity_Name (Prefix (I))
15700            and then Comes_From_Source (I)
15701            and then Is_Type (Entity (Prefix (I)))
15702            and then Is_Discrete_Type (Entity (Prefix (I)))
15703          then
15704             Def_Id := Entity (Prefix (I));
15705          end if;
15706
15707          Analyze_And_Resolve (I);
15708          T := Etype (I);
15709          R := I;
15710
15711       --  If none of the above, must be a subtype. We convert this to a
15712       --  range attribute reference because in the case of declared first
15713       --  named subtypes, the types in the range reference can be different
15714       --  from the type of the entity. A range attribute normalizes the
15715       --  reference and obtains the correct types for the bounds.
15716
15717       --  This transformation is in the nature of an expansion, is only
15718       --  done if expansion is active. In particular, it is not done on
15719       --  formal generic types,  because we need to retain the name of the
15720       --  original index for instantiation purposes.
15721
15722       else
15723          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
15724             Error_Msg_N ("invalid subtype mark in discrete range ", I);
15725             Set_Etype (I, Any_Integer);
15726             return;
15727
15728          else
15729             --  The type mark may be that of an incomplete type. It is only
15730             --  now that we can get the full view, previous analysis does
15731             --  not look specifically for a type mark.
15732
15733             Set_Entity (I, Get_Full_View (Entity (I)));
15734             Set_Etype  (I, Entity (I));
15735             Def_Id := Entity (I);
15736
15737             if not Is_Discrete_Type (Def_Id) then
15738                Error_Msg_N ("discrete type required for index", I);
15739                Set_Etype (I, Any_Type);
15740                return;
15741             end if;
15742          end if;
15743
15744          if Expander_Active then
15745             Rewrite (I,
15746               Make_Attribute_Reference (Sloc (I),
15747                 Attribute_Name => Name_Range,
15748                 Prefix         => Relocate_Node (I)));
15749
15750             --  The original was a subtype mark that does not freeze. This
15751             --  means that the rewritten version must not freeze either.
15752
15753             Set_Must_Not_Freeze (I);
15754             Set_Must_Not_Freeze (Prefix (I));
15755
15756             --  Is order critical??? if so, document why, if not
15757             --  use Analyze_And_Resolve
15758
15759             Analyze_And_Resolve (I);
15760             T := Etype (I);
15761             R := I;
15762
15763          --  If expander is inactive, type is legal, nothing else to construct
15764
15765          else
15766             return;
15767          end if;
15768       end if;
15769
15770       if not Is_Discrete_Type (T) then
15771          Error_Msg_N ("discrete type required for range", I);
15772          Set_Etype (I, Any_Type);
15773          return;
15774
15775       elsif T = Any_Type then
15776          Set_Etype (I, Any_Type);
15777          return;
15778       end if;
15779
15780       --  We will now create the appropriate Itype to describe the range, but
15781       --  first a check. If we originally had a subtype, then we just label
15782       --  the range with this subtype. Not only is there no need to construct
15783       --  a new subtype, but it is wrong to do so for two reasons:
15784
15785       --    1. A legality concern, if we have a subtype, it must not freeze,
15786       --       and the Itype would cause freezing incorrectly
15787
15788       --    2. An efficiency concern, if we created an Itype, it would not be
15789       --       recognized as the same type for the purposes of eliminating
15790       --       checks in some circumstances.
15791
15792       --  We signal this case by setting the subtype entity in Def_Id
15793
15794       if No (Def_Id) then
15795          Def_Id :=
15796            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
15797          Set_Etype (Def_Id, Base_Type (T));
15798
15799          if Is_Signed_Integer_Type (T) then
15800             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
15801
15802          elsif Is_Modular_Integer_Type (T) then
15803             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
15804
15805          else
15806             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
15807             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
15808             Set_First_Literal     (Def_Id, First_Literal (T));
15809          end if;
15810
15811          Set_Size_Info      (Def_Id,                  (T));
15812          Set_RM_Size        (Def_Id, RM_Size          (T));
15813          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
15814
15815          Set_Scalar_Range   (Def_Id, R);
15816          Conditional_Delay  (Def_Id, T);
15817
15818          --  In the subtype indication case, if the immediate parent of the
15819          --  new subtype is non-static, then the subtype we create is non-
15820          --  static, even if its bounds are static.
15821
15822          if Nkind (I) = N_Subtype_Indication
15823            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
15824          then
15825             Set_Is_Non_Static_Subtype (Def_Id);
15826          end if;
15827       end if;
15828
15829       --  Final step is to label the index with this constructed type
15830
15831       Set_Etype (I, Def_Id);
15832    end Make_Index;
15833
15834    ------------------------------
15835    -- Modular_Type_Declaration --
15836    ------------------------------
15837
15838    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
15839       Mod_Expr : constant Node_Id := Expression (Def);
15840       M_Val    : Uint;
15841
15842       procedure Set_Modular_Size (Bits : Int);
15843       --  Sets RM_Size to Bits, and Esize to normal word size above this
15844
15845       ----------------------
15846       -- Set_Modular_Size --
15847       ----------------------
15848
15849       procedure Set_Modular_Size (Bits : Int) is
15850       begin
15851          Set_RM_Size (T, UI_From_Int (Bits));
15852
15853          if Bits <= 8 then
15854             Init_Esize (T, 8);
15855
15856          elsif Bits <= 16 then
15857             Init_Esize (T, 16);
15858
15859          elsif Bits <= 32 then
15860             Init_Esize (T, 32);
15861
15862          else
15863             Init_Esize (T, System_Max_Binary_Modulus_Power);
15864          end if;
15865
15866          if not Non_Binary_Modulus (T)
15867            and then Esize (T) = RM_Size (T)
15868          then
15869             Set_Is_Known_Valid (T);
15870          end if;
15871       end Set_Modular_Size;
15872
15873    --  Start of processing for Modular_Type_Declaration
15874
15875    begin
15876       Analyze_And_Resolve (Mod_Expr, Any_Integer);
15877       Set_Etype (T, T);
15878       Set_Ekind (T, E_Modular_Integer_Type);
15879       Init_Alignment (T);
15880       Set_Is_Constrained (T);
15881
15882       if not Is_OK_Static_Expression (Mod_Expr) then
15883          Flag_Non_Static_Expr
15884            ("non-static expression used for modular type bound!", Mod_Expr);
15885          M_Val := 2 ** System_Max_Binary_Modulus_Power;
15886       else
15887          M_Val := Expr_Value (Mod_Expr);
15888       end if;
15889
15890       if M_Val < 1 then
15891          Error_Msg_N ("modulus value must be positive", Mod_Expr);
15892          M_Val := 2 ** System_Max_Binary_Modulus_Power;
15893       end if;
15894
15895       Set_Modulus (T, M_Val);
15896
15897       --   Create bounds for the modular type based on the modulus given in
15898       --   the type declaration and then analyze and resolve those bounds.
15899
15900       Set_Scalar_Range (T,
15901         Make_Range (Sloc (Mod_Expr),
15902           Low_Bound  =>
15903             Make_Integer_Literal (Sloc (Mod_Expr), 0),
15904           High_Bound =>
15905             Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
15906
15907       --  Properly analyze the literals for the range. We do this manually
15908       --  because we can't go calling Resolve, since we are resolving these
15909       --  bounds with the type, and this type is certainly not complete yet!
15910
15911       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
15912       Set_Etype (High_Bound (Scalar_Range (T)), T);
15913       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
15914       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
15915
15916       --  Loop through powers of two to find number of bits required
15917
15918       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
15919
15920          --  Binary case
15921
15922          if M_Val = 2 ** Bits then
15923             Set_Modular_Size (Bits);
15924             return;
15925
15926          --  Non-binary case
15927
15928          elsif M_Val < 2 ** Bits then
15929             Set_Non_Binary_Modulus (T);
15930
15931             if Bits > System_Max_Nonbinary_Modulus_Power then
15932                Error_Msg_Uint_1 :=
15933                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
15934                Error_Msg_F
15935                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
15936                Set_Modular_Size (System_Max_Binary_Modulus_Power);
15937                return;
15938
15939             else
15940                --  In the non-binary case, set size as per RM 13.3(55)
15941
15942                Set_Modular_Size (Bits);
15943                return;
15944             end if;
15945          end if;
15946
15947       end loop;
15948
15949       --  If we fall through, then the size exceed System.Max_Binary_Modulus
15950       --  so we just signal an error and set the maximum size.
15951
15952       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
15953       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
15954
15955       Set_Modular_Size (System_Max_Binary_Modulus_Power);
15956       Init_Alignment (T);
15957
15958    end Modular_Type_Declaration;
15959
15960    --------------------------
15961    -- New_Concatenation_Op --
15962    --------------------------
15963
15964    procedure New_Concatenation_Op (Typ : Entity_Id) is
15965       Loc : constant Source_Ptr := Sloc (Typ);
15966       Op  : Entity_Id;
15967
15968       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
15969       --  Create abbreviated declaration for the formal of a predefined
15970       --  Operator 'Op' of type 'Typ'
15971
15972       --------------------
15973       -- Make_Op_Formal --
15974       --------------------
15975
15976       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
15977          Formal : Entity_Id;
15978       begin
15979          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
15980          Set_Etype (Formal, Typ);
15981          Set_Mechanism (Formal, Default_Mechanism);
15982          return Formal;
15983       end Make_Op_Formal;
15984
15985    --  Start of processing for New_Concatenation_Op
15986
15987    begin
15988       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
15989
15990       Set_Ekind                   (Op, E_Operator);
15991       Set_Scope                   (Op, Current_Scope);
15992       Set_Etype                   (Op, Typ);
15993       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
15994       Set_Is_Immediately_Visible  (Op);
15995       Set_Is_Intrinsic_Subprogram (Op);
15996       Set_Has_Completion          (Op);
15997       Append_Entity               (Op, Current_Scope);
15998
15999       Set_Name_Entity_Id (Name_Op_Concat, Op);
16000
16001       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16002       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16003    end New_Concatenation_Op;
16004
16005    -------------------------
16006    -- OK_For_Limited_Init --
16007    -------------------------
16008
16009    --  ???Check all calls of this, and compare the conditions under which it's
16010    --  called.
16011
16012    function OK_For_Limited_Init
16013      (Typ : Entity_Id;
16014       Exp : Node_Id) return Boolean
16015    is
16016    begin
16017       return Is_CPP_Constructor_Call (Exp)
16018         or else (Ada_Version >= Ada_2005
16019                   and then not Debug_Flag_Dot_L
16020                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
16021    end OK_For_Limited_Init;
16022
16023    -------------------------------
16024    -- OK_For_Limited_Init_In_05 --
16025    -------------------------------
16026
16027    function OK_For_Limited_Init_In_05
16028      (Typ : Entity_Id;
16029       Exp : Node_Id) return Boolean
16030    is
16031    begin
16032       --  An object of a limited interface type can be initialized with any
16033       --  expression of a nonlimited descendant type.
16034
16035       if Is_Class_Wide_Type (Typ)
16036         and then Is_Limited_Interface (Typ)
16037         and then not Is_Limited_Type (Etype (Exp))
16038       then
16039          return True;
16040       end if;
16041
16042       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
16043       --  case of limited aggregates (including extension aggregates), and
16044       --  function calls. The function call may have been given in prefixed
16045       --  notation, in which case the original node is an indexed component.
16046       --  If the function is parameterless, the original node was an explicit
16047       --  dereference.
16048
16049       case Nkind (Original_Node (Exp)) is
16050          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
16051             return True;
16052
16053          when N_Qualified_Expression =>
16054             return
16055               OK_For_Limited_Init_In_05
16056                 (Typ, Expression (Original_Node (Exp)));
16057
16058          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
16059          --  with a function call, the expander has rewritten the call into an
16060          --  N_Type_Conversion node to force displacement of the pointer to
16061          --  reference the component containing the secondary dispatch table.
16062          --  Otherwise a type conversion is not a legal context.
16063          --  A return statement for a build-in-place function returning a
16064          --  synchronized type also introduces an unchecked conversion.
16065
16066          when N_Type_Conversion           |
16067               N_Unchecked_Type_Conversion =>
16068             return not Comes_From_Source (Exp)
16069               and then
16070                 OK_For_Limited_Init_In_05
16071                   (Typ, Expression (Original_Node (Exp)));
16072
16073          when N_Indexed_Component     |
16074               N_Selected_Component    |
16075               N_Explicit_Dereference  =>
16076             return Nkind (Exp) = N_Function_Call;
16077
16078          --  A use of 'Input is a function call, hence allowed. Normally the
16079          --  attribute will be changed to a call, but the attribute by itself
16080          --  can occur with -gnatc.
16081
16082          when N_Attribute_Reference =>
16083             return Attribute_Name (Original_Node (Exp)) = Name_Input;
16084
16085          when others =>
16086             return False;
16087       end case;
16088    end OK_For_Limited_Init_In_05;
16089
16090    -------------------------------------------
16091    -- Ordinary_Fixed_Point_Type_Declaration --
16092    -------------------------------------------
16093
16094    procedure Ordinary_Fixed_Point_Type_Declaration
16095      (T   : Entity_Id;
16096       Def : Node_Id)
16097    is
16098       Loc           : constant Source_Ptr := Sloc (Def);
16099       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
16100       RRS           : constant Node_Id    := Real_Range_Specification (Def);
16101       Implicit_Base : Entity_Id;
16102       Delta_Val     : Ureal;
16103       Small_Val     : Ureal;
16104       Low_Val       : Ureal;
16105       High_Val      : Ureal;
16106
16107    begin
16108       Check_Restriction (No_Fixed_Point, Def);
16109
16110       --  Create implicit base type
16111
16112       Implicit_Base :=
16113         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
16114       Set_Etype (Implicit_Base, Implicit_Base);
16115
16116       --  Analyze and process delta expression
16117
16118       Analyze_And_Resolve (Delta_Expr, Any_Real);
16119
16120       Check_Delta_Expression (Delta_Expr);
16121       Delta_Val := Expr_Value_R (Delta_Expr);
16122
16123       Set_Delta_Value (Implicit_Base, Delta_Val);
16124
16125       --  Compute default small from given delta, which is the largest power
16126       --  of two that does not exceed the given delta value.
16127
16128       declare
16129          Tmp   : Ureal;
16130          Scale : Int;
16131
16132       begin
16133          Tmp := Ureal_1;
16134          Scale := 0;
16135
16136          if Delta_Val < Ureal_1 then
16137             while Delta_Val < Tmp loop
16138                Tmp := Tmp / Ureal_2;
16139                Scale := Scale + 1;
16140             end loop;
16141
16142          else
16143             loop
16144                Tmp := Tmp * Ureal_2;
16145                exit when Tmp > Delta_Val;
16146                Scale := Scale - 1;
16147             end loop;
16148          end if;
16149
16150          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
16151       end;
16152
16153       Set_Small_Value (Implicit_Base, Small_Val);
16154
16155       --  If no range was given, set a dummy range
16156
16157       if RRS <= Empty_Or_Error then
16158          Low_Val  := -Small_Val;
16159          High_Val := Small_Val;
16160
16161       --  Otherwise analyze and process given range
16162
16163       else
16164          declare
16165             Low  : constant Node_Id := Low_Bound  (RRS);
16166             High : constant Node_Id := High_Bound (RRS);
16167
16168          begin
16169             Analyze_And_Resolve (Low, Any_Real);
16170             Analyze_And_Resolve (High, Any_Real);
16171             Check_Real_Bound (Low);
16172             Check_Real_Bound (High);
16173
16174             --  Obtain and set the range
16175
16176             Low_Val  := Expr_Value_R (Low);
16177             High_Val := Expr_Value_R (High);
16178
16179             if Low_Val > High_Val then
16180                Error_Msg_NE ("?fixed point type& has null range", Def, T);
16181             end if;
16182          end;
16183       end if;
16184
16185       --  The range for both the implicit base and the declared first subtype
16186       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
16187       --  set a temporary range in place. Note that the bounds of the base
16188       --  type will be widened to be symmetrical and to fill the available
16189       --  bits when the type is frozen.
16190
16191       --  We could do this with all discrete types, and probably should, but
16192       --  we absolutely have to do it for fixed-point, since the end-points
16193       --  of the range and the size are determined by the small value, which
16194       --  could be reset before the freeze point.
16195
16196       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
16197       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
16198
16199       --  Complete definition of first subtype
16200
16201       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
16202       Set_Etype          (T, Implicit_Base);
16203       Init_Size_Align    (T);
16204       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
16205       Set_Small_Value    (T, Small_Val);
16206       Set_Delta_Value    (T, Delta_Val);
16207       Set_Is_Constrained (T);
16208
16209    end Ordinary_Fixed_Point_Type_Declaration;
16210
16211    ----------------------------------------
16212    -- Prepare_Private_Subtype_Completion --
16213    ----------------------------------------
16214
16215    procedure Prepare_Private_Subtype_Completion
16216      (Id          : Entity_Id;
16217       Related_Nod : Node_Id)
16218    is
16219       Id_B   : constant Entity_Id := Base_Type (Id);
16220       Full_B : constant Entity_Id := Full_View (Id_B);
16221       Full   : Entity_Id;
16222
16223    begin
16224       if Present (Full_B) then
16225
16226          --  The Base_Type is already completed, we can complete the subtype
16227          --  now. We have to create a new entity with the same name, Thus we
16228          --  can't use Create_Itype.
16229
16230          --  This is messy, should be fixed ???
16231
16232          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
16233          Set_Is_Itype (Full);
16234          Set_Associated_Node_For_Itype (Full, Related_Nod);
16235          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
16236       end if;
16237
16238       --  The parent subtype may be private, but the base might not, in some
16239       --  nested instances. In that case, the subtype does not need to be
16240       --  exchanged. It would still be nice to make private subtypes and their
16241       --  bases consistent at all times ???
16242
16243       if Is_Private_Type (Id_B) then
16244          Append_Elmt (Id, Private_Dependents (Id_B));
16245       end if;
16246
16247    end Prepare_Private_Subtype_Completion;
16248
16249    ---------------------------
16250    -- Process_Discriminants --
16251    ---------------------------
16252
16253    procedure Process_Discriminants
16254      (N    : Node_Id;
16255       Prev : Entity_Id := Empty)
16256    is
16257       Elist               : constant Elist_Id := New_Elmt_List;
16258       Id                  : Node_Id;
16259       Discr               : Node_Id;
16260       Discr_Number        : Uint;
16261       Discr_Type          : Entity_Id;
16262       Default_Present     : Boolean := False;
16263       Default_Not_Present : Boolean := False;
16264
16265    begin
16266       --  A composite type other than an array type can have discriminants.
16267       --  On entry, the current scope is the composite type.
16268
16269       --  The discriminants are initially entered into the scope of the type
16270       --  via Enter_Name with the default Ekind of E_Void to prevent premature
16271       --  use, as explained at the end of this procedure.
16272
16273       Discr := First (Discriminant_Specifications (N));
16274       while Present (Discr) loop
16275          Enter_Name (Defining_Identifier (Discr));
16276
16277          --  For navigation purposes we add a reference to the discriminant
16278          --  in the entity for the type. If the current declaration is a
16279          --  completion, place references on the partial view. Otherwise the
16280          --  type is the current scope.
16281
16282          if Present (Prev) then
16283
16284             --  The references go on the partial view, if present. If the
16285             --  partial view has discriminants, the references have been
16286             --  generated already.
16287
16288             if not Has_Discriminants (Prev) then
16289                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
16290             end if;
16291          else
16292             Generate_Reference
16293               (Current_Scope, Defining_Identifier (Discr), 'd');
16294          end if;
16295
16296          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
16297             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
16298
16299             --  Ada 2005 (AI-254)
16300
16301             if Present (Access_To_Subprogram_Definition
16302                          (Discriminant_Type (Discr)))
16303               and then Protected_Present (Access_To_Subprogram_Definition
16304                                            (Discriminant_Type (Discr)))
16305             then
16306                Discr_Type :=
16307                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
16308             end if;
16309
16310          else
16311             Find_Type (Discriminant_Type (Discr));
16312             Discr_Type := Etype (Discriminant_Type (Discr));
16313
16314             if Error_Posted (Discriminant_Type (Discr)) then
16315                Discr_Type := Any_Type;
16316             end if;
16317          end if;
16318
16319          if Is_Access_Type (Discr_Type) then
16320
16321             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
16322             --  record types
16323
16324             if Ada_Version < Ada_2005 then
16325                Check_Access_Discriminant_Requires_Limited
16326                  (Discr, Discriminant_Type (Discr));
16327             end if;
16328
16329             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
16330                Error_Msg_N
16331                  ("(Ada 83) access discriminant not allowed", Discr);
16332             end if;
16333
16334          elsif not Is_Discrete_Type (Discr_Type) then
16335             Error_Msg_N ("discriminants must have a discrete or access type",
16336               Discriminant_Type (Discr));
16337          end if;
16338
16339          Set_Etype (Defining_Identifier (Discr), Discr_Type);
16340
16341          --  If a discriminant specification includes the assignment compound
16342          --  delimiter followed by an expression, the expression is the default
16343          --  expression of the discriminant; the default expression must be of
16344          --  the type of the discriminant. (RM 3.7.1) Since this expression is
16345          --  a default expression, we do the special preanalysis, since this
16346          --  expression does not freeze (see "Handling of Default and Per-
16347          --  Object Expressions" in spec of package Sem).
16348
16349          if Present (Expression (Discr)) then
16350             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
16351
16352             if Nkind (N) = N_Formal_Type_Declaration then
16353                Error_Msg_N
16354                  ("discriminant defaults not allowed for formal type",
16355                   Expression (Discr));
16356
16357             --  Tagged types declarations cannot have defaulted discriminants,
16358             --  but an untagged private type with defaulted discriminants can
16359             --  have a tagged completion.
16360
16361             elsif Is_Tagged_Type (Current_Scope)
16362               and then Comes_From_Source (N)
16363             then
16364                Error_Msg_N
16365                  ("discriminants of tagged type cannot have defaults",
16366                   Expression (Discr));
16367
16368             else
16369                Default_Present := True;
16370                Append_Elmt (Expression (Discr), Elist);
16371
16372                --  Tag the defining identifiers for the discriminants with
16373                --  their corresponding default expressions from the tree.
16374
16375                Set_Discriminant_Default_Value
16376                  (Defining_Identifier (Discr), Expression (Discr));
16377             end if;
16378
16379          else
16380             Default_Not_Present := True;
16381          end if;
16382
16383          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
16384          --  Discr_Type but with the null-exclusion attribute
16385
16386          if Ada_Version >= Ada_2005 then
16387
16388             --  Ada 2005 (AI-231): Static checks
16389
16390             if Can_Never_Be_Null (Discr_Type) then
16391                Null_Exclusion_Static_Checks (Discr);
16392
16393             elsif Is_Access_Type (Discr_Type)
16394               and then Null_Exclusion_Present (Discr)
16395
16396                --  No need to check itypes because in their case this check
16397                --  was done at their point of creation
16398
16399               and then not Is_Itype (Discr_Type)
16400             then
16401                if Can_Never_Be_Null (Discr_Type) then
16402                   Error_Msg_NE
16403                     ("`NOT NULL` not allowed (& already excludes null)",
16404                      Discr,
16405                      Discr_Type);
16406                end if;
16407
16408                Set_Etype (Defining_Identifier (Discr),
16409                  Create_Null_Excluding_Itype
16410                    (T           => Discr_Type,
16411                     Related_Nod => Discr));
16412
16413             --  Check for improper null exclusion if the type is otherwise
16414             --  legal for a discriminant.
16415
16416             elsif Null_Exclusion_Present (Discr)
16417               and then Is_Discrete_Type (Discr_Type)
16418             then
16419                Error_Msg_N
16420                  ("null exclusion can only apply to an access type", Discr);
16421             end if;
16422
16423             --  Ada 2005 (AI-402): access discriminants of nonlimited types
16424             --  can't have defaults. Synchronized types, or types that are
16425             --  explicitly limited are fine, but special tests apply to derived
16426             --  types in generics: in a generic body we have to assume the
16427             --  worst, and therefore defaults are not allowed if the parent is
16428             --  a generic formal private type (see ACATS B370001).
16429
16430             if Is_Access_Type (Discr_Type) then
16431                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
16432                  or else not Default_Present
16433                  or else Is_Limited_Record (Current_Scope)
16434                  or else Is_Concurrent_Type (Current_Scope)
16435                  or else Is_Concurrent_Record_Type (Current_Scope)
16436                  or else Ekind (Current_Scope) = E_Limited_Private_Type
16437                then
16438                   if not Is_Derived_Type (Current_Scope)
16439                     or else not Is_Generic_Type (Etype (Current_Scope))
16440                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
16441                     or else Limited_Present
16442                               (Type_Definition (Parent (Current_Scope)))
16443                   then
16444                      null;
16445
16446                   else
16447                      Error_Msg_N ("access discriminants of nonlimited types",
16448                          Expression (Discr));
16449                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
16450                   end if;
16451
16452                elsif Present (Expression (Discr)) then
16453                   Error_Msg_N
16454                     ("(Ada 2005) access discriminants of nonlimited types",
16455                      Expression (Discr));
16456                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
16457                end if;
16458             end if;
16459          end if;
16460
16461          Next (Discr);
16462       end loop;
16463
16464       --  An element list consisting of the default expressions of the
16465       --  discriminants is constructed in the above loop and used to set
16466       --  the Discriminant_Constraint attribute for the type. If an object
16467       --  is declared of this (record or task) type without any explicit
16468       --  discriminant constraint given, this element list will form the
16469       --  actual parameters for the corresponding initialization procedure
16470       --  for the type.
16471
16472       Set_Discriminant_Constraint (Current_Scope, Elist);
16473       Set_Stored_Constraint (Current_Scope, No_Elist);
16474
16475       --  Default expressions must be provided either for all or for none
16476       --  of the discriminants of a discriminant part. (RM 3.7.1)
16477
16478       if Default_Present and then Default_Not_Present then
16479          Error_Msg_N
16480            ("incomplete specification of defaults for discriminants", N);
16481       end if;
16482
16483       --  The use of the name of a discriminant is not allowed in default
16484       --  expressions of a discriminant part if the specification of the
16485       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
16486
16487       --  To detect this, the discriminant names are entered initially with an
16488       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
16489       --  attempt to use a void entity (for example in an expression that is
16490       --  type-checked) produces the error message: premature usage. Now after
16491       --  completing the semantic analysis of the discriminant part, we can set
16492       --  the Ekind of all the discriminants appropriately.
16493
16494       Discr := First (Discriminant_Specifications (N));
16495       Discr_Number := Uint_1;
16496       while Present (Discr) loop
16497          Id := Defining_Identifier (Discr);
16498          Set_Ekind (Id, E_Discriminant);
16499          Init_Component_Location (Id);
16500          Init_Esize (Id);
16501          Set_Discriminant_Number (Id, Discr_Number);
16502
16503          --  Make sure this is always set, even in illegal programs
16504
16505          Set_Corresponding_Discriminant (Id, Empty);
16506
16507          --  Initialize the Original_Record_Component to the entity itself.
16508          --  Inherit_Components will propagate the right value to
16509          --  discriminants in derived record types.
16510
16511          Set_Original_Record_Component (Id, Id);
16512
16513          --  Create the discriminal for the discriminant
16514
16515          Build_Discriminal (Id);
16516
16517          Next (Discr);
16518          Discr_Number := Discr_Number + 1;
16519       end loop;
16520
16521       Set_Has_Discriminants (Current_Scope);
16522    end Process_Discriminants;
16523
16524    -----------------------
16525    -- Process_Full_View --
16526    -----------------------
16527
16528    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
16529       Priv_Parent : Entity_Id;
16530       Full_Parent : Entity_Id;
16531       Full_Indic  : Node_Id;
16532
16533       procedure Collect_Implemented_Interfaces
16534         (Typ    : Entity_Id;
16535          Ifaces : Elist_Id);
16536       --  Ada 2005: Gather all the interfaces that Typ directly or
16537       --  inherently implements. Duplicate entries are not added to
16538       --  the list Ifaces.
16539
16540       ------------------------------------
16541       -- Collect_Implemented_Interfaces --
16542       ------------------------------------
16543
16544       procedure Collect_Implemented_Interfaces
16545         (Typ    : Entity_Id;
16546          Ifaces : Elist_Id)
16547       is
16548          Iface      : Entity_Id;
16549          Iface_Elmt : Elmt_Id;
16550
16551       begin
16552          --  Abstract interfaces are only associated with tagged record types
16553
16554          if not Is_Tagged_Type (Typ)
16555            or else not Is_Record_Type (Typ)
16556          then
16557             return;
16558          end if;
16559
16560          --  Recursively climb to the ancestors
16561
16562          if Etype (Typ) /= Typ
16563
16564             --  Protect the frontend against wrong cyclic declarations like:
16565
16566             --     type B is new A with private;
16567             --     type C is new A with private;
16568             --  private
16569             --     type B is new C with null record;
16570             --     type C is new B with null record;
16571
16572            and then Etype (Typ) /= Priv_T
16573            and then Etype (Typ) /= Full_T
16574          then
16575             --  Keep separate the management of private type declarations
16576
16577             if Ekind (Typ) = E_Record_Type_With_Private then
16578
16579                --  Handle the following erronous case:
16580                --      type Private_Type is tagged private;
16581                --   private
16582                --      type Private_Type is new Type_Implementing_Iface;
16583
16584                if Present (Full_View (Typ))
16585                  and then Etype (Typ) /= Full_View (Typ)
16586                then
16587                   if Is_Interface (Etype (Typ)) then
16588                      Append_Unique_Elmt (Etype (Typ), Ifaces);
16589                   end if;
16590
16591                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16592                end if;
16593
16594             --  Non-private types
16595
16596             else
16597                if Is_Interface (Etype (Typ)) then
16598                   Append_Unique_Elmt (Etype (Typ), Ifaces);
16599                end if;
16600
16601                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16602             end if;
16603          end if;
16604
16605          --  Handle entities in the list of abstract interfaces
16606
16607          if Present (Interfaces (Typ)) then
16608             Iface_Elmt := First_Elmt (Interfaces (Typ));
16609             while Present (Iface_Elmt) loop
16610                Iface := Node (Iface_Elmt);
16611
16612                pragma Assert (Is_Interface (Iface));
16613
16614                if not Contain_Interface (Iface, Ifaces) then
16615                   Append_Elmt (Iface, Ifaces);
16616                   Collect_Implemented_Interfaces (Iface, Ifaces);
16617                end if;
16618
16619                Next_Elmt (Iface_Elmt);
16620             end loop;
16621          end if;
16622       end Collect_Implemented_Interfaces;
16623
16624    --  Start of processing for Process_Full_View
16625
16626    begin
16627       --  First some sanity checks that must be done after semantic
16628       --  decoration of the full view and thus cannot be placed with other
16629       --  similar checks in Find_Type_Name
16630
16631       if not Is_Limited_Type (Priv_T)
16632         and then (Is_Limited_Type (Full_T)
16633                    or else Is_Limited_Composite (Full_T))
16634       then
16635          Error_Msg_N
16636            ("completion of nonlimited type cannot be limited", Full_T);
16637          Explain_Limited_Type (Full_T, Full_T);
16638
16639       elsif Is_Abstract_Type (Full_T)
16640         and then not Is_Abstract_Type (Priv_T)
16641       then
16642          Error_Msg_N
16643            ("completion of nonabstract type cannot be abstract", Full_T);
16644
16645       elsif Is_Tagged_Type (Priv_T)
16646         and then Is_Limited_Type (Priv_T)
16647         and then not Is_Limited_Type (Full_T)
16648       then
16649          --  If pragma CPP_Class was applied to the private declaration
16650          --  propagate the limitedness to the full-view
16651
16652          if Is_CPP_Class (Priv_T) then
16653             Set_Is_Limited_Record (Full_T);
16654
16655          --  GNAT allow its own definition of Limited_Controlled to disobey
16656          --  this rule in order in ease the implementation. The next test is
16657          --  safe because Root_Controlled is defined in a private system child
16658
16659          elsif Etype (Full_T) = Full_View (RTE (RE_Root_Controlled)) then
16660             Set_Is_Limited_Composite (Full_T);
16661          else
16662             Error_Msg_N
16663               ("completion of limited tagged type must be limited", Full_T);
16664          end if;
16665
16666       elsif Is_Generic_Type (Priv_T) then
16667          Error_Msg_N ("generic type cannot have a completion", Full_T);
16668       end if;
16669
16670       --  Check that ancestor interfaces of private and full views are
16671       --  consistent. We omit this check for synchronized types because
16672       --  they are performed on the corresponding record type when frozen.
16673
16674       if Ada_Version >= Ada_2005
16675         and then Is_Tagged_Type (Priv_T)
16676         and then Is_Tagged_Type (Full_T)
16677         and then not Is_Concurrent_Type (Full_T)
16678       then
16679          declare
16680             Iface         : Entity_Id;
16681             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
16682             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
16683
16684          begin
16685             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
16686             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
16687
16688             --  Ada 2005 (AI-251): The partial view shall be a descendant of
16689             --  an interface type if and only if the full type is descendant
16690             --  of the interface type (AARM 7.3 (7.3/2).
16691
16692             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
16693
16694             if Present (Iface) then
16695                Error_Msg_NE
16696                  ("interface & not implemented by full type " &
16697                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
16698             end if;
16699
16700             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
16701
16702             if Present (Iface) then
16703                Error_Msg_NE
16704                  ("interface & not implemented by partial view " &
16705                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
16706             end if;
16707          end;
16708       end if;
16709
16710       if Is_Tagged_Type (Priv_T)
16711         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16712         and then Is_Derived_Type (Full_T)
16713       then
16714          Priv_Parent := Etype (Priv_T);
16715
16716          --  The full view of a private extension may have been transformed
16717          --  into an unconstrained derived type declaration and a subtype
16718          --  declaration (see build_derived_record_type for details).
16719
16720          if Nkind (N) = N_Subtype_Declaration then
16721             Full_Indic  := Subtype_Indication (N);
16722             Full_Parent := Etype (Base_Type (Full_T));
16723          else
16724             Full_Indic  := Subtype_Indication (Type_Definition (N));
16725             Full_Parent := Etype (Full_T);
16726          end if;
16727
16728          --  Check that the parent type of the full type is a descendant of
16729          --  the ancestor subtype given in the private extension. If either
16730          --  entity has an Etype equal to Any_Type then we had some previous
16731          --  error situation [7.3(8)].
16732
16733          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
16734             return;
16735
16736          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
16737          --  any order. Therefore we don't have to check that its parent must
16738          --  be a descendant of the parent of the private type declaration.
16739
16740          elsif Is_Interface (Priv_Parent)
16741            and then Is_Interface (Full_Parent)
16742          then
16743             null;
16744
16745          --  Ada 2005 (AI-251): If the parent of the private type declaration
16746          --  is an interface there is no need to check that it is an ancestor
16747          --  of the associated full type declaration. The required tests for
16748          --  this case are performed by Build_Derived_Record_Type.
16749
16750          elsif not Is_Interface (Base_Type (Priv_Parent))
16751            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
16752          then
16753             Error_Msg_N
16754               ("parent of full type must descend from parent"
16755                   & " of private extension", Full_Indic);
16756
16757          --  Check the rules of 7.3(10): if the private extension inherits
16758          --  known discriminants, then the full type must also inherit those
16759          --  discriminants from the same (ancestor) type, and the parent
16760          --  subtype of the full type must be constrained if and only if
16761          --  the ancestor subtype of the private extension is constrained.
16762
16763          elsif No (Discriminant_Specifications (Parent (Priv_T)))
16764            and then not Has_Unknown_Discriminants (Priv_T)
16765            and then Has_Discriminants (Base_Type (Priv_Parent))
16766          then
16767             declare
16768                Priv_Indic  : constant Node_Id :=
16769                                Subtype_Indication (Parent (Priv_T));
16770
16771                Priv_Constr : constant Boolean :=
16772                                Is_Constrained (Priv_Parent)
16773                                  or else
16774                                    Nkind (Priv_Indic) = N_Subtype_Indication
16775                                  or else Is_Constrained (Entity (Priv_Indic));
16776
16777                Full_Constr : constant Boolean :=
16778                                Is_Constrained (Full_Parent)
16779                                  or else
16780                                    Nkind (Full_Indic) = N_Subtype_Indication
16781                                  or else Is_Constrained (Entity (Full_Indic));
16782
16783                Priv_Discr : Entity_Id;
16784                Full_Discr : Entity_Id;
16785
16786             begin
16787                Priv_Discr := First_Discriminant (Priv_Parent);
16788                Full_Discr := First_Discriminant (Full_Parent);
16789                while Present (Priv_Discr) and then Present (Full_Discr) loop
16790                   if Original_Record_Component (Priv_Discr) =
16791                      Original_Record_Component (Full_Discr)
16792                     or else
16793                      Corresponding_Discriminant (Priv_Discr) =
16794                      Corresponding_Discriminant (Full_Discr)
16795                   then
16796                      null;
16797                   else
16798                      exit;
16799                   end if;
16800
16801                   Next_Discriminant (Priv_Discr);
16802                   Next_Discriminant (Full_Discr);
16803                end loop;
16804
16805                if Present (Priv_Discr) or else Present (Full_Discr) then
16806                   Error_Msg_N
16807                     ("full view must inherit discriminants of the parent type"
16808                      & " used in the private extension", Full_Indic);
16809
16810                elsif Priv_Constr and then not Full_Constr then
16811                   Error_Msg_N
16812                     ("parent subtype of full type must be constrained",
16813                      Full_Indic);
16814
16815                elsif Full_Constr and then not Priv_Constr then
16816                   Error_Msg_N
16817                     ("parent subtype of full type must be unconstrained",
16818                      Full_Indic);
16819                end if;
16820             end;
16821
16822          --  Check the rules of 7.3(12): if a partial view has neither known
16823          --  or unknown discriminants, then the full type declaration shall
16824          --  define a definite subtype.
16825
16826          elsif      not Has_Unknown_Discriminants (Priv_T)
16827            and then not Has_Discriminants (Priv_T)
16828            and then not Is_Constrained (Full_T)
16829          then
16830             Error_Msg_N
16831               ("full view must define a constrained type if partial view"
16832                 & " has no discriminants", Full_T);
16833          end if;
16834
16835          --  ??????? Do we implement the following properly ?????
16836          --  If the ancestor subtype of a private extension has constrained
16837          --  discriminants, then the parent subtype of the full view shall
16838          --  impose a statically matching constraint on those discriminants
16839          --  [7.3(13)].
16840
16841       else
16842          --  For untagged types, verify that a type without discriminants
16843          --  is not completed with an unconstrained type.
16844
16845          if not Is_Indefinite_Subtype (Priv_T)
16846            and then Is_Indefinite_Subtype (Full_T)
16847          then
16848             Error_Msg_N ("full view of type must be definite subtype", Full_T);
16849          end if;
16850       end if;
16851
16852       --  AI-419: verify that the use of "limited" is consistent
16853
16854       declare
16855          Orig_Decl : constant Node_Id := Original_Node (N);
16856
16857       begin
16858          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16859            and then not Limited_Present (Parent (Priv_T))
16860            and then not Synchronized_Present (Parent (Priv_T))
16861            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
16862            and then Nkind
16863              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
16864            and then Limited_Present (Type_Definition (Orig_Decl))
16865          then
16866             Error_Msg_N
16867               ("full view of non-limited extension cannot be limited", N);
16868          end if;
16869       end;
16870
16871       --  Ada 2005 (AI-443): A synchronized private extension must be
16872       --  completed by a task or protected type.
16873
16874       if Ada_Version >= Ada_2005
16875         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16876         and then Synchronized_Present (Parent (Priv_T))
16877         and then not Is_Concurrent_Type (Full_T)
16878       then
16879          Error_Msg_N ("full view of synchronized extension must " &
16880                       "be synchronized type", N);
16881       end if;
16882
16883       --  Ada 2005 AI-363: if the full view has discriminants with
16884       --  defaults, it is illegal to declare constrained access subtypes
16885       --  whose designated type is the current type. This allows objects
16886       --  of the type that are declared in the heap to be unconstrained.
16887
16888       if not Has_Unknown_Discriminants (Priv_T)
16889         and then not Has_Discriminants (Priv_T)
16890         and then Has_Discriminants (Full_T)
16891         and then
16892           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
16893       then
16894          Set_Has_Constrained_Partial_View (Full_T);
16895          Set_Has_Constrained_Partial_View (Priv_T);
16896       end if;
16897
16898       --  Create a full declaration for all its subtypes recorded in
16899       --  Private_Dependents and swap them similarly to the base type. These
16900       --  are subtypes that have been define before the full declaration of
16901       --  the private type. We also swap the entry in Private_Dependents list
16902       --  so we can properly restore the private view on exit from the scope.
16903
16904       declare
16905          Priv_Elmt : Elmt_Id;
16906          Priv      : Entity_Id;
16907          Full      : Entity_Id;
16908
16909       begin
16910          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
16911          while Present (Priv_Elmt) loop
16912             Priv := Node (Priv_Elmt);
16913
16914             if Ekind_In (Priv, E_Private_Subtype,
16915                                E_Limited_Private_Subtype,
16916                                E_Record_Subtype_With_Private)
16917             then
16918                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
16919                Set_Is_Itype (Full);
16920                Set_Parent (Full, Parent (Priv));
16921                Set_Associated_Node_For_Itype (Full, N);
16922
16923                --  Now we need to complete the private subtype, but since the
16924                --  base type has already been swapped, we must also swap the
16925                --  subtypes (and thus, reverse the arguments in the call to
16926                --  Complete_Private_Subtype).
16927
16928                Copy_And_Swap (Priv, Full);
16929                Complete_Private_Subtype (Full, Priv, Full_T, N);
16930                Replace_Elmt (Priv_Elmt, Full);
16931             end if;
16932
16933             Next_Elmt (Priv_Elmt);
16934          end loop;
16935       end;
16936
16937       --  If the private view was tagged, copy the new primitive operations
16938       --  from the private view to the full view.
16939
16940       if Is_Tagged_Type (Full_T) then
16941          declare
16942             Disp_Typ  : Entity_Id;
16943             Full_List : Elist_Id;
16944             Prim      : Entity_Id;
16945             Prim_Elmt : Elmt_Id;
16946             Priv_List : Elist_Id;
16947
16948             function Contains
16949               (E : Entity_Id;
16950                L : Elist_Id) return Boolean;
16951             --  Determine whether list L contains element E
16952
16953             --------------
16954             -- Contains --
16955             --------------
16956
16957             function Contains
16958               (E : Entity_Id;
16959                L : Elist_Id) return Boolean
16960             is
16961                List_Elmt : Elmt_Id;
16962
16963             begin
16964                List_Elmt := First_Elmt (L);
16965                while Present (List_Elmt) loop
16966                   if Node (List_Elmt) = E then
16967                      return True;
16968                   end if;
16969
16970                   Next_Elmt (List_Elmt);
16971                end loop;
16972
16973                return False;
16974             end Contains;
16975
16976          --  Start of processing
16977
16978          begin
16979             if Is_Tagged_Type (Priv_T) then
16980                Priv_List := Primitive_Operations (Priv_T);
16981                Prim_Elmt := First_Elmt (Priv_List);
16982
16983                --  In the case of a concurrent type completing a private tagged
16984                --  type, primitives may have been declared in between the two
16985                --  views. These subprograms need to be wrapped the same way
16986                --  entries and protected procedures are handled because they
16987                --  cannot be directly shared by the two views.
16988
16989                if Is_Concurrent_Type (Full_T) then
16990                   declare
16991                      Conc_Typ  : constant Entity_Id :=
16992                                    Corresponding_Record_Type (Full_T);
16993                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
16994                      Wrap_Spec : Node_Id;
16995
16996                   begin
16997                      while Present (Prim_Elmt) loop
16998                         Prim := Node (Prim_Elmt);
16999
17000                         if Comes_From_Source (Prim)
17001                           and then not Is_Abstract_Subprogram (Prim)
17002                         then
17003                            Wrap_Spec :=
17004                              Make_Subprogram_Declaration (Sloc (Prim),
17005                                Specification =>
17006                                  Build_Wrapper_Spec
17007                                    (Subp_Id => Prim,
17008                                     Obj_Typ => Conc_Typ,
17009                                     Formals =>
17010                                       Parameter_Specifications (
17011                                         Parent (Prim))));
17012
17013                            Insert_After (Curr_Nod, Wrap_Spec);
17014                            Curr_Nod := Wrap_Spec;
17015
17016                            Analyze (Wrap_Spec);
17017                         end if;
17018
17019                         Next_Elmt (Prim_Elmt);
17020                      end loop;
17021
17022                      return;
17023                   end;
17024
17025                --  For non-concurrent types, transfer explicit primitives, but
17026                --  omit those inherited from the parent of the private view
17027                --  since they will be re-inherited later on.
17028
17029                else
17030                   Full_List := Primitive_Operations (Full_T);
17031
17032                   while Present (Prim_Elmt) loop
17033                      Prim := Node (Prim_Elmt);
17034
17035                      if Comes_From_Source (Prim)
17036                        and then not Contains (Prim, Full_List)
17037                      then
17038                         Append_Elmt (Prim, Full_List);
17039                      end if;
17040
17041                      Next_Elmt (Prim_Elmt);
17042                   end loop;
17043                end if;
17044
17045             --  Untagged private view
17046
17047             else
17048                Full_List := Primitive_Operations (Full_T);
17049
17050                --  In this case the partial view is untagged, so here we locate
17051                --  all of the earlier primitives that need to be treated as
17052                --  dispatching (those that appear between the two views). Note
17053                --  that these additional operations must all be new operations
17054                --  (any earlier operations that override inherited operations
17055                --  of the full view will already have been inserted in the
17056                --  primitives list, marked by Check_Operation_From_Private_View
17057                --  as dispatching. Note that implicit "/=" operators are
17058                --  excluded from being added to the primitives list since they
17059                --  shouldn't be treated as dispatching (tagged "/=" is handled
17060                --  specially).
17061
17062                Prim := Next_Entity (Full_T);
17063                while Present (Prim) and then Prim /= Priv_T loop
17064                   if Ekind_In (Prim, E_Procedure, E_Function) then
17065                      Disp_Typ := Find_Dispatching_Type (Prim);
17066
17067                      if Disp_Typ = Full_T
17068                        and then (Chars (Prim) /= Name_Op_Ne
17069                                   or else Comes_From_Source (Prim))
17070                      then
17071                         Check_Controlling_Formals (Full_T, Prim);
17072
17073                         if not Is_Dispatching_Operation (Prim) then
17074                            Append_Elmt (Prim, Full_List);
17075                            Set_Is_Dispatching_Operation (Prim, True);
17076                            Set_DT_Position (Prim, No_Uint);
17077                         end if;
17078
17079                      elsif Is_Dispatching_Operation (Prim)
17080                        and then Disp_Typ  /= Full_T
17081                      then
17082
17083                         --  Verify that it is not otherwise controlled by a
17084                         --  formal or a return value of type T.
17085
17086                         Check_Controlling_Formals (Disp_Typ, Prim);
17087                      end if;
17088                   end if;
17089
17090                   Next_Entity (Prim);
17091                end loop;
17092             end if;
17093
17094             --  For the tagged case, the two views can share the same primitive
17095             --  operations list and the same class-wide type. Update attributes
17096             --  of the class-wide type which depend on the full declaration.
17097
17098             if Is_Tagged_Type (Priv_T) then
17099                Set_Direct_Primitive_Operations (Priv_T, Full_List);
17100                Set_Class_Wide_Type
17101                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
17102
17103                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
17104             end if;
17105          end;
17106       end if;
17107
17108       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
17109
17110       if Known_To_Have_Preelab_Init (Priv_T) then
17111
17112          --  Case where there is a pragma Preelaborable_Initialization. We
17113          --  always allow this in predefined units, which is a bit of a kludge,
17114          --  but it means we don't have to struggle to meet the requirements in
17115          --  the RM for having Preelaborable Initialization. Otherwise we
17116          --  require that the type meets the RM rules. But we can't check that
17117          --  yet, because of the rule about overriding Ininitialize, so we
17118          --  simply set a flag that will be checked at freeze time.
17119
17120          if not In_Predefined_Unit (Full_T) then
17121             Set_Must_Have_Preelab_Init (Full_T);
17122          end if;
17123       end if;
17124
17125       --  If pragma CPP_Class was applied to the private type declaration,
17126       --  propagate it now to the full type declaration.
17127
17128       if Is_CPP_Class (Priv_T) then
17129          Set_Is_CPP_Class (Full_T);
17130          Set_Convention   (Full_T, Convention_CPP);
17131       end if;
17132
17133       --  If the private view has user specified stream attributes, then so has
17134       --  the full view.
17135
17136       --  Why the test, how could these flags be already set in Full_T ???
17137
17138       if Has_Specified_Stream_Read (Priv_T) then
17139          Set_Has_Specified_Stream_Read (Full_T);
17140       end if;
17141
17142       if Has_Specified_Stream_Write (Priv_T) then
17143          Set_Has_Specified_Stream_Write (Full_T);
17144       end if;
17145
17146       if Has_Specified_Stream_Input (Priv_T) then
17147          Set_Has_Specified_Stream_Input (Full_T);
17148       end if;
17149
17150       if Has_Specified_Stream_Output (Priv_T) then
17151          Set_Has_Specified_Stream_Output (Full_T);
17152       end if;
17153
17154       --  Deal with invariants
17155
17156       if Has_Invariants (Full_T)
17157            or else
17158          Has_Invariants (Priv_T)
17159       then
17160          Set_Has_Invariants (Full_T);
17161          Set_Has_Invariants (Priv_T);
17162       end if;
17163
17164       if Has_Inheritable_Invariants (Full_T)
17165            or else
17166          Has_Inheritable_Invariants (Priv_T)
17167       then
17168          Set_Has_Inheritable_Invariants (Full_T);
17169          Set_Has_Inheritable_Invariants (Priv_T);
17170       end if;
17171
17172       --  This is where we build the invariant procedure if needed
17173
17174       if Has_Invariants (Priv_T) then
17175          declare
17176             PDecl : Entity_Id;
17177             PBody : Entity_Id;
17178             Packg : constant Node_Id := Declaration_Node (Scope (Priv_T));
17179
17180          begin
17181             Build_Invariant_Procedure (Full_T, PDecl, PBody);
17182
17183             --  Error defense, normally these should be set
17184
17185             if Present (PDecl) and then Present (PBody) then
17186
17187                --  Spec goes at the end of the public part of the package.
17188                --  That's behind us, so we have to manually analyze the
17189                --  inserted spec.
17190
17191                Append_To (Visible_Declarations (Packg), PDecl);
17192                Analyze (PDecl);
17193
17194                --  Body goes at the end of the private part of the package.
17195                --  That's ahead of us so it will get analyzed later on when
17196                --  we come to it.
17197
17198                Append_To (Private_Declarations (Packg), PBody);
17199
17200                --  Copy Invariant procedure to private declaration
17201
17202                Set_Invariant_Procedure (Priv_T, Invariant_Procedure (Full_T));
17203                Set_Has_Invariants (Priv_T);
17204             end if;
17205          end;
17206       end if;
17207
17208       --  Propagate predicates to full type
17209
17210       if Has_Predicates (Priv_T) then
17211          Set_Predicate_Function (Priv_T, Predicate_Function (Full_T));
17212          Set_Has_Predicates (Priv_T);
17213       end if;
17214    end Process_Full_View;
17215
17216    -----------------------------------
17217    -- Process_Incomplete_Dependents --
17218    -----------------------------------
17219
17220    procedure Process_Incomplete_Dependents
17221      (N      : Node_Id;
17222       Full_T : Entity_Id;
17223       Inc_T  : Entity_Id)
17224    is
17225       Inc_Elmt : Elmt_Id;
17226       Priv_Dep : Entity_Id;
17227       New_Subt : Entity_Id;
17228
17229       Disc_Constraint : Elist_Id;
17230
17231    begin
17232       if No (Private_Dependents (Inc_T)) then
17233          return;
17234       end if;
17235
17236       --  Itypes that may be generated by the completion of an incomplete
17237       --  subtype are not used by the back-end and not attached to the tree.
17238       --  They are created only for constraint-checking purposes.
17239
17240       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
17241       while Present (Inc_Elmt) loop
17242          Priv_Dep := Node (Inc_Elmt);
17243
17244          if Ekind (Priv_Dep) = E_Subprogram_Type then
17245
17246             --  An Access_To_Subprogram type may have a return type or a
17247             --  parameter type that is incomplete. Replace with the full view.
17248
17249             if Etype (Priv_Dep) = Inc_T then
17250                Set_Etype (Priv_Dep, Full_T);
17251             end if;
17252
17253             declare
17254                Formal : Entity_Id;
17255
17256             begin
17257                Formal := First_Formal (Priv_Dep);
17258                while Present (Formal) loop
17259                   if Etype (Formal) = Inc_T then
17260                      Set_Etype (Formal, Full_T);
17261                   end if;
17262
17263                   Next_Formal (Formal);
17264                end loop;
17265             end;
17266
17267          elsif Is_Overloadable (Priv_Dep) then
17268
17269             --  A protected operation is never dispatching: only its
17270             --  wrapper operation (which has convention Ada) is.
17271
17272             if Is_Tagged_Type (Full_T)
17273               and then Convention (Priv_Dep) /= Convention_Protected
17274             then
17275
17276                --  Subprogram has an access parameter whose designated type
17277                --  was incomplete. Reexamine declaration now, because it may
17278                --  be a primitive operation of the full type.
17279
17280                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
17281                Set_Is_Dispatching_Operation (Priv_Dep);
17282                Check_Controlling_Formals (Full_T, Priv_Dep);
17283             end if;
17284
17285          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
17286
17287             --  Can happen during processing of a body before the completion
17288             --  of a TA type. Ignore, because spec is also on dependent list.
17289
17290             return;
17291
17292          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
17293          --  corresponding subtype of the full view.
17294
17295          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
17296             Set_Subtype_Indication
17297               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
17298             Set_Etype (Priv_Dep, Full_T);
17299             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
17300             Set_Analyzed (Parent (Priv_Dep), False);
17301
17302             --  Reanalyze the declaration, suppressing the call to
17303             --  Enter_Name to avoid duplicate names.
17304
17305             Analyze_Subtype_Declaration
17306               (N    => Parent (Priv_Dep),
17307                Skip => True);
17308
17309          --  Dependent is a subtype
17310
17311          else
17312             --  We build a new subtype indication using the full view of the
17313             --  incomplete parent. The discriminant constraints have been
17314             --  elaborated already at the point of the subtype declaration.
17315
17316             New_Subt := Create_Itype (E_Void, N);
17317
17318             if Has_Discriminants (Full_T) then
17319                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
17320             else
17321                Disc_Constraint := No_Elist;
17322             end if;
17323
17324             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
17325             Set_Full_View (Priv_Dep, New_Subt);
17326          end if;
17327
17328          Next_Elmt (Inc_Elmt);
17329       end loop;
17330    end Process_Incomplete_Dependents;
17331
17332    --------------------------------
17333    -- Process_Range_Expr_In_Decl --
17334    --------------------------------
17335
17336    procedure Process_Range_Expr_In_Decl
17337      (R           : Node_Id;
17338       T           : Entity_Id;
17339       Check_List  : List_Id := Empty_List;
17340       R_Check_Off : Boolean := False)
17341    is
17342       Lo, Hi    : Node_Id;
17343       R_Checks  : Check_Result;
17344       Type_Decl : Node_Id;
17345       Def_Id    : Entity_Id;
17346
17347    begin
17348       Analyze_And_Resolve (R, Base_Type (T));
17349
17350       if Nkind (R) = N_Range then
17351          Lo := Low_Bound (R);
17352          Hi := High_Bound (R);
17353
17354          --  We need to ensure validity of the bounds here, because if we
17355          --  go ahead and do the expansion, then the expanded code will get
17356          --  analyzed with range checks suppressed and we miss the check.
17357
17358          Validity_Check_Range (R);
17359
17360          --  If there were errors in the declaration, try and patch up some
17361          --  common mistakes in the bounds. The cases handled are literals
17362          --  which are Integer where the expected type is Real and vice versa.
17363          --  These corrections allow the compilation process to proceed further
17364          --  along since some basic assumptions of the format of the bounds
17365          --  are guaranteed.
17366
17367          if Etype (R) = Any_Type then
17368
17369             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
17370                Rewrite (Lo,
17371                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
17372
17373             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
17374                Rewrite (Hi,
17375                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
17376
17377             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
17378                Rewrite (Lo,
17379                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
17380
17381             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
17382                Rewrite (Hi,
17383                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
17384             end if;
17385
17386             Set_Etype (Lo, T);
17387             Set_Etype (Hi, T);
17388          end if;
17389
17390          --  If the bounds of the range have been mistakenly given as string
17391          --  literals (perhaps in place of character literals), then an error
17392          --  has already been reported, but we rewrite the string literal as a
17393          --  bound of the range's type to avoid blowups in later processing
17394          --  that looks at static values.
17395
17396          if Nkind (Lo) = N_String_Literal then
17397             Rewrite (Lo,
17398               Make_Attribute_Reference (Sloc (Lo),
17399                 Attribute_Name => Name_First,
17400                 Prefix => New_Reference_To (T, Sloc (Lo))));
17401             Analyze_And_Resolve (Lo);
17402          end if;
17403
17404          if Nkind (Hi) = N_String_Literal then
17405             Rewrite (Hi,
17406               Make_Attribute_Reference (Sloc (Hi),
17407                 Attribute_Name => Name_First,
17408                 Prefix => New_Reference_To (T, Sloc (Hi))));
17409             Analyze_And_Resolve (Hi);
17410          end if;
17411
17412          --  If bounds aren't scalar at this point then exit, avoiding
17413          --  problems with further processing of the range in this procedure.
17414
17415          if not Is_Scalar_Type (Etype (Lo)) then
17416             return;
17417          end if;
17418
17419          --  Resolve (actually Sem_Eval) has checked that the bounds are in
17420          --  then range of the base type. Here we check whether the bounds
17421          --  are in the range of the subtype itself. Note that if the bounds
17422          --  represent the null range the Constraint_Error exception should
17423          --  not be raised.
17424
17425          --  ??? The following code should be cleaned up as follows
17426
17427          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
17428          --     is done in the call to Range_Check (R, T); below
17429
17430          --  2. The use of R_Check_Off should be investigated and possibly
17431          --     removed, this would clean up things a bit.
17432
17433          if Is_Null_Range (Lo, Hi) then
17434             null;
17435
17436          else
17437             --  Capture values of bounds and generate temporaries for them
17438             --  if needed, before applying checks, since checks may cause
17439             --  duplication of the expression without forcing evaluation.
17440
17441             if Expander_Active then
17442                Force_Evaluation (Lo);
17443                Force_Evaluation (Hi);
17444             end if;
17445
17446             --  We use a flag here instead of suppressing checks on the
17447             --  type because the type we check against isn't necessarily
17448             --  the place where we put the check.
17449
17450             if not R_Check_Off then
17451                R_Checks := Get_Range_Checks (R, T);
17452
17453                --  Look up tree to find an appropriate insertion point.
17454                --  This seems really junk code, and very brittle, couldn't
17455                --  we just use an insert actions call of some kind ???
17456
17457                Type_Decl := Parent (R);
17458                while Present (Type_Decl) and then not
17459                  (Nkind_In (Type_Decl, N_Full_Type_Declaration,
17460                                        N_Subtype_Declaration,
17461                                        N_Loop_Statement,
17462                                        N_Task_Type_Declaration)
17463                     or else
17464                   Nkind_In (Type_Decl, N_Single_Task_Declaration,
17465                                        N_Protected_Type_Declaration,
17466                                        N_Single_Protected_Declaration))
17467                loop
17468                   Type_Decl := Parent (Type_Decl);
17469                end loop;
17470
17471                --  Why would Type_Decl not be present???  Without this test,
17472                --  short regression tests fail.
17473
17474                if Present (Type_Decl) then
17475
17476                   --  Case of loop statement (more comments ???)
17477
17478                   if Nkind (Type_Decl) = N_Loop_Statement then
17479                      declare
17480                         Indic : Node_Id;
17481
17482                      begin
17483                         Indic := Parent (R);
17484                         while Present (Indic)
17485                           and then Nkind (Indic) /= N_Subtype_Indication
17486                         loop
17487                            Indic := Parent (Indic);
17488                         end loop;
17489
17490                         if Present (Indic) then
17491                            Def_Id := Etype (Subtype_Mark (Indic));
17492
17493                            Insert_Range_Checks
17494                              (R_Checks,
17495                               Type_Decl,
17496                               Def_Id,
17497                               Sloc (Type_Decl),
17498                               R,
17499                               Do_Before => True);
17500                         end if;
17501                      end;
17502
17503                   --  All other cases (more comments ???)
17504
17505                   else
17506                      Def_Id := Defining_Identifier (Type_Decl);
17507
17508                      if (Ekind (Def_Id) = E_Record_Type
17509                           and then Depends_On_Discriminant (R))
17510                        or else
17511                         (Ekind (Def_Id) = E_Protected_Type
17512                           and then Has_Discriminants (Def_Id))
17513                      then
17514                         Append_Range_Checks
17515                           (R_Checks, Check_List, Def_Id, Sloc (Type_Decl), R);
17516
17517                      else
17518                         Insert_Range_Checks
17519                           (R_Checks, Type_Decl, Def_Id, Sloc (Type_Decl), R);
17520
17521                      end if;
17522                   end if;
17523                end if;
17524             end if;
17525          end if;
17526
17527       elsif Expander_Active then
17528          Get_Index_Bounds (R, Lo, Hi);
17529          Force_Evaluation (Lo);
17530          Force_Evaluation (Hi);
17531       end if;
17532    end Process_Range_Expr_In_Decl;
17533
17534    --------------------------------------
17535    -- Process_Real_Range_Specification --
17536    --------------------------------------
17537
17538    procedure Process_Real_Range_Specification (Def : Node_Id) is
17539       Spec : constant Node_Id := Real_Range_Specification (Def);
17540       Lo   : Node_Id;
17541       Hi   : Node_Id;
17542       Err  : Boolean := False;
17543
17544       procedure Analyze_Bound (N : Node_Id);
17545       --  Analyze and check one bound
17546
17547       -------------------
17548       -- Analyze_Bound --
17549       -------------------
17550
17551       procedure Analyze_Bound (N : Node_Id) is
17552       begin
17553          Analyze_And_Resolve (N, Any_Real);
17554
17555          if not Is_OK_Static_Expression (N) then
17556             Flag_Non_Static_Expr
17557               ("bound in real type definition is not static!", N);
17558             Err := True;
17559          end if;
17560       end Analyze_Bound;
17561
17562    --  Start of processing for Process_Real_Range_Specification
17563
17564    begin
17565       if Present (Spec) then
17566          Lo := Low_Bound (Spec);
17567          Hi := High_Bound (Spec);
17568          Analyze_Bound (Lo);
17569          Analyze_Bound (Hi);
17570
17571          --  If error, clear away junk range specification
17572
17573          if Err then
17574             Set_Real_Range_Specification (Def, Empty);
17575          end if;
17576       end if;
17577    end Process_Real_Range_Specification;
17578
17579    ---------------------
17580    -- Process_Subtype --
17581    ---------------------
17582
17583    function Process_Subtype
17584      (S           : Node_Id;
17585       Related_Nod : Node_Id;
17586       Related_Id  : Entity_Id := Empty;
17587       Suffix      : Character := ' ') return Entity_Id
17588    is
17589       P               : Node_Id;
17590       Def_Id          : Entity_Id;
17591       Error_Node      : Node_Id;
17592       Full_View_Id    : Entity_Id;
17593       Subtype_Mark_Id : Entity_Id;
17594
17595       May_Have_Null_Exclusion : Boolean;
17596
17597       procedure Check_Incomplete (T : Entity_Id);
17598       --  Called to verify that an incomplete type is not used prematurely
17599
17600       ----------------------
17601       -- Check_Incomplete --
17602       ----------------------
17603
17604       procedure Check_Incomplete (T : Entity_Id) is
17605       begin
17606          --  Ada 2005 (AI-412): Incomplete subtypes are legal
17607
17608          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
17609            and then
17610              not (Ada_Version >= Ada_2005
17611                     and then
17612                        (Nkind (Parent (T)) = N_Subtype_Declaration
17613                           or else
17614                             (Nkind (Parent (T)) = N_Subtype_Indication
17615                                and then Nkind (Parent (Parent (T))) =
17616                                           N_Subtype_Declaration)))
17617          then
17618             Error_Msg_N ("invalid use of type before its full declaration", T);
17619          end if;
17620       end Check_Incomplete;
17621
17622    --  Start of processing for Process_Subtype
17623
17624    begin
17625       --  Case of no constraints present
17626
17627       if Nkind (S) /= N_Subtype_Indication then
17628          Find_Type (S);
17629          Check_Incomplete (S);
17630          P := Parent (S);
17631
17632          --  Ada 2005 (AI-231): Static check
17633
17634          if Ada_Version >= Ada_2005
17635            and then Present (P)
17636            and then Null_Exclusion_Present (P)
17637            and then Nkind (P) /= N_Access_To_Object_Definition
17638            and then not Is_Access_Type (Entity (S))
17639          then
17640             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
17641          end if;
17642
17643          --  The following is ugly, can't we have a range or even a flag???
17644
17645          May_Have_Null_Exclusion :=
17646            Nkind_In (P, N_Access_Definition,
17647                         N_Access_Function_Definition,
17648                         N_Access_Procedure_Definition,
17649                         N_Access_To_Object_Definition,
17650                         N_Allocator,
17651                         N_Component_Definition)
17652              or else
17653            Nkind_In (P, N_Derived_Type_Definition,
17654                         N_Discriminant_Specification,
17655                         N_Formal_Object_Declaration,
17656                         N_Object_Declaration,
17657                         N_Object_Renaming_Declaration,
17658                         N_Parameter_Specification,
17659                         N_Subtype_Declaration);
17660
17661          --  Create an Itype that is a duplicate of Entity (S) but with the
17662          --  null-exclusion attribute.
17663
17664          if May_Have_Null_Exclusion
17665            and then Is_Access_Type (Entity (S))
17666            and then Null_Exclusion_Present (P)
17667
17668             --  No need to check the case of an access to object definition.
17669             --  It is correct to define double not-null pointers.
17670
17671             --  Example:
17672             --     type Not_Null_Int_Ptr is not null access Integer;
17673             --     type Acc is not null access Not_Null_Int_Ptr;
17674
17675            and then Nkind (P) /= N_Access_To_Object_Definition
17676          then
17677             if Can_Never_Be_Null (Entity (S)) then
17678                case Nkind (Related_Nod) is
17679                   when N_Full_Type_Declaration =>
17680                      if Nkind (Type_Definition (Related_Nod))
17681                        in N_Array_Type_Definition
17682                      then
17683                         Error_Node :=
17684                           Subtype_Indication
17685                             (Component_Definition
17686                              (Type_Definition (Related_Nod)));
17687                      else
17688                         Error_Node :=
17689                           Subtype_Indication (Type_Definition (Related_Nod));
17690                      end if;
17691
17692                   when N_Subtype_Declaration =>
17693                      Error_Node := Subtype_Indication (Related_Nod);
17694
17695                   when N_Object_Declaration =>
17696                      Error_Node := Object_Definition (Related_Nod);
17697
17698                   when N_Component_Declaration =>
17699                      Error_Node :=
17700                        Subtype_Indication (Component_Definition (Related_Nod));
17701
17702                   when N_Allocator =>
17703                      Error_Node := Expression (Related_Nod);
17704
17705                   when others =>
17706                      pragma Assert (False);
17707                      Error_Node := Related_Nod;
17708                end case;
17709
17710                Error_Msg_NE
17711                  ("`NOT NULL` not allowed (& already excludes null)",
17712                   Error_Node,
17713                   Entity (S));
17714             end if;
17715
17716             Set_Etype  (S,
17717               Create_Null_Excluding_Itype
17718                 (T           => Entity (S),
17719                  Related_Nod => P));
17720             Set_Entity (S, Etype (S));
17721          end if;
17722
17723          return Entity (S);
17724
17725       --  Case of constraint present, so that we have an N_Subtype_Indication
17726       --  node (this node is created only if constraints are present).
17727
17728       else
17729          Find_Type (Subtype_Mark (S));
17730
17731          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
17732            and then not
17733             (Nkind (Parent (S)) = N_Subtype_Declaration
17734               and then Is_Itype (Defining_Identifier (Parent (S))))
17735          then
17736             Check_Incomplete (Subtype_Mark (S));
17737          end if;
17738
17739          P := Parent (S);
17740          Subtype_Mark_Id := Entity (Subtype_Mark (S));
17741
17742          --  Explicit subtype declaration case
17743
17744          if Nkind (P) = N_Subtype_Declaration then
17745             Def_Id := Defining_Identifier (P);
17746
17747          --  Explicit derived type definition case
17748
17749          elsif Nkind (P) = N_Derived_Type_Definition then
17750             Def_Id := Defining_Identifier (Parent (P));
17751
17752          --  Implicit case, the Def_Id must be created as an implicit type.
17753          --  The one exception arises in the case of concurrent types, array
17754          --  and access types, where other subsidiary implicit types may be
17755          --  created and must appear before the main implicit type. In these
17756          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
17757          --  has not yet been called to create Def_Id.
17758
17759          else
17760             if Is_Array_Type (Subtype_Mark_Id)
17761               or else Is_Concurrent_Type (Subtype_Mark_Id)
17762               or else Is_Access_Type (Subtype_Mark_Id)
17763             then
17764                Def_Id := Empty;
17765
17766             --  For the other cases, we create a new unattached Itype,
17767             --  and set the indication to ensure it gets attached later.
17768
17769             else
17770                Def_Id :=
17771                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
17772             end if;
17773          end if;
17774
17775          --  If the kind of constraint is invalid for this kind of type,
17776          --  then give an error, and then pretend no constraint was given.
17777
17778          if not Is_Valid_Constraint_Kind
17779                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
17780          then
17781             Error_Msg_N
17782               ("incorrect constraint for this kind of type", Constraint (S));
17783
17784             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
17785
17786             --  Set Ekind of orphan itype, to prevent cascaded errors
17787
17788             if Present (Def_Id) then
17789                Set_Ekind (Def_Id, Ekind (Any_Type));
17790             end if;
17791
17792             --  Make recursive call, having got rid of the bogus constraint
17793
17794             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
17795          end if;
17796
17797          --  Remaining processing depends on type
17798
17799          case Ekind (Subtype_Mark_Id) is
17800             when Access_Kind =>
17801                Constrain_Access (Def_Id, S, Related_Nod);
17802
17803                if Expander_Active
17804                  and then  Is_Itype (Designated_Type (Def_Id))
17805                  and then Nkind (Related_Nod) = N_Subtype_Declaration
17806                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
17807                then
17808                   Build_Itype_Reference
17809                     (Designated_Type (Def_Id), Related_Nod);
17810                end if;
17811
17812             when Array_Kind =>
17813                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
17814
17815             when Decimal_Fixed_Point_Kind =>
17816                Constrain_Decimal (Def_Id, S);
17817
17818             when Enumeration_Kind =>
17819                Constrain_Enumeration (Def_Id, S);
17820
17821             when Ordinary_Fixed_Point_Kind =>
17822                Constrain_Ordinary_Fixed (Def_Id, S);
17823
17824             when Float_Kind =>
17825                Constrain_Float (Def_Id, S);
17826
17827             when Integer_Kind =>
17828                Constrain_Integer (Def_Id, S);
17829
17830             when E_Record_Type     |
17831                  E_Record_Subtype  |
17832                  Class_Wide_Kind   |
17833                  E_Incomplete_Type =>
17834                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
17835
17836                if Ekind (Def_Id) = E_Incomplete_Type then
17837                   Set_Private_Dependents (Def_Id, New_Elmt_List);
17838                end if;
17839
17840             when Private_Kind =>
17841                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
17842                Set_Private_Dependents (Def_Id, New_Elmt_List);
17843
17844                --  In case of an invalid constraint prevent further processing
17845                --  since the type constructed is missing expected fields.
17846
17847                if Etype (Def_Id) = Any_Type then
17848                   return Def_Id;
17849                end if;
17850
17851                --  If the full view is that of a task with discriminants,
17852                --  we must constrain both the concurrent type and its
17853                --  corresponding record type. Otherwise we will just propagate
17854                --  the constraint to the full view, if available.
17855
17856                if Present (Full_View (Subtype_Mark_Id))
17857                  and then Has_Discriminants (Subtype_Mark_Id)
17858                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
17859                then
17860                   Full_View_Id :=
17861                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
17862
17863                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
17864                   Constrain_Concurrent (Full_View_Id, S,
17865                     Related_Nod, Related_Id, Suffix);
17866                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
17867                   Set_Full_View (Def_Id, Full_View_Id);
17868
17869                   --  Introduce an explicit reference to the private subtype,
17870                   --  to prevent scope anomalies in gigi if first use appears
17871                   --  in a nested context, e.g. a later function body.
17872                   --  Should this be generated in other contexts than a full
17873                   --  type declaration?
17874
17875                   if Is_Itype (Def_Id)
17876                     and then
17877                       Nkind (Parent (P)) = N_Full_Type_Declaration
17878                   then
17879                      Build_Itype_Reference (Def_Id, Parent (P));
17880                   end if;
17881
17882                else
17883                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
17884                end if;
17885
17886             when Concurrent_Kind  =>
17887                Constrain_Concurrent (Def_Id, S,
17888                  Related_Nod, Related_Id, Suffix);
17889
17890             when others =>
17891                Error_Msg_N ("invalid subtype mark in subtype indication", S);
17892          end case;
17893
17894          --  Size and Convention are always inherited from the base type
17895
17896          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
17897          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
17898
17899          return Def_Id;
17900       end if;
17901    end Process_Subtype;
17902
17903    ---------------------------------------
17904    -- Check_Anonymous_Access_Components --
17905    ---------------------------------------
17906
17907    procedure Check_Anonymous_Access_Components
17908       (Typ_Decl  : Node_Id;
17909        Typ       : Entity_Id;
17910        Prev      : Entity_Id;
17911        Comp_List : Node_Id)
17912    is
17913       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
17914       Anon_Access : Entity_Id;
17915       Acc_Def     : Node_Id;
17916       Comp        : Node_Id;
17917       Comp_Def    : Node_Id;
17918       Decl        : Node_Id;
17919       Type_Def    : Node_Id;
17920
17921       procedure Build_Incomplete_Type_Declaration;
17922       --  If the record type contains components that include an access to the
17923       --  current record, then create an incomplete type declaration for the
17924       --  record, to be used as the designated type of the anonymous access.
17925       --  This is done only once, and only if there is no previous partial
17926       --  view of the type.
17927
17928       function Designates_T (Subt : Node_Id) return Boolean;
17929       --  Check whether a node designates the enclosing record type, or 'Class
17930       --  of that type
17931
17932       function Mentions_T (Acc_Def : Node_Id) return Boolean;
17933       --  Check whether an access definition includes a reference to
17934       --  the enclosing record type. The reference can be a subtype mark
17935       --  in the access definition itself, a 'Class attribute reference, or
17936       --  recursively a reference appearing in a parameter specification
17937       --  or result definition of an access_to_subprogram definition.
17938
17939       --------------------------------------
17940       -- Build_Incomplete_Type_Declaration --
17941       --------------------------------------
17942
17943       procedure Build_Incomplete_Type_Declaration is
17944          Decl  : Node_Id;
17945          Inc_T : Entity_Id;
17946          H     : Entity_Id;
17947
17948          --  Is_Tagged indicates whether the type is tagged. It is tagged if
17949          --  it's "is new ... with record" or else "is tagged record ...".
17950
17951          Is_Tagged : constant Boolean :=
17952              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
17953                  and then
17954                    Present
17955                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
17956            or else
17957              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
17958                  and then Tagged_Present (Type_Definition (Typ_Decl)));
17959
17960       begin
17961          --  If there is a previous partial view, no need to create a new one
17962          --  If the partial view, given by Prev, is incomplete,  If Prev is
17963          --  a private declaration, full declaration is flagged accordingly.
17964
17965          if Prev /= Typ then
17966             if Is_Tagged then
17967                Make_Class_Wide_Type (Prev);
17968                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
17969                Set_Etype (Class_Wide_Type (Typ), Typ);
17970             end if;
17971
17972             return;
17973
17974          elsif Has_Private_Declaration (Typ) then
17975
17976             --  If we refer to T'Class inside T, and T is the completion of a
17977             --  private type, then we need to make sure the class-wide type
17978             --  exists.
17979
17980             if Is_Tagged then
17981                Make_Class_Wide_Type (Typ);
17982             end if;
17983
17984             return;
17985
17986          --  If there was a previous anonymous access type, the incomplete
17987          --  type declaration will have been created already.
17988
17989          elsif Present (Current_Entity (Typ))
17990            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
17991            and then Full_View (Current_Entity (Typ)) = Typ
17992          then
17993             if Is_Tagged
17994               and then Comes_From_Source (Current_Entity (Typ))
17995               and then not Is_Tagged_Type (Current_Entity (Typ))
17996             then
17997                Make_Class_Wide_Type (Typ);
17998                Error_Msg_N
17999                  ("incomplete view of tagged type should be declared tagged?",
18000                   Parent (Current_Entity (Typ)));
18001             end if;
18002             return;
18003
18004          else
18005             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
18006             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
18007
18008             --  Type has already been inserted into the current scope. Remove
18009             --  it, and add incomplete declaration for type, so that subsequent
18010             --  anonymous access types can use it. The entity is unchained from
18011             --  the homonym list and from immediate visibility. After analysis,
18012             --  the entity in the incomplete declaration becomes immediately
18013             --  visible in the record declaration that follows.
18014
18015             H := Current_Entity (Typ);
18016
18017             if H = Typ then
18018                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
18019             else
18020                while Present (H)
18021                  and then Homonym (H) /= Typ
18022                loop
18023                   H := Homonym (Typ);
18024                end loop;
18025
18026                Set_Homonym (H, Homonym (Typ));
18027             end if;
18028
18029             Insert_Before (Typ_Decl, Decl);
18030             Analyze (Decl);
18031             Set_Full_View (Inc_T, Typ);
18032
18033             if Is_Tagged then
18034
18035                --  Create a common class-wide type for both views, and set the
18036                --  Etype of the class-wide type to the full view.
18037
18038                Make_Class_Wide_Type (Inc_T);
18039                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
18040                Set_Etype (Class_Wide_Type (Typ), Typ);
18041             end if;
18042          end if;
18043       end Build_Incomplete_Type_Declaration;
18044
18045       ------------------
18046       -- Designates_T --
18047       ------------------
18048
18049       function Designates_T (Subt : Node_Id) return Boolean is
18050          Type_Id : constant Name_Id := Chars (Typ);
18051
18052          function Names_T (Nam : Node_Id) return Boolean;
18053          --  The record type has not been introduced in the current scope
18054          --  yet, so we must examine the name of the type itself, either
18055          --  an identifier T, or an expanded name of the form P.T, where
18056          --  P denotes the current scope.
18057
18058          -------------
18059          -- Names_T --
18060          -------------
18061
18062          function Names_T (Nam : Node_Id) return Boolean is
18063          begin
18064             if Nkind (Nam) = N_Identifier then
18065                return Chars (Nam) = Type_Id;
18066
18067             elsif Nkind (Nam) = N_Selected_Component then
18068                if Chars (Selector_Name (Nam)) = Type_Id then
18069                   if Nkind (Prefix (Nam)) = N_Identifier then
18070                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
18071
18072                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
18073                      return Chars (Selector_Name (Prefix (Nam))) =
18074                             Chars (Current_Scope);
18075                   else
18076                      return False;
18077                   end if;
18078
18079                else
18080                   return False;
18081                end if;
18082
18083             else
18084                return False;
18085             end if;
18086          end Names_T;
18087
18088       --  Start of processing for Designates_T
18089
18090       begin
18091          if Nkind (Subt) = N_Identifier then
18092             return Chars (Subt) = Type_Id;
18093
18094             --  Reference can be through an expanded name which has not been
18095             --  analyzed yet, and which designates enclosing scopes.
18096
18097          elsif Nkind (Subt) = N_Selected_Component then
18098             if Names_T (Subt) then
18099                return True;
18100
18101             --  Otherwise it must denote an entity that is already visible.
18102             --  The access definition may name a subtype of the enclosing
18103             --  type, if there is a previous incomplete declaration for it.
18104
18105             else
18106                Find_Selected_Component (Subt);
18107                return
18108                  Is_Entity_Name (Subt)
18109                    and then Scope (Entity (Subt)) = Current_Scope
18110                    and then
18111                      (Chars (Base_Type (Entity (Subt))) = Type_Id
18112                        or else
18113                          (Is_Class_Wide_Type (Entity (Subt))
18114                            and then
18115                            Chars (Etype (Base_Type (Entity (Subt)))) =
18116                                                                   Type_Id));
18117             end if;
18118
18119          --  A reference to the current type may appear as the prefix of
18120          --  a 'Class attribute.
18121
18122          elsif Nkind (Subt) = N_Attribute_Reference
18123            and then Attribute_Name (Subt) = Name_Class
18124          then
18125             return Names_T (Prefix (Subt));
18126
18127          else
18128             return False;
18129          end if;
18130       end Designates_T;
18131
18132       ----------------
18133       -- Mentions_T --
18134       ----------------
18135
18136       function Mentions_T (Acc_Def : Node_Id) return Boolean is
18137          Param_Spec : Node_Id;
18138
18139          Acc_Subprg : constant Node_Id :=
18140                         Access_To_Subprogram_Definition (Acc_Def);
18141
18142       begin
18143          if No (Acc_Subprg) then
18144             return Designates_T (Subtype_Mark (Acc_Def));
18145          end if;
18146
18147          --  Component is an access_to_subprogram: examine its formals,
18148          --  and result definition in the case of an access_to_function.
18149
18150          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
18151          while Present (Param_Spec) loop
18152             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
18153               and then Mentions_T (Parameter_Type (Param_Spec))
18154             then
18155                return True;
18156
18157             elsif Designates_T (Parameter_Type (Param_Spec)) then
18158                return True;
18159             end if;
18160
18161             Next (Param_Spec);
18162          end loop;
18163
18164          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
18165             if Nkind (Result_Definition (Acc_Subprg)) =
18166                  N_Access_Definition
18167             then
18168                return Mentions_T (Result_Definition (Acc_Subprg));
18169             else
18170                return Designates_T (Result_Definition (Acc_Subprg));
18171             end if;
18172          end if;
18173
18174          return False;
18175       end Mentions_T;
18176
18177    --  Start of processing for Check_Anonymous_Access_Components
18178
18179    begin
18180       if No (Comp_List) then
18181          return;
18182       end if;
18183
18184       Comp := First (Component_Items (Comp_List));
18185       while Present (Comp) loop
18186          if Nkind (Comp) = N_Component_Declaration
18187            and then Present
18188              (Access_Definition (Component_Definition (Comp)))
18189            and then
18190              Mentions_T (Access_Definition (Component_Definition (Comp)))
18191          then
18192             Comp_Def := Component_Definition (Comp);
18193             Acc_Def :=
18194               Access_To_Subprogram_Definition
18195                 (Access_Definition (Comp_Def));
18196
18197             Build_Incomplete_Type_Declaration;
18198             Anon_Access := Make_Temporary (Loc, 'S');
18199
18200             --  Create a declaration for the anonymous access type: either
18201             --  an access_to_object or an access_to_subprogram.
18202
18203             if Present (Acc_Def) then
18204                if Nkind  (Acc_Def) = N_Access_Function_Definition then
18205                   Type_Def :=
18206                     Make_Access_Function_Definition (Loc,
18207                       Parameter_Specifications =>
18208                         Parameter_Specifications (Acc_Def),
18209                       Result_Definition => Result_Definition (Acc_Def));
18210                else
18211                   Type_Def :=
18212                     Make_Access_Procedure_Definition (Loc,
18213                       Parameter_Specifications =>
18214                         Parameter_Specifications (Acc_Def));
18215                end if;
18216
18217             else
18218                Type_Def :=
18219                  Make_Access_To_Object_Definition (Loc,
18220                    Subtype_Indication =>
18221                       Relocate_Node
18222                         (Subtype_Mark
18223                           (Access_Definition (Comp_Def))));
18224
18225                Set_Constant_Present
18226                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
18227                Set_All_Present
18228                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
18229             end if;
18230
18231             Set_Null_Exclusion_Present
18232               (Type_Def,
18233                Null_Exclusion_Present (Access_Definition (Comp_Def)));
18234
18235             Decl :=
18236               Make_Full_Type_Declaration (Loc,
18237                 Defining_Identifier => Anon_Access,
18238                 Type_Definition     => Type_Def);
18239
18240             Insert_Before (Typ_Decl, Decl);
18241             Analyze (Decl);
18242
18243             --  If an access to object, Preserve entity of designated type,
18244             --  for ASIS use, before rewriting the component definition.
18245
18246             if No (Acc_Def) then
18247                declare
18248                   Desig : Entity_Id;
18249
18250                begin
18251                   Desig := Entity (Subtype_Indication (Type_Def));
18252
18253                   --  If the access definition is to the current  record,
18254                   --  the visible entity at this point is an  incomplete
18255                   --  type. Retrieve the full view to simplify  ASIS queries
18256
18257                   if Ekind (Desig) = E_Incomplete_Type then
18258                      Desig := Full_View (Desig);
18259                   end if;
18260
18261                   Set_Entity
18262                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
18263                end;
18264             end if;
18265
18266             Rewrite (Comp_Def,
18267               Make_Component_Definition (Loc,
18268                 Subtype_Indication =>
18269                New_Occurrence_Of (Anon_Access, Loc)));
18270
18271             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
18272                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
18273             else
18274                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
18275             end if;
18276
18277             Set_Is_Local_Anonymous_Access (Anon_Access);
18278          end if;
18279
18280          Next (Comp);
18281       end loop;
18282
18283       if Present (Variant_Part (Comp_List)) then
18284          declare
18285             V : Node_Id;
18286          begin
18287             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
18288             while Present (V) loop
18289                Check_Anonymous_Access_Components
18290                  (Typ_Decl, Typ, Prev, Component_List (V));
18291                Next_Non_Pragma (V);
18292             end loop;
18293          end;
18294       end if;
18295    end Check_Anonymous_Access_Components;
18296
18297    --------------------------------
18298    -- Preanalyze_Spec_Expression --
18299    --------------------------------
18300
18301    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
18302       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
18303    begin
18304       In_Spec_Expression := True;
18305       Preanalyze_And_Resolve (N, T);
18306       In_Spec_Expression := Save_In_Spec_Expression;
18307    end Preanalyze_Spec_Expression;
18308
18309    -----------------------------
18310    -- Record_Type_Declaration --
18311    -----------------------------
18312
18313    procedure Record_Type_Declaration
18314      (T    : Entity_Id;
18315       N    : Node_Id;
18316       Prev : Entity_Id)
18317    is
18318       Def       : constant Node_Id := Type_Definition (N);
18319       Is_Tagged : Boolean;
18320       Tag_Comp  : Entity_Id;
18321
18322    begin
18323       --  These flags must be initialized before calling Process_Discriminants
18324       --  because this routine makes use of them.
18325
18326       Set_Ekind             (T, E_Record_Type);
18327       Set_Etype             (T, T);
18328       Init_Size_Align       (T);
18329       Set_Interfaces        (T, No_Elist);
18330       Set_Stored_Constraint (T, No_Elist);
18331
18332       --  Normal case
18333
18334       if Ada_Version < Ada_2005
18335         or else not Interface_Present (Def)
18336       then
18337          --  The flag Is_Tagged_Type might have already been set by
18338          --  Find_Type_Name if it detected an error for declaration T. This
18339          --  arises in the case of private tagged types where the full view
18340          --  omits the word tagged.
18341
18342          Is_Tagged :=
18343            Tagged_Present (Def)
18344              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
18345
18346          Set_Is_Tagged_Type      (T, Is_Tagged);
18347          Set_Is_Limited_Record   (T, Limited_Present (Def));
18348
18349          --  Type is abstract if full declaration carries keyword, or if
18350          --  previous partial view did.
18351
18352          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
18353                                       or else Abstract_Present (Def));
18354
18355       else
18356          Is_Tagged := True;
18357          Analyze_Interface_Declaration (T, Def);
18358
18359          if Present (Discriminant_Specifications (N)) then
18360             Error_Msg_N
18361               ("interface types cannot have discriminants",
18362                 Defining_Identifier
18363                   (First (Discriminant_Specifications (N))));
18364          end if;
18365       end if;
18366
18367       --  First pass: if there are self-referential access components,
18368       --  create the required anonymous access type declarations, and if
18369       --  need be an incomplete type declaration for T itself.
18370
18371       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
18372
18373       if Ada_Version >= Ada_2005
18374         and then Present (Interface_List (Def))
18375       then
18376          Check_Interfaces (N, Def);
18377
18378          declare
18379             Ifaces_List : Elist_Id;
18380
18381          begin
18382             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
18383             --  already in the parents.
18384
18385             Collect_Interfaces
18386               (T               => T,
18387                Ifaces_List     => Ifaces_List,
18388                Exclude_Parents => True);
18389
18390             Set_Interfaces (T, Ifaces_List);
18391          end;
18392       end if;
18393
18394       --  Records constitute a scope for the component declarations within.
18395       --  The scope is created prior to the processing of these declarations.
18396       --  Discriminants are processed first, so that they are visible when
18397       --  processing the other components. The Ekind of the record type itself
18398       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
18399
18400       --  Enter record scope
18401
18402       Push_Scope (T);
18403
18404       --  If an incomplete or private type declaration was already given for
18405       --  the type, then this scope already exists, and the discriminants have
18406       --  been declared within. We must verify that the full declaration
18407       --  matches the incomplete one.
18408
18409       Check_Or_Process_Discriminants (N, T, Prev);
18410
18411       Set_Is_Constrained     (T, not Has_Discriminants (T));
18412       Set_Has_Delayed_Freeze (T, True);
18413
18414       --  For tagged types add a manually analyzed component corresponding
18415       --  to the component _tag, the corresponding piece of tree will be
18416       --  expanded as part of the freezing actions if it is not a CPP_Class.
18417
18418       if Is_Tagged then
18419
18420          --  Do not add the tag unless we are in expansion mode
18421
18422          if Expander_Active then
18423             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
18424             Enter_Name (Tag_Comp);
18425
18426             Set_Ekind                     (Tag_Comp, E_Component);
18427             Set_Is_Tag                    (Tag_Comp);
18428             Set_Is_Aliased                (Tag_Comp);
18429             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
18430             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
18431             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
18432             Init_Component_Location       (Tag_Comp);
18433
18434             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
18435             --  implemented interfaces.
18436
18437             if Has_Interfaces (T) then
18438                Add_Interface_Tag_Components (N, T);
18439             end if;
18440          end if;
18441
18442          Make_Class_Wide_Type (T);
18443          Set_Direct_Primitive_Operations (T, New_Elmt_List);
18444       end if;
18445
18446       --  We must suppress range checks when processing record components in
18447       --  the presence of discriminants, since we don't want spurious checks to
18448       --  be generated during their analysis, but Suppress_Range_Checks flags
18449       --  must be reset the after processing the record definition.
18450
18451       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
18452       --  couldn't we just use the normal range check suppression method here.
18453       --  That would seem cleaner ???
18454
18455       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
18456          Set_Kill_Range_Checks (T, True);
18457          Record_Type_Definition (Def, Prev);
18458          Set_Kill_Range_Checks (T, False);
18459       else
18460          Record_Type_Definition (Def, Prev);
18461       end if;
18462
18463       --  Exit from record scope
18464
18465       End_Scope;
18466
18467       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
18468       --  the implemented interfaces and associate them an aliased entity.
18469
18470       if Is_Tagged
18471         and then not Is_Empty_List (Interface_List (Def))
18472       then
18473          Derive_Progenitor_Subprograms (T, T);
18474       end if;
18475    end Record_Type_Declaration;
18476
18477    ----------------------------
18478    -- Record_Type_Definition --
18479    ----------------------------
18480
18481    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
18482       Component          : Entity_Id;
18483       Ctrl_Components    : Boolean := False;
18484       Final_Storage_Only : Boolean;
18485       T                  : Entity_Id;
18486
18487    begin
18488       if Ekind (Prev_T) = E_Incomplete_Type then
18489          T := Full_View (Prev_T);
18490       else
18491          T := Prev_T;
18492       end if;
18493
18494       Final_Storage_Only := not Is_Controlled (T);
18495
18496       --  Ada 2005: check whether an explicit Limited is present in a derived
18497       --  type declaration.
18498
18499       if Nkind (Parent (Def)) = N_Derived_Type_Definition
18500         and then Limited_Present (Parent (Def))
18501       then
18502          Set_Is_Limited_Record (T);
18503       end if;
18504
18505       --  If the component list of a record type is defined by the reserved
18506       --  word null and there is no discriminant part, then the record type has
18507       --  no components and all records of the type are null records (RM 3.7)
18508       --  This procedure is also called to process the extension part of a
18509       --  record extension, in which case the current scope may have inherited
18510       --  components.
18511
18512       if No (Def)
18513         or else No (Component_List (Def))
18514         or else Null_Present (Component_List (Def))
18515       then
18516          null;
18517
18518       else
18519          Analyze_Declarations (Component_Items (Component_List (Def)));
18520
18521          if Present (Variant_Part (Component_List (Def))) then
18522             Analyze (Variant_Part (Component_List (Def)));
18523          end if;
18524       end if;
18525
18526       --  After completing the semantic analysis of the record definition,
18527       --  record components, both new and inherited, are accessible. Set their
18528       --  kind accordingly. Exclude malformed itypes from illegal declarations,
18529       --  whose Ekind may be void.
18530
18531       Component := First_Entity (Current_Scope);
18532       while Present (Component) loop
18533          if Ekind (Component) = E_Void
18534            and then not Is_Itype (Component)
18535          then
18536             Set_Ekind (Component, E_Component);
18537             Init_Component_Location (Component);
18538          end if;
18539
18540          if Has_Task (Etype (Component)) then
18541             Set_Has_Task (T);
18542          end if;
18543
18544          if Ekind (Component) /= E_Component then
18545             null;
18546
18547          --  Do not set Has_Controlled_Component on a class-wide equivalent
18548          --  type. See Make_CW_Equivalent_Type.
18549
18550          elsif not Is_Class_Wide_Equivalent_Type (T)
18551            and then (Has_Controlled_Component (Etype (Component))
18552                       or else (Chars (Component) /= Name_uParent
18553                                 and then Is_Controlled (Etype (Component))))
18554          then
18555             Set_Has_Controlled_Component (T, True);
18556             Final_Storage_Only :=
18557               Final_Storage_Only
18558                 and then Finalize_Storage_Only (Etype (Component));
18559             Ctrl_Components := True;
18560          end if;
18561
18562          Next_Entity (Component);
18563       end loop;
18564
18565       --  A Type is Finalize_Storage_Only only if all its controlled components
18566       --  are also.
18567
18568       if Ctrl_Components then
18569          Set_Finalize_Storage_Only (T, Final_Storage_Only);
18570       end if;
18571
18572       --  Place reference to end record on the proper entity, which may
18573       --  be a partial view.
18574
18575       if Present (Def) then
18576          Process_End_Label (Def, 'e', Prev_T);
18577       end if;
18578    end Record_Type_Definition;
18579
18580    ------------------------
18581    -- Replace_Components --
18582    ------------------------
18583
18584    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
18585       function Process (N : Node_Id) return Traverse_Result;
18586
18587       -------------
18588       -- Process --
18589       -------------
18590
18591       function Process (N : Node_Id) return Traverse_Result is
18592          Comp : Entity_Id;
18593
18594       begin
18595          if Nkind (N) = N_Discriminant_Specification then
18596             Comp := First_Discriminant (Typ);
18597             while Present (Comp) loop
18598                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18599                   Set_Defining_Identifier (N, Comp);
18600                   exit;
18601                end if;
18602
18603                Next_Discriminant (Comp);
18604             end loop;
18605
18606          elsif Nkind (N) = N_Component_Declaration then
18607             Comp := First_Component (Typ);
18608             while Present (Comp) loop
18609                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18610                   Set_Defining_Identifier (N, Comp);
18611                   exit;
18612                end if;
18613
18614                Next_Component (Comp);
18615             end loop;
18616          end if;
18617
18618          return OK;
18619       end Process;
18620
18621       procedure Replace is new Traverse_Proc (Process);
18622
18623    --  Start of processing for Replace_Components
18624
18625    begin
18626       Replace (Decl);
18627    end Replace_Components;
18628
18629    -------------------------------
18630    -- Set_Completion_Referenced --
18631    -------------------------------
18632
18633    procedure Set_Completion_Referenced (E : Entity_Id) is
18634    begin
18635       --  If in main unit, mark entity that is a completion as referenced,
18636       --  warnings go on the partial view when needed.
18637
18638       if In_Extended_Main_Source_Unit (E) then
18639          Set_Referenced (E);
18640       end if;
18641    end Set_Completion_Referenced;
18642
18643    ---------------------
18644    -- Set_Fixed_Range --
18645    ---------------------
18646
18647    --  The range for fixed-point types is complicated by the fact that we
18648    --  do not know the exact end points at the time of the declaration. This
18649    --  is true for three reasons:
18650
18651    --     A size clause may affect the fudging of the end-points
18652    --     A small clause may affect the values of the end-points
18653    --     We try to include the end-points if it does not affect the size
18654
18655    --  This means that the actual end-points must be established at the point
18656    --  when the type is frozen. Meanwhile, we first narrow the range as
18657    --  permitted (so that it will fit if necessary in a small specified size),
18658    --  and then build a range subtree with these narrowed bounds.
18659
18660    --  Set_Fixed_Range constructs the range from real literal values, and sets
18661    --  the range as the Scalar_Range of the given fixed-point type entity.
18662
18663    --  The parent of this range is set to point to the entity so that it is
18664    --  properly hooked into the tree (unlike normal Scalar_Range entries for
18665    --  other scalar types, which are just pointers to the range in the
18666    --  original tree, this would otherwise be an orphan).
18667
18668    --  The tree is left unanalyzed. When the type is frozen, the processing
18669    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
18670    --  analyzed, and uses this as an indication that it should complete
18671    --  work on the range (it will know the final small and size values).
18672
18673    procedure Set_Fixed_Range
18674      (E   : Entity_Id;
18675       Loc : Source_Ptr;
18676       Lo  : Ureal;
18677       Hi  : Ureal)
18678    is
18679       S : constant Node_Id :=
18680             Make_Range (Loc,
18681               Low_Bound  => Make_Real_Literal (Loc, Lo),
18682               High_Bound => Make_Real_Literal (Loc, Hi));
18683    begin
18684       Set_Scalar_Range (E, S);
18685       Set_Parent (S, E);
18686    end Set_Fixed_Range;
18687
18688    ----------------------------------
18689    -- Set_Scalar_Range_For_Subtype --
18690    ----------------------------------
18691
18692    procedure Set_Scalar_Range_For_Subtype
18693      (Def_Id : Entity_Id;
18694       R      : Node_Id;
18695       Subt   : Entity_Id)
18696    is
18697       Kind : constant Entity_Kind :=  Ekind (Def_Id);
18698
18699    begin
18700       --  Defend against previous error
18701
18702       if Nkind (R) = N_Error then
18703          return;
18704       end if;
18705
18706       Set_Scalar_Range (Def_Id, R);
18707
18708       --  We need to link the range into the tree before resolving it so
18709       --  that types that are referenced, including importantly the subtype
18710       --  itself, are properly frozen (Freeze_Expression requires that the
18711       --  expression be properly linked into the tree). Of course if it is
18712       --  already linked in, then we do not disturb the current link.
18713
18714       if No (Parent (R)) then
18715          Set_Parent (R, Def_Id);
18716       end if;
18717
18718       --  Reset the kind of the subtype during analysis of the range, to
18719       --  catch possible premature use in the bounds themselves.
18720
18721       Set_Ekind (Def_Id, E_Void);
18722       Process_Range_Expr_In_Decl (R, Subt);
18723       Set_Ekind (Def_Id, Kind);
18724    end Set_Scalar_Range_For_Subtype;
18725
18726    --------------------------------------------------------
18727    -- Set_Stored_Constraint_From_Discriminant_Constraint --
18728    --------------------------------------------------------
18729
18730    procedure Set_Stored_Constraint_From_Discriminant_Constraint
18731      (E : Entity_Id)
18732    is
18733    begin
18734       --  Make sure set if encountered during Expand_To_Stored_Constraint
18735
18736       Set_Stored_Constraint (E, No_Elist);
18737
18738       --  Give it the right value
18739
18740       if Is_Constrained (E) and then Has_Discriminants (E) then
18741          Set_Stored_Constraint (E,
18742            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
18743       end if;
18744    end Set_Stored_Constraint_From_Discriminant_Constraint;
18745
18746    -------------------------------------
18747    -- Signed_Integer_Type_Declaration --
18748    -------------------------------------
18749
18750    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
18751       Implicit_Base : Entity_Id;
18752       Base_Typ      : Entity_Id;
18753       Lo_Val        : Uint;
18754       Hi_Val        : Uint;
18755       Errs          : Boolean := False;
18756       Lo            : Node_Id;
18757       Hi            : Node_Id;
18758
18759       function Can_Derive_From (E : Entity_Id) return Boolean;
18760       --  Determine whether given bounds allow derivation from specified type
18761
18762       procedure Check_Bound (Expr : Node_Id);
18763       --  Check bound to make sure it is integral and static. If not, post
18764       --  appropriate error message and set Errs flag
18765
18766       ---------------------
18767       -- Can_Derive_From --
18768       ---------------------
18769
18770       --  Note we check both bounds against both end values, to deal with
18771       --  strange types like ones with a range of 0 .. -12341234.
18772
18773       function Can_Derive_From (E : Entity_Id) return Boolean is
18774          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
18775          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
18776       begin
18777          return Lo <= Lo_Val and then Lo_Val <= Hi
18778                   and then
18779                 Lo <= Hi_Val and then Hi_Val <= Hi;
18780       end Can_Derive_From;
18781
18782       -----------------
18783       -- Check_Bound --
18784       -----------------
18785
18786       procedure Check_Bound (Expr : Node_Id) is
18787       begin
18788          --  If a range constraint is used as an integer type definition, each
18789          --  bound of the range must be defined by a static expression of some
18790          --  integer type, but the two bounds need not have the same integer
18791          --  type (Negative bounds are allowed.) (RM 3.5.4)
18792
18793          if not Is_Integer_Type (Etype (Expr)) then
18794             Error_Msg_N
18795               ("integer type definition bounds must be of integer type", Expr);
18796             Errs := True;
18797
18798          elsif not Is_OK_Static_Expression (Expr) then
18799             Flag_Non_Static_Expr
18800               ("non-static expression used for integer type bound!", Expr);
18801             Errs := True;
18802
18803          --  The bounds are folded into literals, and we set their type to be
18804          --  universal, to avoid typing difficulties: we cannot set the type
18805          --  of the literal to the new type, because this would be a forward
18806          --  reference for the back end,  and if the original type is user-
18807          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
18808
18809          else
18810             if Is_Entity_Name (Expr) then
18811                Fold_Uint (Expr, Expr_Value (Expr), True);
18812             end if;
18813
18814             Set_Etype (Expr, Universal_Integer);
18815          end if;
18816       end Check_Bound;
18817
18818    --  Start of processing for Signed_Integer_Type_Declaration
18819
18820    begin
18821       --  Create an anonymous base type
18822
18823       Implicit_Base :=
18824         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
18825
18826       --  Analyze and check the bounds, they can be of any integer type
18827
18828       Lo := Low_Bound (Def);
18829       Hi := High_Bound (Def);
18830
18831       --  Arbitrarily use Integer as the type if either bound had an error
18832
18833       if Hi = Error or else Lo = Error then
18834          Base_Typ := Any_Integer;
18835          Set_Error_Posted (T, True);
18836
18837       --  Here both bounds are OK expressions
18838
18839       else
18840          Analyze_And_Resolve (Lo, Any_Integer);
18841          Analyze_And_Resolve (Hi, Any_Integer);
18842
18843          Check_Bound (Lo);
18844          Check_Bound (Hi);
18845
18846          if Errs then
18847             Hi := Type_High_Bound (Standard_Long_Long_Integer);
18848             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
18849          end if;
18850
18851          --  Find type to derive from
18852
18853          Lo_Val := Expr_Value (Lo);
18854          Hi_Val := Expr_Value (Hi);
18855
18856          if Can_Derive_From (Standard_Short_Short_Integer) then
18857             Base_Typ := Base_Type (Standard_Short_Short_Integer);
18858
18859          elsif Can_Derive_From (Standard_Short_Integer) then
18860             Base_Typ := Base_Type (Standard_Short_Integer);
18861
18862          elsif Can_Derive_From (Standard_Integer) then
18863             Base_Typ := Base_Type (Standard_Integer);
18864
18865          elsif Can_Derive_From (Standard_Long_Integer) then
18866             Base_Typ := Base_Type (Standard_Long_Integer);
18867
18868          elsif Can_Derive_From (Standard_Long_Long_Integer) then
18869             Base_Typ := Base_Type (Standard_Long_Long_Integer);
18870
18871          else
18872             Base_Typ := Base_Type (Standard_Long_Long_Integer);
18873             Error_Msg_N ("integer type definition bounds out of range", Def);
18874             Hi := Type_High_Bound (Standard_Long_Long_Integer);
18875             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
18876          end if;
18877       end if;
18878
18879       --  Complete both implicit base and declared first subtype entities
18880
18881       Set_Etype          (Implicit_Base, Base_Typ);
18882       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
18883       Set_Size_Info      (Implicit_Base,                (Base_Typ));
18884       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
18885       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
18886
18887       Set_Ekind          (T, E_Signed_Integer_Subtype);
18888       Set_Etype          (T, Implicit_Base);
18889
18890       Set_Size_Info      (T,                (Implicit_Base));
18891       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
18892       Set_Scalar_Range   (T, Def);
18893       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
18894       Set_Is_Constrained (T);
18895    end Signed_Integer_Type_Declaration;
18896
18897 end Sem_Ch3;