OSDN Git Service

PR 33870
[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-2007, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Elists;   use Elists;
30 with Einfo;    use Einfo;
31 with Errout;   use Errout;
32 with Eval_Fat; use Eval_Fat;
33 with Exp_Ch3;  use Exp_Ch3;
34 with Exp_Dist; use Exp_Dist;
35 with Exp_Tss;  use Exp_Tss;
36 with Exp_Util; use Exp_Util;
37 with Fname;    use Fname;
38 with Freeze;   use Freeze;
39 with Itypes;   use Itypes;
40 with Layout;   use Layout;
41 with Lib;      use Lib;
42 with Lib.Xref; use Lib.Xref;
43 with Namet;    use Namet;
44 with Nmake;    use Nmake;
45 with Opt;      use Opt;
46 with Restrict; use Restrict;
47 with Rident;   use Rident;
48 with Rtsfind;  use Rtsfind;
49 with Sem;      use Sem;
50 with Sem_Case; use Sem_Case;
51 with Sem_Cat;  use Sem_Cat;
52 with Sem_Ch6;  use Sem_Ch6;
53 with Sem_Ch7;  use Sem_Ch7;
54 with Sem_Ch8;  use Sem_Ch8;
55 with Sem_Ch13; use Sem_Ch13;
56 with Sem_Disp; use Sem_Disp;
57 with Sem_Dist; use Sem_Dist;
58 with Sem_Elim; use Sem_Elim;
59 with Sem_Eval; use Sem_Eval;
60 with Sem_Mech; use Sem_Mech;
61 with Sem_Res;  use Sem_Res;
62 with Sem_Smem; use Sem_Smem;
63 with Sem_Type; use Sem_Type;
64 with Sem_Util; use Sem_Util;
65 with Sem_Warn; use Sem_Warn;
66 with Stand;    use Stand;
67 with Sinfo;    use Sinfo;
68 with Snames;   use Snames;
69 with Targparm; use Targparm;
70 with Tbuild;   use Tbuild;
71 with Ttypes;   use Ttypes;
72 with Uintp;    use Uintp;
73 with Urealp;   use Urealp;
74
75 package body Sem_Ch3 is
76
77    -----------------------
78    -- Local Subprograms --
79    -----------------------
80
81    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
82    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
83    --  abstract interface types implemented by a record type or a derived
84    --  record type.
85
86    procedure Build_Derived_Type
87      (N             : Node_Id;
88       Parent_Type   : Entity_Id;
89       Derived_Type  : Entity_Id;
90       Is_Completion : Boolean;
91       Derive_Subps  : Boolean := True);
92    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
93    --  the N_Full_Type_Declaration node containing the derived type definition.
94    --  Parent_Type is the entity for the parent type in the derived type
95    --  definition and Derived_Type the actual derived type. Is_Completion must
96    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
97    --  (ie Derived_Type = Defining_Identifier (N)). In this case N is not the
98    --  completion of a private type declaration. If Is_Completion is set to
99    --  True, N is the completion of a private type declaration and Derived_Type
100    --  is different from the defining identifier inside N (i.e. Derived_Type /=
101    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
102    --  subprograms should be derived. The only case where this parameter is
103    --  False is when Build_Derived_Type is recursively called to process an
104    --  implicit derived full type for a type derived from a private type (in
105    --  that case the subprograms must only be derived for the private view of
106    --  the type).
107    --
108    --  ??? These flags need a bit of re-examination and re-documentation:
109    --  ???  are they both necessary (both seem related to the recursion)?
110
111    procedure Build_Derived_Access_Type
112      (N            : Node_Id;
113       Parent_Type  : Entity_Id;
114       Derived_Type : Entity_Id);
115    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
116    --  create an implicit base if the parent type is constrained or if the
117    --  subtype indication has a constraint.
118
119    procedure Build_Derived_Array_Type
120      (N            : Node_Id;
121       Parent_Type  : Entity_Id;
122       Derived_Type : Entity_Id);
123    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
124    --  create an implicit base if the parent type is constrained or if the
125    --  subtype indication has a constraint.
126
127    procedure Build_Derived_Concurrent_Type
128      (N            : Node_Id;
129       Parent_Type  : Entity_Id;
130       Derived_Type : Entity_Id);
131    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
132    --  protected type, inherit entries and protected subprograms, check
133    --  legality of discriminant constraints if any.
134
135    procedure Build_Derived_Enumeration_Type
136      (N            : Node_Id;
137       Parent_Type  : Entity_Id;
138       Derived_Type : Entity_Id);
139    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
140    --  type, we must create a new list of literals. Types derived from
141    --  Character and Wide_Character are special-cased.
142
143    procedure Build_Derived_Numeric_Type
144      (N            : Node_Id;
145       Parent_Type  : Entity_Id;
146       Derived_Type : Entity_Id);
147    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
148    --  an anonymous base type, and propagate constraint to subtype if needed.
149
150    procedure Build_Derived_Private_Type
151      (N             : Node_Id;
152       Parent_Type   : Entity_Id;
153       Derived_Type  : Entity_Id;
154       Is_Completion : Boolean;
155       Derive_Subps  : Boolean := True);
156    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
157    --  because the parent may or may not have a completion, and the derivation
158    --  may itself be a completion.
159
160    procedure Build_Derived_Record_Type
161      (N            : Node_Id;
162       Parent_Type  : Entity_Id;
163       Derived_Type : Entity_Id;
164       Derive_Subps : Boolean := True);
165    --  Subsidiary procedure for Build_Derived_Type and
166    --  Analyze_Private_Extension_Declaration used for tagged and untagged
167    --  record types. All parameters are as in Build_Derived_Type except that
168    --  N, in addition to being an N_Full_Type_Declaration node, can also be an
169    --  N_Private_Extension_Declaration node. See the definition of this routine
170    --  for much more info. Derive_Subps indicates whether subprograms should
171    --  be derived from the parent type. The only case where Derive_Subps is
172    --  False is for an implicit derived full type for a type derived from a
173    --  private type (see Build_Derived_Type).
174
175    procedure Build_Discriminal (Discrim : Entity_Id);
176    --  Create the discriminal corresponding to discriminant Discrim, that is
177    --  the parameter corresponding to Discrim to be used in initialization
178    --  procedures for the type where Discrim is a discriminant. Discriminals
179    --  are not used during semantic analysis, and are not fully defined
180    --  entities until expansion. Thus they are not given a scope until
181    --  initialization procedures are built.
182
183    function Build_Discriminant_Constraints
184      (T           : Entity_Id;
185       Def         : Node_Id;
186       Derived_Def : Boolean := False) return Elist_Id;
187    --  Validate discriminant constraints and return the list of the constraints
188    --  in order of discriminant declarations, where T is the discriminated
189    --  unconstrained type. Def is the N_Subtype_Indication node where the
190    --  discriminants constraints for T are specified. Derived_Def is True
191    --  when building the discriminant constraints in a derived type definition
192    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
193    --  type and Def is the constraint "(xxx)" on T and this routine sets the
194    --  Corresponding_Discriminant field of the discriminants in the derived
195    --  type D to point to the corresponding discriminants in the parent type T.
196
197    procedure Build_Discriminated_Subtype
198      (T           : Entity_Id;
199       Def_Id      : Entity_Id;
200       Elist       : Elist_Id;
201       Related_Nod : Node_Id;
202       For_Access  : Boolean := False);
203    --  Subsidiary procedure to Constrain_Discriminated_Type and to
204    --  Process_Incomplete_Dependents. Given
205    --
206    --     T (a possibly discriminated base type)
207    --     Def_Id (a very partially built subtype for T),
208    --
209    --  the call completes Def_Id to be the appropriate E_*_Subtype.
210    --
211    --  The Elist is the list of discriminant constraints if any (it is set
212    --  to No_Elist if T is not a discriminated type, and to an empty list if
213    --  T has discriminants but there are no discriminant constraints). The
214    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
215    --  The For_Access says whether or not this subtype is really constraining
216    --  an access type. That is its sole purpose is the designated type of an
217    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
218    --  is built to avoid freezing T when the access subtype is frozen.
219
220    function Build_Scalar_Bound
221      (Bound : Node_Id;
222       Par_T : Entity_Id;
223       Der_T : Entity_Id) return Node_Id;
224    --  The bounds of a derived scalar type are conversions of the bounds of
225    --  the parent type. Optimize the representation if the bounds are literals.
226    --  Needs a more complete spec--what are the parameters exactly, and what
227    --  exactly is the returned value, and how is Bound affected???
228
229    procedure Build_Itype_Reference
230      (Ityp : Entity_Id;
231       Nod  : Node_Id);
232    --  Create a reference to an internal type, for use by Gigi. The back-end
233    --  elaborates itypes on demand, i.e. when their first use is seen. This
234    --  can lead to scope anomalies if the first use is within a scope that is
235    --  nested within the scope that contains  the point of definition of the
236    --  itype. The Itype_Reference node forces the elaboration of the itype
237    --  in the proper scope. The node is inserted after Nod, which is the
238    --  enclosing declaration that generated Ityp.
239    --  A related mechanism is used during expansion, for itypes created in
240    --  branches of conditionals. See Ensure_Defined in exp_util.
241    --  Could both mechanisms be merged ???
242
243    procedure Build_Underlying_Full_View
244      (N   : Node_Id;
245       Typ : Entity_Id;
246       Par : Entity_Id);
247    --  If the completion of a private type is itself derived from a private
248    --  type, or if the full view of a private subtype is itself private, the
249    --  back-end has no way to compute the actual size of this type. We build
250    --  an internal subtype declaration of the proper parent type to convey
251    --  this information. This extra mechanism is needed because a full
252    --  view cannot itself have a full view (it would get clobbered during
253    --  view exchanges).
254
255    procedure Check_Abstract_Interfaces (N : Node_Id; Def : Node_Id);
256    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
257
258    procedure Check_Access_Discriminant_Requires_Limited
259      (D   : Node_Id;
260       Loc : Node_Id);
261    --  Check the restriction that the type to which an access discriminant
262    --  belongs must be a concurrent type or a descendant of a type with
263    --  the reserved word 'limited' in its declaration.
264
265    procedure Check_Anonymous_Access_Components
266       (Typ_Decl  : Node_Id;
267        Typ       : Entity_Id;
268        Prev      : Entity_Id;
269        Comp_List : Node_Id);
270    --  Ada 2005 AI-382: an access component in a record definition can refer to
271    --  the enclosing record, in which case it denotes the type itself, and not
272    --  the current instance of the type. We create an anonymous access type for
273    --  the component, and flag it as an access to a component, so accessibility
274    --  checks are properly performed on it. The declaration of the access type
275    --  is placed ahead of that of the record to prevent order-of-elaboration
276    --  circularity issues in Gigi. We create an incomplete type for the record
277    --  declaration, which is the designated type of the anonymous access.
278
279    procedure Check_Delta_Expression (E : Node_Id);
280    --  Check that the expression represented by E is suitable for use as a
281    --  delta expression, i.e. it is of real type and is static.
282
283    procedure Check_Digits_Expression (E : Node_Id);
284    --  Check that the expression represented by E is suitable for use as a
285    --  digits expression, i.e. it is of integer type, positive and static.
286
287    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
288    --  Validate the initialization of an object declaration. T is the required
289    --  type, and Exp is the initialization expression.
290
291    procedure Check_Or_Process_Discriminants
292      (N    : Node_Id;
293       T    : Entity_Id;
294       Prev : Entity_Id := Empty);
295    --  If T is the full declaration of an incomplete or private type, check the
296    --  conformance of the discriminants, otherwise process them. Prev is the
297    --  entity of the partial declaration, if any.
298
299    procedure Check_Real_Bound (Bound : Node_Id);
300    --  Check given bound for being of real type and static. If not, post an
301    --  appropriate message, and rewrite the bound with the real literal zero.
302
303    procedure Constant_Redeclaration
304      (Id : Entity_Id;
305       N  : Node_Id;
306       T  : out Entity_Id);
307    --  Various checks on legality of full declaration of deferred constant.
308    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
309    --  node. The caller has not yet set any attributes of this entity.
310
311    function Contain_Interface
312      (Iface  : Entity_Id;
313       Ifaces : Elist_Id) return Boolean;
314    --  Ada 2005: Determine whether Iface is present in the list Ifaces
315
316    procedure Convert_Scalar_Bounds
317      (N            : Node_Id;
318       Parent_Type  : Entity_Id;
319       Derived_Type : Entity_Id;
320       Loc          : Source_Ptr);
321    --  For derived scalar types, convert the bounds in the type definition to
322    --  the derived type, and complete their analysis. Given a constraint of the
323    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
324    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
325    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
326    --  subtype are conversions of those bounds to the derived_type, so that
327    --  their typing is consistent.
328
329    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
330    --  Copies attributes from array base type T2 to array base type T1. Copies
331    --  only attributes that apply to base types, but not subtypes.
332
333    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
334    --  Copies attributes from array subtype T2 to array subtype T1. Copies
335    --  attributes that apply to both subtypes and base types.
336
337    procedure Create_Constrained_Components
338      (Subt        : Entity_Id;
339       Decl_Node   : Node_Id;
340       Typ         : Entity_Id;
341       Constraints : Elist_Id);
342    --  Build the list of entities for a constrained discriminated record
343    --  subtype. If a component depends on a discriminant, replace its subtype
344    --  using the discriminant values in the discriminant constraint. Subt is
345    --  the defining identifier for the subtype whose list of constrained
346    --  entities we will create. Decl_Node is the type declaration node where we
347    --  will attach all the itypes created. Typ is the base discriminated type
348    --  for the subtype Subt. Constraints is the list of discriminant
349    --  constraints for Typ.
350
351    function Constrain_Component_Type
352      (Comp            : Entity_Id;
353       Constrained_Typ : Entity_Id;
354       Related_Node    : Node_Id;
355       Typ             : Entity_Id;
356       Constraints     : Elist_Id) return Entity_Id;
357    --  Given a discriminated base type Typ, a list of discriminant constraint
358    --  Constraints for Typ and a component of Typ, with type Compon_Type,
359    --  create and return the type corresponding to Compon_type where all
360    --  discriminant references are replaced with the corresponding constraint.
361    --  If no discriminant references occur in Compon_Typ then return it as is.
362    --  Constrained_Typ is the final constrained subtype to which the
363    --  constrained Compon_Type belongs. Related_Node is the node where we will
364    --  attach all the itypes created.
365    --  Above description is confused, what is Compon_Type???
366
367    procedure Constrain_Access
368      (Def_Id      : in out Entity_Id;
369       S           : Node_Id;
370       Related_Nod : Node_Id);
371    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
372    --  an anonymous type created for a subtype indication. In that case it is
373    --  created in the procedure and attached to Related_Nod.
374
375    procedure Constrain_Array
376      (Def_Id      : in out Entity_Id;
377       SI          : Node_Id;
378       Related_Nod : Node_Id;
379       Related_Id  : Entity_Id;
380       Suffix      : Character);
381    --  Apply a list of index constraints to an unconstrained array type. The
382    --  first parameter is the entity for the resulting subtype. A value of
383    --  Empty for Def_Id indicates that an implicit type must be created, but
384    --  creation is delayed (and must be done by this procedure) because other
385    --  subsidiary implicit types must be created first (which is why Def_Id
386    --  is an in/out parameter). The second parameter is a subtype indication
387    --  node for the constrained array to be created (e.g. something of the
388    --  form string (1 .. 10)). Related_Nod gives the place where this type
389    --  has to be inserted in the tree. The Related_Id and Suffix parameters
390    --  are used to build the associated Implicit type name.
391
392    procedure Constrain_Concurrent
393      (Def_Id      : in out Entity_Id;
394       SI          : Node_Id;
395       Related_Nod : Node_Id;
396       Related_Id  : Entity_Id;
397       Suffix      : Character);
398    --  Apply list of discriminant constraints to an unconstrained concurrent
399    --  type.
400    --
401    --    SI is the N_Subtype_Indication node containing the constraint and
402    --    the unconstrained type to constrain.
403    --
404    --    Def_Id is the entity for the resulting constrained subtype. A value
405    --    of Empty for Def_Id indicates that an implicit type must be created,
406    --    but creation is delayed (and must be done by this procedure) because
407    --    other subsidiary implicit types must be created first (which is why
408    --    Def_Id is an in/out parameter).
409    --
410    --    Related_Nod gives the place where this type has to be inserted
411    --    in the tree
412    --
413    --  The last two arguments are used to create its external name if needed.
414
415    function Constrain_Corresponding_Record
416      (Prot_Subt   : Entity_Id;
417       Corr_Rec    : Entity_Id;
418       Related_Nod : Node_Id;
419       Related_Id  : Entity_Id) return Entity_Id;
420    --  When constraining a protected type or task type with discriminants,
421    --  constrain the corresponding record with the same discriminant values.
422
423    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
424    --  Constrain a decimal fixed point type with a digits constraint and/or a
425    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
426
427    procedure Constrain_Discriminated_Type
428      (Def_Id      : Entity_Id;
429       S           : Node_Id;
430       Related_Nod : Node_Id;
431       For_Access  : Boolean := False);
432    --  Process discriminant constraints of composite type. Verify that values
433    --  have been provided for all discriminants, that the original type is
434    --  unconstrained, and that the types of the supplied expressions match
435    --  the discriminant types. The first three parameters are like in routine
436    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
437    --  of For_Access.
438
439    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
440    --  Constrain an enumeration type with a range constraint. This is identical
441    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
442
443    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
444    --  Constrain a floating point type with either a digits constraint
445    --  and/or a range constraint, building a E_Floating_Point_Subtype.
446
447    procedure Constrain_Index
448      (Index        : Node_Id;
449       S            : Node_Id;
450       Related_Nod  : Node_Id;
451       Related_Id   : Entity_Id;
452       Suffix       : Character;
453       Suffix_Index : Nat);
454    --  Process an index constraint in a constrained array declaration. The
455    --  constraint can be a subtype name, or a range with or without an explicit
456    --  subtype mark. The index is the corresponding index of the unconstrained
457    --  array. The Related_Id and Suffix parameters are used to build the
458    --  associated Implicit type name.
459
460    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
461    --  Build subtype of a signed or modular integer type
462
463    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
464    --  Constrain an ordinary fixed point type with a range constraint, and
465    --  build an E_Ordinary_Fixed_Point_Subtype entity.
466
467    procedure Copy_And_Swap (Priv, Full : Entity_Id);
468    --  Copy the Priv entity into the entity of its full declaration then swap
469    --  the two entities in such a manner that the former private type is now
470    --  seen as a full type.
471
472    procedure Decimal_Fixed_Point_Type_Declaration
473      (T   : Entity_Id;
474       Def : Node_Id);
475    --  Create a new decimal fixed point type, and apply the constraint to
476    --  obtain a subtype of this new type.
477
478    procedure Complete_Private_Subtype
479      (Priv        : Entity_Id;
480       Full        : Entity_Id;
481       Full_Base   : Entity_Id;
482       Related_Nod : Node_Id);
483    --  Complete the implicit full view of a private subtype by setting the
484    --  appropriate semantic fields. If the full view of the parent is a record
485    --  type, build constrained components of subtype.
486
487    procedure Derive_Interface_Subprograms
488      (Parent_Type : Entity_Id;
489       Tagged_Type : Entity_Id;
490       Ifaces_List : Elist_Id);
491    --  Ada 2005 (AI-251): Derive primitives of abstract interface types that
492    --  are not immediate ancestors of Tagged type and associate them their
493    --  aliased primitive. Ifaces_List contains the abstract interface
494    --  primitives that have been derived from Parent_Type.
495
496    procedure Derived_Standard_Character
497      (N             : Node_Id;
498       Parent_Type   : Entity_Id;
499       Derived_Type  : Entity_Id);
500    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
501    --  derivations from types Standard.Character and Standard.Wide_Character.
502
503    procedure Derived_Type_Declaration
504      (T             : Entity_Id;
505       N             : Node_Id;
506       Is_Completion : Boolean);
507    --  Process a derived type declaration. This routine will invoke
508    --  Build_Derived_Type to process the actual derived type definition.
509    --  Parameters N and Is_Completion have the same meaning as in
510    --  Build_Derived_Type. T is the N_Defining_Identifier for the entity
511    --  defined in the N_Full_Type_Declaration node N, that is T is the derived
512    --  type.
513
514    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
515    --  Insert each literal in symbol table, as an overloadable identifier. Each
516    --  enumeration type is mapped into a sequence of integers, and each literal
517    --  is defined as a constant with integer value. If any of the literals are
518    --  character literals, the type is a character type, which means that
519    --  strings are legal aggregates for arrays of components of the type.
520
521    function Expand_To_Stored_Constraint
522      (Typ        : Entity_Id;
523       Constraint : Elist_Id) return Elist_Id;
524    --  Given a Constraint (i.e. a list of expressions) on the discriminants of
525    --  Typ, expand it into a constraint on the stored discriminants and return
526    --  the new list of expressions constraining the stored discriminants.
527
528    function Find_Type_Of_Object
529      (Obj_Def     : Node_Id;
530       Related_Nod : Node_Id) return Entity_Id;
531    --  Get type entity for object referenced by Obj_Def, attaching the
532    --  implicit types generated to Related_Nod
533
534    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
535    --  Create a new float, and apply the constraint to obtain subtype of it
536
537    function Has_Range_Constraint (N : Node_Id) return Boolean;
538    --  Given an N_Subtype_Indication node N, return True if a range constraint
539    --  is present, either directly, or as part of a digits or delta constraint.
540    --  In addition, a digits constraint in the decimal case returns True, since
541    --  it establishes a default range if no explicit range is present.
542
543    function Inherit_Components
544      (N             : Node_Id;
545       Parent_Base   : Entity_Id;
546       Derived_Base  : Entity_Id;
547       Is_Tagged     : Boolean;
548       Inherit_Discr : Boolean;
549       Discs         : Elist_Id) return Elist_Id;
550    --  Called from Build_Derived_Record_Type to inherit the components of
551    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
552    --  For more information on derived types and component inheritance please
553    --  consult the comment above the body of Build_Derived_Record_Type.
554    --
555    --    N is the original derived type declaration
556    --
557    --    Is_Tagged is set if we are dealing with tagged types
558    --
559    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
560    --    Parent_Base, otherwise no discriminants are inherited.
561    --
562    --    Discs gives the list of constraints that apply to Parent_Base in the
563    --    derived type declaration. If Discs is set to No_Elist, then we have
564    --    the following situation:
565    --
566    --      type Parent (D1..Dn : ..) is [tagged] record ...;
567    --      type Derived is new Parent [with ...];
568    --
569    --    which gets treated as
570    --
571    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
572    --
573    --  For untagged types the returned value is an association list. The list
574    --  starts from the association (Parent_Base => Derived_Base), and then it
575    --  contains a sequence of the associations of the form
576    --
577    --    (Old_Component => New_Component),
578    --
579    --  where Old_Component is the Entity_Id of a component in Parent_Base and
580    --  New_Component is the Entity_Id of the corresponding component in
581    --  Derived_Base. For untagged records, this association list is needed when
582    --  copying the record declaration for the derived base. In the tagged case
583    --  the value returned is irrelevant.
584
585    function Is_Valid_Constraint_Kind
586      (T_Kind          : Type_Kind;
587       Constraint_Kind : Node_Kind) return Boolean;
588    --  Returns True if it is legal to apply the given kind of constraint to the
589    --  given kind of type (index constraint to an array type, for example).
590
591    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
592    --  Create new modular type. Verify that modulus is in  bounds and is
593    --  a power of two (implementation restriction).
594
595    procedure New_Concatenation_Op (Typ : Entity_Id);
596    --  Create an abbreviated declaration for an operator in order to
597    --  materialize concatenation on array types.
598
599    procedure Ordinary_Fixed_Point_Type_Declaration
600      (T   : Entity_Id;
601       Def : Node_Id);
602    --  Create a new ordinary fixed point type, and apply the constraint to
603    --  obtain subtype of it.
604
605    procedure Prepare_Private_Subtype_Completion
606      (Id          : Entity_Id;
607       Related_Nod : Node_Id);
608    --  Id is a subtype of some private type. Creates the full declaration
609    --  associated with Id whenever possible, i.e. when the full declaration
610    --  of the base type is already known. Records each subtype into
611    --  Private_Dependents of the base type.
612
613    procedure Process_Incomplete_Dependents
614      (N      : Node_Id;
615       Full_T : Entity_Id;
616       Inc_T  : Entity_Id);
617    --  Process all entities that depend on an incomplete type. There include
618    --  subtypes, subprogram types that mention the incomplete type in their
619    --  profiles, and subprogram with access parameters that designate the
620    --  incomplete type.
621
622    --  Inc_T is the defining identifier of an incomplete type declaration, its
623    --  Ekind is E_Incomplete_Type.
624    --
625    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
626    --
627    --    Full_T is N's defining identifier.
628    --
629    --  Subtypes of incomplete types with discriminants are completed when the
630    --  parent type is. This is simpler than private subtypes, because they can
631    --  only appear in the same scope, and there is no need to exchange views.
632    --  Similarly, access_to_subprogram types may have a parameter or a return
633    --  type that is an incomplete type, and that must be replaced with the
634    --  full type.
635
636    --  If the full type is tagged, subprogram with access parameters that
637    --  designated the incomplete may be primitive operations of the full type,
638    --  and have to be processed accordingly.
639
640    procedure Process_Real_Range_Specification (Def : Node_Id);
641    --  Given the type definition for a real type, this procedure processes
642    --  and checks the real range specification of this type definition if
643    --  one is present. If errors are found, error messages are posted, and
644    --  the Real_Range_Specification of Def is reset to Empty.
645
646    procedure Record_Type_Declaration
647      (T    : Entity_Id;
648       N    : Node_Id;
649       Prev : Entity_Id);
650    --  Process a record type declaration (for both untagged and tagged
651    --  records). Parameters T and N are exactly like in procedure
652    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
653    --  for this routine. If this is the completion of an incomplete type
654    --  declaration, Prev is the entity of the incomplete declaration, used for
655    --  cross-referencing. Otherwise Prev = T.
656
657    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
658    --  This routine is used to process the actual record type definition
659    --  (both for untagged and tagged records). Def is a record type
660    --  definition node. This procedure analyzes the components in this
661    --  record type definition. Prev_T is the entity for the enclosing record
662    --  type. It is provided so that its Has_Task flag can be set if any of
663    --  the component have Has_Task set. If the declaration is the completion
664    --  of an incomplete type declaration, Prev_T is the original incomplete
665    --  type, whose full view is the record type.
666
667    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
668    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
669    --  build a copy of the declaration tree of the parent, and we create
670    --  independently the list of components for the derived type. Semantic
671    --  information uses the component entities, but record representation
672    --  clauses are validated on the declaration tree. This procedure replaces
673    --  discriminants and components in the declaration with those that have
674    --  been created by Inherit_Components.
675
676    procedure Set_Fixed_Range
677      (E   : Entity_Id;
678       Loc : Source_Ptr;
679       Lo  : Ureal;
680       Hi  : Ureal);
681    --  Build a range node with the given bounds and set it as the Scalar_Range
682    --  of the given fixed-point type entity. Loc is the source location used
683    --  for the constructed range. See body for further details.
684
685    procedure Set_Scalar_Range_For_Subtype
686      (Def_Id : Entity_Id;
687       R      : Node_Id;
688       Subt   : Entity_Id);
689    --  This routine is used to set the scalar range field for a subtype given
690    --  Def_Id, the entity for the subtype, and R, the range expression for the
691    --  scalar range. Subt provides the parent subtype to be used to analyze,
692    --  resolve, and check the given range.
693
694    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
695    --  Create a new signed integer entity, and apply the constraint to obtain
696    --  the required first named subtype of this type.
697
698    procedure Set_Stored_Constraint_From_Discriminant_Constraint
699      (E : Entity_Id);
700    --  E is some record type. This routine computes E's Stored_Constraint
701    --  from its Discriminant_Constraint.
702
703    -----------------------
704    -- Access_Definition --
705    -----------------------
706
707    function Access_Definition
708      (Related_Nod : Node_Id;
709       N           : Node_Id) return Entity_Id
710    is
711       Loc        : constant Source_Ptr := Sloc (Related_Nod);
712       Anon_Type  : Entity_Id;
713       Anon_Scope : Entity_Id;
714       Desig_Type : Entity_Id;
715       Decl       : Entity_Id;
716
717    begin
718       if Is_Entry (Current_Scope)
719         and then Is_Task_Type (Etype (Scope (Current_Scope)))
720       then
721          Error_Msg_N ("task entries cannot have access parameters", N);
722          return Empty;
723       end if;
724
725       --  Ada 2005: for an object declaration the corresponding anonymous
726       --  type is declared in the current scope.
727
728       --  If the access definition is the return type of another access to
729       --  function, scope is the current one, because it is the one of the
730       --  current type declaration.
731
732       if Nkind (Related_Nod) = N_Object_Declaration
733         or else Nkind (Related_Nod) = N_Access_Function_Definition
734       then
735          Anon_Scope := Current_Scope;
736
737       --  For the anonymous function result case, retrieve the scope of the
738       --  function specification's associated entity rather than using the
739       --  current scope. The current scope will be the function itself if the
740       --  formal part is currently being analyzed, but will be the parent scope
741       --  in the case of a parameterless function, and we always want to use
742       --  the function's parent scope. Finally, if the function is a child
743       --  unit, we must traverse the the tree to retrieve the proper entity.
744
745       elsif Nkind (Related_Nod) = N_Function_Specification
746          and then Nkind (Parent (N)) /= N_Parameter_Specification
747       then
748          --  If the current scope is a protected type, the anonymous access
749          --  is associated with one of the protected operations, and must
750          --  be available in the scope that encloses the protected declaration.
751          --  Otherwise the type is is in the scope enclosing the subprogram.
752
753          if Ekind (Current_Scope) = E_Protected_Type then
754             Anon_Scope := Scope (Scope (Defining_Entity (Related_Nod)));
755          else
756             Anon_Scope := Scope (Defining_Entity (Related_Nod));
757          end if;
758
759       else
760          --  For access formals, access components, and access discriminants,
761          --  the scope is that of the enclosing declaration,
762
763          Anon_Scope := Scope (Current_Scope);
764       end if;
765
766       Anon_Type :=
767         Create_Itype
768          (E_Anonymous_Access_Type, Related_Nod, Scope_Id =>  Anon_Scope);
769
770       if All_Present (N)
771         and then Ada_Version >= Ada_05
772       then
773          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
774       end if;
775
776       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
777       --  the corresponding semantic routine
778
779       if Present (Access_To_Subprogram_Definition (N)) then
780          Access_Subprogram_Declaration
781            (T_Name => Anon_Type,
782             T_Def  => Access_To_Subprogram_Definition (N));
783
784          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
785             Set_Ekind
786               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
787          else
788             Set_Ekind
789               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
790          end if;
791
792          --  If the anonymous access is associated with a protected operation
793          --  create a reference to it after the enclosing protected definition
794          --  because the itype will be used in the subsequent bodies.
795
796          if Ekind (Current_Scope) = E_Protected_Type then
797             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
798          end if;
799
800          return Anon_Type;
801       end if;
802
803       Find_Type (Subtype_Mark (N));
804       Desig_Type := Entity (Subtype_Mark (N));
805
806       Set_Directly_Designated_Type
807                              (Anon_Type, Desig_Type);
808       Set_Etype              (Anon_Type, Anon_Type);
809       Init_Size_Align        (Anon_Type);
810       Set_Depends_On_Private (Anon_Type, Has_Private_Component (Anon_Type));
811
812       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
813       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
814       --  the null value is allowed. In Ada 95 the null value is never allowed.
815
816       if Ada_Version >= Ada_05 then
817          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
818       else
819          Set_Can_Never_Be_Null (Anon_Type, True);
820       end if;
821
822       --  The anonymous access type is as public as the discriminated type or
823       --  subprogram that defines it. It is imported (for back-end purposes)
824       --  if the designated type is.
825
826       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
827
828       --  Ada 2005 (AI-50217): Propagate the attribute that indicates that the
829       --  designated type comes from the limited view.
830
831       Set_From_With_Type (Anon_Type, From_With_Type (Desig_Type));
832
833       --  Ada 2005 (AI-231): Propagate the access-constant attribute
834
835       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
836
837       --  The context is either a subprogram declaration, object declaration,
838       --  or an access discriminant, in a private or a full type declaration.
839       --  In the case of a subprogram, if the designated type is incomplete,
840       --  the operation will be a primitive operation of the full type, to be
841       --  updated subsequently. If the type is imported through a limited_with
842       --  clause, the subprogram is not a primitive operation of the type
843       --  (which is declared elsewhere in some other scope).
844
845       if Ekind (Desig_Type) = E_Incomplete_Type
846         and then not From_With_Type (Desig_Type)
847         and then Is_Overloadable (Current_Scope)
848       then
849          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
850          Set_Has_Delayed_Freeze (Current_Scope);
851       end if;
852
853       --  Ada 2005: if the designated type is an interface that may contain
854       --  tasks, create a Master entity for the declaration. This must be done
855       --  before expansion of the full declaration, because the declaration may
856       --  include an expression that is an allocator, whose expansion needs the
857       --  proper Master for the created tasks.
858
859       if Nkind (Related_Nod) = N_Object_Declaration
860          and then Expander_Active
861       then
862          if Is_Interface (Desig_Type)
863            and then Is_Limited_Record (Desig_Type)
864          then
865             Build_Class_Wide_Master (Anon_Type);
866
867          --  Similarly, if the type is an anonymous access that designates
868          --  tasks, create a master entity for it in the current context.
869
870          elsif Has_Task (Desig_Type)
871            and then Comes_From_Source (Related_Nod)
872          then
873             if not Has_Master_Entity (Current_Scope) then
874                Decl :=
875                  Make_Object_Declaration (Loc,
876                    Defining_Identifier =>
877                      Make_Defining_Identifier (Loc, Name_uMaster),
878                    Constant_Present => True,
879                    Object_Definition =>
880                      New_Reference_To (RTE (RE_Master_Id), Loc),
881                    Expression =>
882                      Make_Explicit_Dereference (Loc,
883                        New_Reference_To (RTE (RE_Current_Master), Loc)));
884
885                Insert_Before (Related_Nod, Decl);
886                Analyze (Decl);
887
888                Set_Master_Id (Anon_Type, Defining_Identifier (Decl));
889                Set_Has_Master_Entity (Current_Scope);
890             else
891                Build_Master_Renaming (Related_Nod, Anon_Type);
892             end if;
893          end if;
894       end if;
895
896       --  For a private component of a protected type, it is imperative that
897       --  the back-end elaborate the type immediately after the protected
898       --  declaration, because this type will be used in the declarations
899       --  created for the component within each protected body, so we must
900       --  create an itype reference for it now.
901
902       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
903          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
904       end if;
905
906       return Anon_Type;
907    end Access_Definition;
908
909    -----------------------------------
910    -- Access_Subprogram_Declaration --
911    -----------------------------------
912
913    procedure Access_Subprogram_Declaration
914      (T_Name : Entity_Id;
915       T_Def  : Node_Id)
916    is
917       Formals : constant List_Id := Parameter_Specifications (T_Def);
918       Formal  : Entity_Id;
919       D_Ityp  : Node_Id;
920
921       Desig_Type : constant Entity_Id :=
922                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
923
924    begin
925       --  Associate the Itype node with the inner full-type declaration or
926       --  subprogram spec. This is required to handle nested anonymous
927       --  declarations. For example:
928
929       --      procedure P
930       --       (X : access procedure
931       --                     (Y : access procedure
932       --                                   (Z : access T)))
933
934       D_Ityp := Associated_Node_For_Itype (Desig_Type);
935       while Nkind (D_Ityp) /= N_Full_Type_Declaration
936          and then Nkind (D_Ityp) /= N_Private_Type_Declaration
937          and then Nkind (D_Ityp) /= N_Private_Extension_Declaration
938          and then Nkind (D_Ityp) /= N_Procedure_Specification
939          and then Nkind (D_Ityp) /= N_Function_Specification
940          and then Nkind (D_Ityp) /= N_Object_Declaration
941          and then Nkind (D_Ityp) /= N_Object_Renaming_Declaration
942          and then Nkind (D_Ityp) /= N_Formal_Type_Declaration
943          and then Nkind (D_Ityp) /= N_Task_Type_Declaration
944          and then Nkind (D_Ityp) /= N_Protected_Type_Declaration
945       loop
946          D_Ityp := Parent (D_Ityp);
947          pragma Assert (D_Ityp /= Empty);
948       end loop;
949
950       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
951
952       if Nkind (D_Ityp) = N_Procedure_Specification
953         or else Nkind (D_Ityp) = N_Function_Specification
954       then
955          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
956
957       elsif Nkind (D_Ityp) = N_Full_Type_Declaration
958         or else Nkind (D_Ityp) = N_Object_Declaration
959         or else Nkind (D_Ityp) = N_Object_Renaming_Declaration
960         or else Nkind (D_Ityp) = N_Formal_Type_Declaration
961       then
962          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
963       end if;
964
965       if Nkind (T_Def) = N_Access_Function_Definition then
966          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
967
968             declare
969                Acc : constant Node_Id := Result_Definition (T_Def);
970
971             begin
972                if Present (Access_To_Subprogram_Definition (Acc))
973                  and then
974                    Protected_Present (Access_To_Subprogram_Definition (Acc))
975                then
976                   Set_Etype
977                     (Desig_Type,
978                        Replace_Anonymous_Access_To_Protected_Subprogram
979                          (T_Def));
980
981                else
982                   Set_Etype
983                     (Desig_Type,
984                        Access_Definition (T_Def, Result_Definition (T_Def)));
985                end if;
986             end;
987
988          else
989             Analyze (Result_Definition (T_Def));
990             Set_Etype (Desig_Type, Entity (Result_Definition (T_Def)));
991          end if;
992
993          if not (Is_Type (Etype (Desig_Type))) then
994             Error_Msg_N
995               ("expect type in function specification",
996                Result_Definition (T_Def));
997          end if;
998
999       else
1000          Set_Etype (Desig_Type, Standard_Void_Type);
1001       end if;
1002
1003       if Present (Formals) then
1004          Push_Scope (Desig_Type);
1005          Process_Formals (Formals, Parent (T_Def));
1006
1007          --  A bit of a kludge here, End_Scope requires that the parent
1008          --  pointer be set to something reasonable, but Itypes don't have
1009          --  parent pointers. So we set it and then unset it ??? If and when
1010          --  Itypes have proper parent pointers to their declarations, this
1011          --  kludge can be removed.
1012
1013          Set_Parent (Desig_Type, T_Name);
1014          End_Scope;
1015          Set_Parent (Desig_Type, Empty);
1016       end if;
1017
1018       --  The return type and/or any parameter type may be incomplete. Mark
1019       --  the subprogram_type as depending on the incomplete type, so that
1020       --  it can be updated when the full type declaration is seen. This
1021       --  only applies to incomplete types declared in some enclosing scope,
1022       --  not to limited views from other packages.
1023
1024       if Present (Formals) then
1025          Formal := First_Formal (Desig_Type);
1026          while Present (Formal) loop
1027             if Ekind (Formal) /= E_In_Parameter
1028               and then Nkind (T_Def) = N_Access_Function_Definition
1029             then
1030                Error_Msg_N ("functions can only have IN parameters", Formal);
1031             end if;
1032
1033             if Ekind (Etype (Formal)) = E_Incomplete_Type
1034               and then In_Open_Scopes (Scope (Etype (Formal)))
1035             then
1036                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1037                Set_Has_Delayed_Freeze (Desig_Type);
1038             end if;
1039
1040             Next_Formal (Formal);
1041          end loop;
1042       end if;
1043
1044       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1045         and then not Has_Delayed_Freeze (Desig_Type)
1046       then
1047          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1048          Set_Has_Delayed_Freeze (Desig_Type);
1049       end if;
1050
1051       Check_Delayed_Subprogram (Desig_Type);
1052
1053       if Protected_Present (T_Def) then
1054          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1055          Set_Convention (Desig_Type, Convention_Protected);
1056       else
1057          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1058       end if;
1059
1060       Set_Etype                    (T_Name, T_Name);
1061       Init_Size_Align              (T_Name);
1062       Set_Directly_Designated_Type (T_Name, Desig_Type);
1063
1064       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1065
1066       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1067
1068       Check_Restriction (No_Access_Subprograms, T_Def);
1069    end Access_Subprogram_Declaration;
1070
1071    ----------------------------
1072    -- Access_Type_Declaration --
1073    ----------------------------
1074
1075    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1076       S : constant Node_Id := Subtype_Indication (Def);
1077       P : constant Node_Id := Parent (Def);
1078
1079       Desig : Entity_Id;
1080       --  Designated type
1081
1082    begin
1083       --  Check for permissible use of incomplete type
1084
1085       if Nkind (S) /= N_Subtype_Indication then
1086          Analyze (S);
1087
1088          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1089             Set_Directly_Designated_Type (T, Entity (S));
1090          else
1091             Set_Directly_Designated_Type (T,
1092               Process_Subtype (S, P, T, 'P'));
1093          end if;
1094
1095       else
1096          Set_Directly_Designated_Type (T,
1097            Process_Subtype (S, P, T, 'P'));
1098       end if;
1099
1100       if All_Present (Def) or Constant_Present (Def) then
1101          Set_Ekind (T, E_General_Access_Type);
1102       else
1103          Set_Ekind (T, E_Access_Type);
1104       end if;
1105
1106       if Base_Type (Designated_Type (T)) = T then
1107          Error_Msg_N ("access type cannot designate itself", S);
1108
1109       --  In Ada 2005, the type may have a limited view through some unit
1110       --  in its own context, allowing the following circularity that cannot
1111       --  be detected earlier
1112
1113       elsif Is_Class_Wide_Type (Designated_Type (T))
1114         and then Etype (Designated_Type (T)) = T
1115       then
1116          Error_Msg_N
1117            ("access type cannot designate its own classwide type", S);
1118
1119          --  Clean up indication of tagged status to prevent cascaded errors
1120
1121          Set_Is_Tagged_Type (T, False);
1122       end if;
1123
1124       Set_Etype (T, T);
1125
1126       --  If the type has appeared already in a with_type clause, it is
1127       --  frozen and the pointer size is already set. Else, initialize.
1128
1129       if not From_With_Type (T) then
1130          Init_Size_Align (T);
1131       end if;
1132
1133       Desig := Designated_Type (T);
1134
1135       --  If designated type is an imported tagged type, indicate that the
1136       --  access type is also imported, and therefore restricted in its use.
1137       --  The access type may already be imported, so keep setting otherwise.
1138
1139       --  Ada 2005 (AI-50217): If the non-limited view of the designated type
1140       --  is available, use it as the designated type of the access type, so
1141       --  that the back-end gets a usable entity.
1142
1143       if From_With_Type (Desig)
1144         and then Ekind (Desig) /= E_Access_Type
1145       then
1146          Set_From_With_Type (T);
1147       end if;
1148
1149       --  Note that Has_Task is always false, since the access type itself
1150       --  is not a task type. See Einfo for more description on this point.
1151       --  Exactly the same consideration applies to Has_Controlled_Component.
1152
1153       Set_Has_Task (T, False);
1154       Set_Has_Controlled_Component (T, False);
1155
1156       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1157       --  attributes
1158
1159       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1160       Set_Is_Access_Constant (T, Constant_Present (Def));
1161    end Access_Type_Declaration;
1162
1163    ----------------------------------
1164    -- Add_Interface_Tag_Components --
1165    ----------------------------------
1166
1167    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1168       Loc      : constant Source_Ptr := Sloc (N);
1169       Elmt     : Elmt_Id;
1170       Ext      : Node_Id;
1171       L        : List_Id;
1172       Last_Tag : Node_Id;
1173       Comp     : Node_Id;
1174
1175       procedure Add_Sync_Iface_Tags (T : Entity_Id);
1176       --  Local subprogram used to recursively climb through the parents
1177       --  of T to add the tags of all the progenitor interfaces.
1178
1179       procedure Add_Tag (Iface : Entity_Id);
1180       --  Add tag for one of the progenitor interfaces
1181
1182       -------------------------
1183       -- Add_Sync_Iface_Tags --
1184       -------------------------
1185
1186       procedure Add_Sync_Iface_Tags (T : Entity_Id) is
1187       begin
1188          if Etype (T) /= T then
1189             Add_Sync_Iface_Tags (Etype (T));
1190          end if;
1191
1192          Elmt := First_Elmt (Abstract_Interfaces (T));
1193          while Present (Elmt) loop
1194             Add_Tag (Node (Elmt));
1195             Next_Elmt (Elmt);
1196          end loop;
1197       end Add_Sync_Iface_Tags;
1198
1199       -------------
1200       -- Add_Tag --
1201       -------------
1202
1203       procedure Add_Tag (Iface : Entity_Id) is
1204          Decl   : Node_Id;
1205          Def    : Node_Id;
1206          Tag    : Entity_Id;
1207          Offset : Entity_Id;
1208
1209       begin
1210          pragma Assert (Is_Tagged_Type (Iface)
1211            and then Is_Interface (Iface));
1212
1213          Def :=
1214            Make_Component_Definition (Loc,
1215              Aliased_Present    => True,
1216              Subtype_Indication =>
1217                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1218
1219          Tag := Make_Defining_Identifier (Loc, New_Internal_Name ('V'));
1220
1221          Decl :=
1222            Make_Component_Declaration (Loc,
1223              Defining_Identifier  => Tag,
1224              Component_Definition => Def);
1225
1226          Analyze_Component_Declaration (Decl);
1227
1228          Set_Analyzed (Decl);
1229          Set_Ekind               (Tag, E_Component);
1230          Set_Is_Tag              (Tag);
1231          Set_Is_Aliased          (Tag);
1232          Set_Related_Interface   (Tag, Iface);
1233          Init_Component_Location (Tag);
1234
1235          pragma Assert (Is_Frozen (Iface));
1236
1237          Set_DT_Entry_Count    (Tag,
1238            DT_Entry_Count (First_Entity (Iface)));
1239
1240          if No (Last_Tag) then
1241             Prepend (Decl, L);
1242          else
1243             Insert_After (Last_Tag, Decl);
1244          end if;
1245
1246          Last_Tag := Decl;
1247
1248          --  If the ancestor has discriminants we need to give special support
1249          --  to store the offset_to_top value of the secondary dispatch tables.
1250          --  For this purpose we add a supplementary component just after the
1251          --  field that contains the tag associated with each secondary DT.
1252
1253          if Typ /= Etype (Typ)
1254            and then Has_Discriminants (Etype (Typ))
1255          then
1256             Def :=
1257               Make_Component_Definition (Loc,
1258                 Subtype_Indication =>
1259                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1260
1261             Offset :=
1262               Make_Defining_Identifier (Loc, New_Internal_Name ('V'));
1263
1264             Decl :=
1265               Make_Component_Declaration (Loc,
1266                 Defining_Identifier  => Offset,
1267                 Component_Definition => Def);
1268
1269             Analyze_Component_Declaration (Decl);
1270
1271             Set_Analyzed (Decl);
1272             Set_Ekind               (Offset, E_Component);
1273             Set_Is_Aliased          (Offset);
1274             Set_Related_Interface   (Offset, Iface);
1275             Init_Component_Location (Offset);
1276             Insert_After (Last_Tag, Decl);
1277             Last_Tag := Decl;
1278          end if;
1279       end Add_Tag;
1280
1281       --  Local variables
1282
1283       Iface_List : List_Id;
1284
1285    --  Start of processing for Add_Interface_Tag_Components
1286
1287    begin
1288       if not RTE_Available (RE_Interface_Tag) then
1289          Error_Msg
1290            ("(Ada 2005) interface types not supported by this run-time!",
1291             Sloc (N));
1292          return;
1293       end if;
1294
1295       if Ekind (Typ) /= E_Record_Type
1296         or else (Is_Concurrent_Record_Type (Typ)
1297                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1298         or else (not Is_Concurrent_Record_Type (Typ)
1299                   and then No (Abstract_Interfaces (Typ))
1300                   and then Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1301       then
1302          return;
1303       end if;
1304
1305       --  Find the current last tag
1306
1307       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1308          Ext := Record_Extension_Part (Type_Definition (N));
1309       else
1310          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1311          Ext := Type_Definition (N);
1312       end if;
1313
1314       Last_Tag := Empty;
1315
1316       if not (Present (Component_List (Ext))) then
1317          Set_Null_Present (Ext, False);
1318          L := New_List;
1319          Set_Component_List (Ext,
1320            Make_Component_List (Loc,
1321              Component_Items => L,
1322              Null_Present => False));
1323       else
1324          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1325             L := Component_Items
1326                    (Component_List
1327                      (Record_Extension_Part
1328                        (Type_Definition (N))));
1329          else
1330             L := Component_Items
1331                    (Component_List
1332                      (Type_Definition (N)));
1333          end if;
1334
1335          --  Find the last tag component
1336
1337          Comp := First (L);
1338          while Present (Comp) loop
1339             if Nkind (Comp) = N_Component_Declaration
1340               and then Is_Tag (Defining_Identifier (Comp))
1341             then
1342                Last_Tag := Comp;
1343             end if;
1344
1345             Next (Comp);
1346          end loop;
1347       end if;
1348
1349       --  At this point L references the list of components and Last_Tag
1350       --  references the current last tag (if any). Now we add the tag
1351       --  corresponding with all the interfaces that are not implemented
1352       --  by the parent.
1353
1354       if Is_Concurrent_Record_Type (Typ) then
1355          Iface_List := Abstract_Interface_List (Typ);
1356
1357          if Is_Non_Empty_List (Iface_List) then
1358             Add_Sync_Iface_Tags (Etype (First (Iface_List)));
1359          end if;
1360       end if;
1361
1362       if Present (Abstract_Interfaces (Typ)) then
1363          Elmt := First_Elmt (Abstract_Interfaces (Typ));
1364          while Present (Elmt) loop
1365             Add_Tag (Node (Elmt));
1366             Next_Elmt (Elmt);
1367          end loop;
1368       end if;
1369    end Add_Interface_Tag_Components;
1370
1371    -----------------------------------
1372    -- Analyze_Component_Declaration --
1373    -----------------------------------
1374
1375    procedure Analyze_Component_Declaration (N : Node_Id) is
1376       Id : constant Entity_Id := Defining_Identifier (N);
1377       E  : constant Node_Id   := Expression (N);
1378       T  : Entity_Id;
1379       P  : Entity_Id;
1380
1381       function Contains_POC (Constr : Node_Id) return Boolean;
1382       --  Determines whether a constraint uses the discriminant of a record
1383       --  type thus becoming a per-object constraint (POC).
1384
1385       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1386       --  Typ is the type of the current component, check whether this type is
1387       --  a limited type. Used to validate declaration against that of
1388       --  enclosing record.
1389
1390       ------------------
1391       -- Contains_POC --
1392       ------------------
1393
1394       function Contains_POC (Constr : Node_Id) return Boolean is
1395       begin
1396          --  Prevent cascaded errors
1397
1398          if Error_Posted (Constr) then
1399             return False;
1400          end if;
1401
1402          case Nkind (Constr) is
1403             when N_Attribute_Reference =>
1404                return
1405                  Attribute_Name (Constr) = Name_Access
1406                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1407
1408             when N_Discriminant_Association =>
1409                return Denotes_Discriminant (Expression (Constr));
1410
1411             when N_Identifier =>
1412                return Denotes_Discriminant (Constr);
1413
1414             when N_Index_Or_Discriminant_Constraint =>
1415                declare
1416                   IDC : Node_Id;
1417
1418                begin
1419                   IDC := First (Constraints (Constr));
1420                   while Present (IDC) loop
1421
1422                      --  One per-object constraint is sufficient
1423
1424                      if Contains_POC (IDC) then
1425                         return True;
1426                      end if;
1427
1428                      Next (IDC);
1429                   end loop;
1430
1431                   return False;
1432                end;
1433
1434             when N_Range =>
1435                return Denotes_Discriminant (Low_Bound (Constr))
1436                         or else
1437                       Denotes_Discriminant (High_Bound (Constr));
1438
1439             when N_Range_Constraint =>
1440                return Denotes_Discriminant (Range_Expression (Constr));
1441
1442             when others =>
1443                return False;
1444
1445          end case;
1446       end Contains_POC;
1447
1448       ----------------------
1449       -- Is_Known_Limited --
1450       ----------------------
1451
1452       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1453          P : constant Entity_Id := Etype (Typ);
1454          R : constant Entity_Id := Root_Type (Typ);
1455
1456       begin
1457          if Is_Limited_Record (Typ) then
1458             return True;
1459
1460          --  If the root type is limited (and not a limited interface)
1461          --  so is the current type
1462
1463          elsif Is_Limited_Record (R)
1464            and then
1465              (not Is_Interface (R)
1466                or else not Is_Limited_Interface (R))
1467          then
1468             return True;
1469
1470          --  Else the type may have a limited interface progenitor, but a
1471          --  limited record parent.
1472
1473          elsif R /= P
1474            and then Is_Limited_Record (P)
1475          then
1476             return True;
1477
1478          else
1479             return False;
1480          end if;
1481       end Is_Known_Limited;
1482
1483    --  Start of processing for Analyze_Component_Declaration
1484
1485    begin
1486       Generate_Definition (Id);
1487       Enter_Name (Id);
1488
1489       if Present (Subtype_Indication (Component_Definition (N))) then
1490          T := Find_Type_Of_Object
1491                 (Subtype_Indication (Component_Definition (N)), N);
1492
1493       --  Ada 2005 (AI-230): Access Definition case
1494
1495       else
1496          pragma Assert (Present
1497                           (Access_Definition (Component_Definition (N))));
1498
1499          T := Access_Definition
1500                 (Related_Nod => N,
1501                  N => Access_Definition (Component_Definition (N)));
1502          Set_Is_Local_Anonymous_Access (T);
1503
1504          --  Ada 2005 (AI-254)
1505
1506          if Present (Access_To_Subprogram_Definition
1507                       (Access_Definition (Component_Definition (N))))
1508            and then Protected_Present (Access_To_Subprogram_Definition
1509                                         (Access_Definition
1510                                           (Component_Definition (N))))
1511          then
1512             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1513          end if;
1514       end if;
1515
1516       --  If the subtype is a constrained subtype of the enclosing record,
1517       --  (which must have a partial view) the back-end does not properly
1518       --  handle the recursion. Rewrite the component declaration with an
1519       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1520       --  the tree directly because side effects have already been removed from
1521       --  discriminant constraints.
1522
1523       if Ekind (T) = E_Access_Subtype
1524         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1525         and then Comes_From_Source (T)
1526         and then Nkind (Parent (T)) = N_Subtype_Declaration
1527         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1528       then
1529          Rewrite
1530            (Subtype_Indication (Component_Definition (N)),
1531              New_Copy_Tree (Subtype_Indication (Parent (T))));
1532          T := Find_Type_Of_Object
1533                  (Subtype_Indication (Component_Definition (N)), N);
1534       end if;
1535
1536       --  If the component declaration includes a default expression, then we
1537       --  check that the component is not of a limited type (RM 3.7(5)),
1538       --  and do the special preanalysis of the expression (see section on
1539       --  "Handling of Default and Per-Object Expressions" in the spec of
1540       --  package Sem).
1541
1542       if Present (E) then
1543          Analyze_Per_Use_Expression (E, T);
1544          Check_Initialization (T, E);
1545
1546          if Ada_Version >= Ada_05
1547            and then Ekind (T) = E_Anonymous_Access_Type
1548          then
1549             --  Check RM 3.9.2(9): "if the expected type for an expression is
1550             --  an anonymous access-to-specific tagged type, then the object
1551             --  designated by the expression shall not be dynamically tagged
1552             --  unless it is a controlling operand in a call on a dispatching
1553             --  operation"
1554
1555             if Is_Tagged_Type (Directly_Designated_Type (T))
1556               and then
1557                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1558               and then
1559                 Ekind (Directly_Designated_Type (Etype (E))) =
1560                   E_Class_Wide_Type
1561             then
1562                Error_Msg_N
1563                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1564             end if;
1565
1566             --  (Ada 2005: AI-230): Accessibility check for anonymous
1567             --  components
1568
1569             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1570                Error_Msg_N
1571                  ("expression has deeper access level than component " &
1572                   "(RM 3.10.2 (12.2))", E);
1573             end if;
1574
1575             --  The initialization expression is a reference to an access
1576             --  discriminant. The type of the discriminant is always deeper
1577             --  than any access type.
1578
1579             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1580               and then Is_Entity_Name (E)
1581               and then Ekind (Entity (E)) = E_In_Parameter
1582               and then Present (Discriminal_Link (Entity (E)))
1583             then
1584                Error_Msg_N
1585                  ("discriminant has deeper accessibility level than target",
1586                   E);
1587             end if;
1588          end if;
1589       end if;
1590
1591       --  The parent type may be a private view with unknown discriminants,
1592       --  and thus unconstrained. Regular components must be constrained.
1593
1594       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1595          if Is_Class_Wide_Type (T) then
1596             Error_Msg_N
1597                ("class-wide subtype with unknown discriminants" &
1598                  " in component declaration",
1599                  Subtype_Indication (Component_Definition (N)));
1600          else
1601             Error_Msg_N
1602               ("unconstrained subtype in component declaration",
1603                Subtype_Indication (Component_Definition (N)));
1604          end if;
1605
1606       --  Components cannot be abstract, except for the special case of
1607       --  the _Parent field (case of extending an abstract tagged type)
1608
1609       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1610          Error_Msg_N ("type of a component cannot be abstract", N);
1611       end if;
1612
1613       Set_Etype (Id, T);
1614       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1615
1616       --  The component declaration may have a per-object constraint, set
1617       --  the appropriate flag in the defining identifier of the subtype.
1618
1619       if Present (Subtype_Indication (Component_Definition (N))) then
1620          declare
1621             Sindic : constant Node_Id :=
1622                        Subtype_Indication (Component_Definition (N));
1623
1624          begin
1625             if Nkind (Sindic) = N_Subtype_Indication
1626               and then Present (Constraint (Sindic))
1627               and then Contains_POC (Constraint (Sindic))
1628             then
1629                Set_Has_Per_Object_Constraint (Id);
1630             end if;
1631          end;
1632       end if;
1633
1634       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1635       --  out some static checks.
1636
1637       if Ada_Version >= Ada_05
1638         and then Can_Never_Be_Null (T)
1639       then
1640          Null_Exclusion_Static_Checks (N);
1641       end if;
1642
1643       --  If this component is private (or depends on a private type), flag the
1644       --  record type to indicate that some operations are not available.
1645
1646       P := Private_Component (T);
1647
1648       if Present (P) then
1649
1650          --  Check for circular definitions
1651
1652          if P = Any_Type then
1653             Set_Etype (Id, Any_Type);
1654
1655          --  There is a gap in the visibility of operations only if the
1656          --  component type is not defined in the scope of the record type.
1657
1658          elsif Scope (P) = Scope (Current_Scope) then
1659             null;
1660
1661          elsif Is_Limited_Type (P) then
1662             Set_Is_Limited_Composite (Current_Scope);
1663
1664          else
1665             Set_Is_Private_Composite (Current_Scope);
1666          end if;
1667       end if;
1668
1669       if P /= Any_Type
1670         and then Is_Limited_Type (T)
1671         and then Chars (Id) /= Name_uParent
1672         and then Is_Tagged_Type (Current_Scope)
1673       then
1674          if Is_Derived_Type (Current_Scope)
1675            and then not Is_Known_Limited (Current_Scope)
1676          then
1677             Error_Msg_N
1678               ("extension of nonlimited type cannot have limited components",
1679                N);
1680
1681             if Is_Interface (Root_Type (Current_Scope)) then
1682                Error_Msg_N
1683                  ("\limitedness is not inherited from limited interface", N);
1684                Error_Msg_N
1685                  ("\add LIMITED to type indication", N);
1686             end if;
1687
1688             Explain_Limited_Type (T, N);
1689             Set_Etype (Id, Any_Type);
1690             Set_Is_Limited_Composite (Current_Scope, False);
1691
1692          elsif not Is_Derived_Type (Current_Scope)
1693            and then not Is_Limited_Record (Current_Scope)
1694            and then not Is_Concurrent_Type (Current_Scope)
1695          then
1696             Error_Msg_N
1697               ("nonlimited tagged type cannot have limited components", N);
1698             Explain_Limited_Type (T, N);
1699             Set_Etype (Id, Any_Type);
1700             Set_Is_Limited_Composite (Current_Scope, False);
1701          end if;
1702       end if;
1703
1704       Set_Original_Record_Component (Id, Id);
1705    end Analyze_Component_Declaration;
1706
1707    --------------------------
1708    -- Analyze_Declarations --
1709    --------------------------
1710
1711    procedure Analyze_Declarations (L : List_Id) is
1712       D           : Node_Id;
1713       Freeze_From : Entity_Id := Empty;
1714       Next_Node   : Node_Id;
1715
1716       procedure Adjust_D;
1717       --  Adjust D not to include implicit label declarations, since these
1718       --  have strange Sloc values that result in elaboration check problems.
1719       --  (They have the sloc of the label as found in the source, and that
1720       --  is ahead of the current declarative part).
1721
1722       --------------
1723       -- Adjust_D --
1724       --------------
1725
1726       procedure Adjust_D is
1727       begin
1728          while Present (Prev (D))
1729            and then Nkind (D) = N_Implicit_Label_Declaration
1730          loop
1731             Prev (D);
1732          end loop;
1733       end Adjust_D;
1734
1735    --  Start of processing for Analyze_Declarations
1736
1737    begin
1738       D := First (L);
1739       while Present (D) loop
1740
1741          --  Complete analysis of declaration
1742
1743          Analyze (D);
1744          Next_Node := Next (D);
1745
1746          if No (Freeze_From) then
1747             Freeze_From := First_Entity (Current_Scope);
1748          end if;
1749
1750          --  At the end of a declarative part, freeze remaining entities
1751          --  declared in it. The end of the visible declarations of package
1752          --  specification is not the end of a declarative part if private
1753          --  declarations are present. The end of a package declaration is a
1754          --  freezing point only if it a library package. A task definition or
1755          --  protected type definition is not a freeze point either. Finally,
1756          --  we do not freeze entities in generic scopes, because there is no
1757          --  code generated for them and freeze nodes will be generated for
1758          --  the instance.
1759
1760          --  The end of a package instantiation is not a freeze point, but
1761          --  for now we make it one, because the generic body is inserted
1762          --  (currently) immediately after. Generic instantiations will not
1763          --  be a freeze point once delayed freezing of bodies is implemented.
1764          --  (This is needed in any case for early instantiations ???).
1765
1766          if No (Next_Node) then
1767             if Nkind (Parent (L)) = N_Component_List
1768               or else Nkind (Parent (L)) = N_Task_Definition
1769               or else Nkind (Parent (L)) = N_Protected_Definition
1770             then
1771                null;
1772
1773             elsif Nkind (Parent (L)) /= N_Package_Specification then
1774                if Nkind (Parent (L)) = N_Package_Body then
1775                   Freeze_From := First_Entity (Current_Scope);
1776                end if;
1777
1778                Adjust_D;
1779                Freeze_All (Freeze_From, D);
1780                Freeze_From := Last_Entity (Current_Scope);
1781
1782             elsif Scope (Current_Scope) /= Standard_Standard
1783               and then not Is_Child_Unit (Current_Scope)
1784               and then No (Generic_Parent (Parent (L)))
1785             then
1786                null;
1787
1788             elsif L /= Visible_Declarations (Parent (L))
1789                or else No (Private_Declarations (Parent (L)))
1790                or else Is_Empty_List (Private_Declarations (Parent (L)))
1791             then
1792                Adjust_D;
1793                Freeze_All (Freeze_From, D);
1794                Freeze_From := Last_Entity (Current_Scope);
1795             end if;
1796
1797          --  If next node is a body then freeze all types before the body.
1798          --  An exception occurs for some expander-generated bodies. If these
1799          --  are generated at places where in general language rules would not
1800          --  allow a freeze point, then we assume that the expander has
1801          --  explicitly checked that all required types are properly frozen,
1802          --  and we do not cause general freezing here. This special circuit
1803          --  is used when the encountered body is marked as having already
1804          --  been analyzed.
1805
1806          --  In all other cases (bodies that come from source, and expander
1807          --  generated bodies that have not been analyzed yet), freeze all
1808          --  types now. Note that in the latter case, the expander must take
1809          --  care to attach the bodies at a proper place in the tree so as to
1810          --  not cause unwanted freezing at that point.
1811
1812          elsif not Analyzed (Next_Node)
1813            and then (Nkind (Next_Node) = N_Subprogram_Body
1814              or else Nkind (Next_Node) = N_Entry_Body
1815              or else Nkind (Next_Node) = N_Package_Body
1816              or else Nkind (Next_Node) = N_Protected_Body
1817              or else Nkind (Next_Node) = N_Task_Body
1818              or else Nkind (Next_Node) in N_Body_Stub)
1819          then
1820             Adjust_D;
1821             Freeze_All (Freeze_From, D);
1822             Freeze_From := Last_Entity (Current_Scope);
1823          end if;
1824
1825          D := Next_Node;
1826       end loop;
1827    end Analyze_Declarations;
1828
1829    ----------------------------------
1830    -- Analyze_Incomplete_Type_Decl --
1831    ----------------------------------
1832
1833    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
1834       F : constant Boolean := Is_Pure (Current_Scope);
1835       T : Entity_Id;
1836
1837    begin
1838       Generate_Definition (Defining_Identifier (N));
1839
1840       --  Process an incomplete declaration. The identifier must not have been
1841       --  declared already in the scope. However, an incomplete declaration may
1842       --  appear in the private part of a package, for a private type that has
1843       --  already been declared.
1844
1845       --  In this case, the discriminants (if any) must match
1846
1847       T := Find_Type_Name (N);
1848
1849       Set_Ekind (T, E_Incomplete_Type);
1850       Init_Size_Align (T);
1851       Set_Is_First_Subtype (T, True);
1852       Set_Etype (T, T);
1853
1854       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
1855       --  incomplete types.
1856
1857       if Tagged_Present (N) then
1858          Set_Is_Tagged_Type (T);
1859          Make_Class_Wide_Type (T);
1860          Set_Primitive_Operations (T, New_Elmt_List);
1861       end if;
1862
1863       Push_Scope (T);
1864
1865       Set_Stored_Constraint (T, No_Elist);
1866
1867       if Present (Discriminant_Specifications (N)) then
1868          Process_Discriminants (N);
1869       end if;
1870
1871       End_Scope;
1872
1873       --  If the type has discriminants, non-trivial subtypes may be be
1874       --  declared before the full view of the type. The full views of those
1875       --  subtypes will be built after the full view of the type.
1876
1877       Set_Private_Dependents (T, New_Elmt_List);
1878       Set_Is_Pure (T, F);
1879    end Analyze_Incomplete_Type_Decl;
1880
1881    -----------------------------------
1882    -- Analyze_Interface_Declaration --
1883    -----------------------------------
1884
1885    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
1886       CW : constant Entity_Id := Class_Wide_Type (T);
1887
1888    begin
1889       Set_Is_Tagged_Type      (T);
1890
1891       Set_Is_Limited_Record   (T, Limited_Present (Def)
1892                                    or else Task_Present (Def)
1893                                    or else Protected_Present (Def)
1894                                    or else Synchronized_Present (Def));
1895
1896       --  Type is abstract if full declaration carries keyword, or if previous
1897       --  partial view did.
1898
1899       Set_Is_Abstract_Type (T);
1900       Set_Is_Interface     (T);
1901
1902       --  Type is a limited interface if it includes the keyword limited, task,
1903       --  protected, or synchronized.
1904
1905       Set_Is_Limited_Interface
1906         (T, Limited_Present (Def)
1907               or else Protected_Present (Def)
1908               or else Synchronized_Present (Def)
1909               or else Task_Present (Def));
1910
1911       Set_Is_Protected_Interface    (T, Protected_Present (Def));
1912       Set_Is_Task_Interface         (T, Task_Present (Def));
1913
1914       --  Type is a synchronized interface if it includes the keyword task,
1915       --  protected, or synchronized.
1916
1917       Set_Is_Synchronized_Interface
1918         (T, Synchronized_Present (Def)
1919               or else Protected_Present (Def)
1920               or else Task_Present (Def));
1921
1922       Set_Abstract_Interfaces       (T, New_Elmt_List);
1923       Set_Primitive_Operations      (T, New_Elmt_List);
1924
1925       --  Complete the decoration of the class-wide entity if it was already
1926       --  built (ie. during the creation of the limited view)
1927
1928       if Present (CW) then
1929          Set_Is_Interface (CW);
1930          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
1931          Set_Is_Protected_Interface    (CW, Is_Protected_Interface (T));
1932          Set_Is_Synchronized_Interface (CW, Is_Synchronized_Interface (T));
1933          Set_Is_Task_Interface         (CW, Is_Task_Interface (T));
1934       end if;
1935    end Analyze_Interface_Declaration;
1936
1937    -----------------------------
1938    -- Analyze_Itype_Reference --
1939    -----------------------------
1940
1941    --  Nothing to do. This node is placed in the tree only for the benefit of
1942    --  back end processing, and has no effect on the semantic processing.
1943
1944    procedure Analyze_Itype_Reference (N : Node_Id) is
1945    begin
1946       pragma Assert (Is_Itype (Itype (N)));
1947       null;
1948    end Analyze_Itype_Reference;
1949
1950    --------------------------------
1951    -- Analyze_Number_Declaration --
1952    --------------------------------
1953
1954    procedure Analyze_Number_Declaration (N : Node_Id) is
1955       Id    : constant Entity_Id := Defining_Identifier (N);
1956       E     : constant Node_Id   := Expression (N);
1957       T     : Entity_Id;
1958       Index : Interp_Index;
1959       It    : Interp;
1960
1961    begin
1962       Generate_Definition (Id);
1963       Enter_Name (Id);
1964
1965       --  This is an optimization of a common case of an integer literal
1966
1967       if Nkind (E) = N_Integer_Literal then
1968          Set_Is_Static_Expression (E, True);
1969          Set_Etype                (E, Universal_Integer);
1970
1971          Set_Etype     (Id, Universal_Integer);
1972          Set_Ekind     (Id, E_Named_Integer);
1973          Set_Is_Frozen (Id, True);
1974          return;
1975       end if;
1976
1977       Set_Is_Pure (Id, Is_Pure (Current_Scope));
1978
1979       --  Process expression, replacing error by integer zero, to avoid
1980       --  cascaded errors or aborts further along in the processing
1981
1982       --  Replace Error by integer zero, which seems least likely to
1983       --  cause cascaded errors.
1984
1985       if E = Error then
1986          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
1987          Set_Error_Posted (E);
1988       end if;
1989
1990       Analyze (E);
1991
1992       --  Verify that the expression is static and numeric. If
1993       --  the expression is overloaded, we apply the preference
1994       --  rule that favors root numeric types.
1995
1996       if not Is_Overloaded (E) then
1997          T := Etype (E);
1998
1999       else
2000          T := Any_Type;
2001
2002          Get_First_Interp (E, Index, It);
2003          while Present (It.Typ) loop
2004             if (Is_Integer_Type (It.Typ)
2005                  or else Is_Real_Type (It.Typ))
2006               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2007             then
2008                if T = Any_Type then
2009                   T := It.Typ;
2010
2011                elsif It.Typ = Universal_Real
2012                  or else It.Typ = Universal_Integer
2013                then
2014                   --  Choose universal interpretation over any other
2015
2016                   T := It.Typ;
2017                   exit;
2018                end if;
2019             end if;
2020
2021             Get_Next_Interp (Index, It);
2022          end loop;
2023       end if;
2024
2025       if Is_Integer_Type (T)  then
2026          Resolve (E, T);
2027          Set_Etype (Id, Universal_Integer);
2028          Set_Ekind (Id, E_Named_Integer);
2029
2030       elsif Is_Real_Type (T) then
2031
2032          --  Because the real value is converted to universal_real, this is a
2033          --  legal context for a universal fixed expression.
2034
2035          if T = Universal_Fixed then
2036             declare
2037                Loc  : constant Source_Ptr := Sloc (N);
2038                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2039                         Subtype_Mark =>
2040                           New_Occurrence_Of (Universal_Real, Loc),
2041                         Expression => Relocate_Node (E));
2042
2043             begin
2044                Rewrite (E, Conv);
2045                Analyze (E);
2046             end;
2047
2048          elsif T = Any_Fixed then
2049             Error_Msg_N ("illegal context for mixed mode operation", E);
2050
2051             --  Expression is of the form : universal_fixed * integer. Try to
2052             --  resolve as universal_real.
2053
2054             T := Universal_Real;
2055             Set_Etype (E, T);
2056          end if;
2057
2058          Resolve (E, T);
2059          Set_Etype (Id, Universal_Real);
2060          Set_Ekind (Id, E_Named_Real);
2061
2062       else
2063          Wrong_Type (E, Any_Numeric);
2064          Resolve (E, T);
2065
2066          Set_Etype               (Id, T);
2067          Set_Ekind               (Id, E_Constant);
2068          Set_Never_Set_In_Source (Id, True);
2069          Set_Is_True_Constant    (Id, True);
2070          return;
2071       end if;
2072
2073       if Nkind (E) = N_Integer_Literal
2074         or else Nkind (E) = N_Real_Literal
2075       then
2076          Set_Etype (E, Etype (Id));
2077       end if;
2078
2079       if not Is_OK_Static_Expression (E) then
2080          Flag_Non_Static_Expr
2081            ("non-static expression used in number declaration!", E);
2082          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2083          Set_Etype (E, Any_Type);
2084       end if;
2085    end Analyze_Number_Declaration;
2086
2087    --------------------------------
2088    -- Analyze_Object_Declaration --
2089    --------------------------------
2090
2091    procedure Analyze_Object_Declaration (N : Node_Id) is
2092       Loc   : constant Source_Ptr := Sloc (N);
2093       Id    : constant Entity_Id  := Defining_Identifier (N);
2094       T     : Entity_Id;
2095       Act_T : Entity_Id;
2096
2097       E : Node_Id := Expression (N);
2098       --  E is set to Expression (N) throughout this routine. When
2099       --  Expression (N) is modified, E is changed accordingly.
2100
2101       Prev_Entity : Entity_Id := Empty;
2102
2103       function Count_Tasks (T : Entity_Id) return Uint;
2104       --  This function is called when a library level object of type is
2105       --  declared. It's function is to count the static number of tasks
2106       --  declared within the type (it is only called if Has_Tasks is set for
2107       --  T). As a side effect, if an array of tasks with non-static bounds or
2108       --  a variant record type is encountered, Check_Restrictions is called
2109       --  indicating the count is unknown.
2110
2111       -----------------
2112       -- Count_Tasks --
2113       -----------------
2114
2115       function Count_Tasks (T : Entity_Id) return Uint is
2116          C : Entity_Id;
2117          X : Node_Id;
2118          V : Uint;
2119
2120       begin
2121          if Is_Task_Type (T) then
2122             return Uint_1;
2123
2124          elsif Is_Record_Type (T) then
2125             if Has_Discriminants (T) then
2126                Check_Restriction (Max_Tasks, N);
2127                return Uint_0;
2128
2129             else
2130                V := Uint_0;
2131                C := First_Component (T);
2132                while Present (C) loop
2133                   V := V + Count_Tasks (Etype (C));
2134                   Next_Component (C);
2135                end loop;
2136
2137                return V;
2138             end if;
2139
2140          elsif Is_Array_Type (T) then
2141             X := First_Index (T);
2142             V := Count_Tasks (Component_Type (T));
2143             while Present (X) loop
2144                C := Etype (X);
2145
2146                if not Is_Static_Subtype (C) then
2147                   Check_Restriction (Max_Tasks, N);
2148                   return Uint_0;
2149                else
2150                   V := V * (UI_Max (Uint_0,
2151                                     Expr_Value (Type_High_Bound (C)) -
2152                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2153                end if;
2154
2155                Next_Index (X);
2156             end loop;
2157
2158             return V;
2159
2160          else
2161             return Uint_0;
2162          end if;
2163       end Count_Tasks;
2164
2165    --  Start of processing for Analyze_Object_Declaration
2166
2167    begin
2168       --  There are three kinds of implicit types generated by an
2169       --  object declaration:
2170
2171       --   1. Those for generated by the original Object Definition
2172
2173       --   2. Those generated by the Expression
2174
2175       --   3. Those used to constrained the Object Definition with the
2176       --       expression constraints when it is unconstrained
2177
2178       --  They must be generated in this order to avoid order of elaboration
2179       --  issues. Thus the first step (after entering the name) is to analyze
2180       --  the object definition.
2181
2182       if Constant_Present (N) then
2183          Prev_Entity := Current_Entity_In_Scope (Id);
2184
2185          --  If homograph is an implicit subprogram, it is overridden by the
2186          --  current declaration.
2187
2188          if Present (Prev_Entity)
2189            and then Is_Overloadable (Prev_Entity)
2190            and then Is_Inherited_Operation (Prev_Entity)
2191          then
2192             Prev_Entity := Empty;
2193          end if;
2194       end if;
2195
2196       if Present (Prev_Entity) then
2197          Constant_Redeclaration (Id, N, T);
2198
2199          Generate_Reference (Prev_Entity, Id, 'c');
2200          Set_Completion_Referenced (Id);
2201
2202          if Error_Posted (N) then
2203
2204             --  Type mismatch or illegal redeclaration, Do not analyze
2205             --  expression to avoid cascaded errors.
2206
2207             T := Find_Type_Of_Object (Object_Definition (N), N);
2208             Set_Etype (Id, T);
2209             Set_Ekind (Id, E_Variable);
2210             return;
2211          end if;
2212
2213       --  In the normal case, enter identifier at the start to catch premature
2214       --  usage in the initialization expression.
2215
2216       else
2217          Generate_Definition (Id);
2218          Enter_Name (Id);
2219
2220          Mark_Coextensions (N, Object_Definition (N));
2221
2222          T := Find_Type_Of_Object (Object_Definition (N), N);
2223
2224          if Nkind (Object_Definition (N)) = N_Access_Definition
2225            and then Present
2226              (Access_To_Subprogram_Definition (Object_Definition (N)))
2227            and then Protected_Present
2228              (Access_To_Subprogram_Definition (Object_Definition (N)))
2229          then
2230             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2231          end if;
2232
2233          if Error_Posted (Id) then
2234             Set_Etype (Id, T);
2235             Set_Ekind (Id, E_Variable);
2236             return;
2237          end if;
2238       end if;
2239
2240       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2241       --  out some static checks
2242
2243       if Ada_Version >= Ada_05
2244         and then Can_Never_Be_Null (T)
2245       then
2246          --  In case of aggregates we must also take care of the correct
2247          --  initialization of nested aggregates bug this is done at the
2248          --  point of the analysis of the aggregate (see sem_aggr.adb)
2249
2250          if Present (Expression (N))
2251            and then Nkind (Expression (N)) = N_Aggregate
2252          then
2253             null;
2254
2255          else
2256             declare
2257                Save_Typ : constant Entity_Id := Etype (Id);
2258             begin
2259                Set_Etype (Id, T); --  Temp. decoration for static checks
2260                Null_Exclusion_Static_Checks (N);
2261                Set_Etype (Id, Save_Typ);
2262             end;
2263          end if;
2264       end if;
2265
2266       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2267
2268       --  If deferred constant, make sure context is appropriate. We detect
2269       --  a deferred constant as a constant declaration with no expression.
2270       --  A deferred constant can appear in a package body if its completion
2271       --  is by means of an interface pragma.
2272
2273       if Constant_Present (N)
2274         and then No (E)
2275       then
2276          --  We exclude forward references to tags
2277
2278          if Is_Imported (Defining_Identifier (N))
2279            and then
2280             (T = RTE (RE_Tag)
2281               or else (Present (Full_View (T))
2282                         and then Full_View (T) = RTE (RE_Tag)))
2283          then
2284             null;
2285
2286          elsif not Is_Package_Or_Generic_Package (Current_Scope) then
2287             Error_Msg_N
2288               ("invalid context for deferred constant declaration (RM 7.4)",
2289                 N);
2290             Error_Msg_N
2291               ("\declaration requires an initialization expression",
2292                 N);
2293             Set_Constant_Present (N, False);
2294
2295          --  In Ada 83, deferred constant must be of private type
2296
2297          elsif not Is_Private_Type (T) then
2298             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
2299                Error_Msg_N
2300                  ("(Ada 83) deferred constant must be private type", N);
2301             end if;
2302          end if;
2303
2304       --  If not a deferred constant, then object declaration freezes its type
2305
2306       else
2307          Check_Fully_Declared (T, N);
2308          Freeze_Before (N, T);
2309       end if;
2310
2311       --  If the object was created by a constrained array definition, then
2312       --  set the link in both the anonymous base type and anonymous subtype
2313       --  that are built to represent the array type to point to the object.
2314
2315       if Nkind (Object_Definition (Declaration_Node (Id))) =
2316                         N_Constrained_Array_Definition
2317       then
2318          Set_Related_Array_Object (T, Id);
2319          Set_Related_Array_Object (Base_Type (T), Id);
2320       end if;
2321
2322       --  Special checks for protected objects not at library level
2323
2324       if Is_Protected_Type (T)
2325         and then not Is_Library_Level_Entity (Id)
2326       then
2327          Check_Restriction (No_Local_Protected_Objects, Id);
2328
2329          --  Protected objects with interrupt handlers must be at library level
2330
2331          --  Ada 2005: this test is not needed (and the corresponding clause
2332          --  in the RM is removed) because accessibility checks are sufficient
2333          --  to make handlers not at the library level illegal.
2334
2335          if Has_Interrupt_Handler (T)
2336            and then Ada_Version < Ada_05
2337          then
2338             Error_Msg_N
2339               ("interrupt object can only be declared at library level", Id);
2340          end if;
2341       end if;
2342
2343       --  The actual subtype of the object is the nominal subtype, unless
2344       --  the nominal one is unconstrained and obtained from the expression.
2345
2346       Act_T := T;
2347
2348       --  Process initialization expression if present and not in error
2349
2350       if Present (E) and then E /= Error then
2351          Mark_Coextensions (N, E);
2352          Analyze (E);
2353
2354          --  In case of errors detected in the analysis of the expression,
2355          --  decorate it with the expected type to avoid cascade errors
2356
2357          if No (Etype (E)) then
2358             Set_Etype (E, T);
2359          end if;
2360
2361          --  If an initialization expression is present, then we set the
2362          --  Is_True_Constant flag. It will be reset if this is a variable
2363          --  and it is indeed modified.
2364
2365          Set_Is_True_Constant (Id, True);
2366
2367          --  If we are analyzing a constant declaration, set its completion
2368          --  flag after analyzing the expression.
2369
2370          if Constant_Present (N) then
2371             Set_Has_Completion (Id);
2372          end if;
2373
2374          Set_Etype (Id, T);             --  may be overridden later on
2375          Resolve (E, T);
2376
2377          if not Assignment_OK (N) then
2378             Check_Initialization (T, E);
2379          end if;
2380
2381          Check_Unset_Reference (E);
2382
2383          --  If this is a variable, then set current value
2384
2385          if not Constant_Present (N) then
2386             if Compile_Time_Known_Value (E) then
2387                Set_Current_Value (Id, E);
2388             end if;
2389          end if;
2390
2391          --  Deal with setting of null flags
2392
2393          if Is_Access_Type (T) then
2394             if Known_Non_Null (E) then
2395                Set_Is_Known_Non_Null (Id, True);
2396             elsif Known_Null (E)
2397               and then not Can_Never_Be_Null (Id)
2398             then
2399                Set_Is_Known_Null (Id, True);
2400             end if;
2401          end if;
2402
2403          --  Check incorrect use of dynamically tagged expressions. Note
2404          --  the use of Is_Tagged_Type (T) which seems redundant but is in
2405          --  fact important to avoid spurious errors due to expanded code
2406          --  for dispatching functions over an anonymous access type
2407
2408          if (Is_Class_Wide_Type (Etype (E)) or else Is_Dynamically_Tagged (E))
2409            and then Is_Tagged_Type (T)
2410            and then not Is_Class_Wide_Type (T)
2411          then
2412             Error_Msg_N ("dynamically tagged expression not allowed!", E);
2413          end if;
2414
2415          Apply_Scalar_Range_Check (E, T);
2416          Apply_Static_Length_Check (E, T);
2417       end if;
2418
2419       --  If the No_Streams restriction is set, check that the type of the
2420       --  object is not, and does not contain, any subtype derived from
2421       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
2422       --  Has_Stream just for efficiency reasons. There is no point in
2423       --  spending time on a Has_Stream check if the restriction is not set.
2424
2425       if Restrictions.Set (No_Streams) then
2426          if Has_Stream (T) then
2427             Check_Restriction (No_Streams, N);
2428          end if;
2429       end if;
2430
2431       --  Abstract type is never permitted for a variable or constant.
2432       --  Note: we inhibit this check for objects that do not come from
2433       --  source because there is at least one case (the expansion of
2434       --  x'class'input where x is abstract) where we legitimately
2435       --  generate an abstract object.
2436
2437       if Is_Abstract_Type (T) and then Comes_From_Source (N) then
2438          Error_Msg_N ("type of object cannot be abstract",
2439                       Object_Definition (N));
2440
2441          if Is_CPP_Class (T) then
2442             Error_Msg_NE ("\} may need a cpp_constructor",
2443               Object_Definition (N), T);
2444          end if;
2445
2446       --  Case of unconstrained type
2447
2448       elsif Is_Indefinite_Subtype (T) then
2449
2450          --  Nothing to do in deferred constant case
2451
2452          if Constant_Present (N) and then No (E) then
2453             null;
2454
2455          --  Case of no initialization present
2456
2457          elsif No (E) then
2458             if No_Initialization (N) then
2459                null;
2460
2461             elsif Is_Class_Wide_Type (T) then
2462                Error_Msg_N
2463                  ("initialization required in class-wide declaration ", N);
2464
2465             else
2466                Error_Msg_N
2467                  ("unconstrained subtype not allowed (need initialization)",
2468                   Object_Definition (N));
2469             end if;
2470
2471          --  Case of initialization present but in error. Set initial
2472          --  expression as absent (but do not make above complaints)
2473
2474          elsif E = Error then
2475             Set_Expression (N, Empty);
2476             E := Empty;
2477
2478          --  Case of initialization present
2479
2480          else
2481             --  Not allowed in Ada 83
2482
2483             if not Constant_Present (N) then
2484                if Ada_Version = Ada_83
2485                  and then Comes_From_Source (Object_Definition (N))
2486                then
2487                   Error_Msg_N
2488                     ("(Ada 83) unconstrained variable not allowed",
2489                      Object_Definition (N));
2490                end if;
2491             end if;
2492
2493             --  Now we constrain the variable from the initializing expression
2494
2495             --  If the expression is an aggregate, it has been expanded into
2496             --  individual assignments. Retrieve the actual type from the
2497             --  expanded construct.
2498
2499             if Is_Array_Type (T)
2500               and then No_Initialization (N)
2501               and then Nkind (Original_Node (E)) = N_Aggregate
2502             then
2503                Act_T := Etype (E);
2504
2505             else
2506                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
2507                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
2508             end if;
2509
2510             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
2511
2512             if Aliased_Present (N) then
2513                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
2514             end if;
2515
2516             Freeze_Before (N, Act_T);
2517             Freeze_Before (N, T);
2518          end if;
2519
2520       elsif Is_Array_Type (T)
2521         and then No_Initialization (N)
2522         and then Nkind (Original_Node (E)) = N_Aggregate
2523       then
2524          if not Is_Entity_Name (Object_Definition (N)) then
2525             Act_T := Etype (E);
2526             Check_Compile_Time_Size (Act_T);
2527
2528             if Aliased_Present (N) then
2529                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
2530             end if;
2531          end if;
2532
2533          --  When the given object definition and the aggregate are specified
2534          --  independently, and their lengths might differ do a length check.
2535          --  This cannot happen if the aggregate is of the form (others =>...)
2536
2537          if not Is_Constrained (T) then
2538             null;
2539
2540          elsif Nkind (E) = N_Raise_Constraint_Error then
2541
2542             --  Aggregate is statically illegal. Place back in declaration
2543
2544             Set_Expression (N, E);
2545             Set_No_Initialization (N, False);
2546
2547          elsif T = Etype (E) then
2548             null;
2549
2550          elsif Nkind (E) = N_Aggregate
2551            and then Present (Component_Associations (E))
2552            and then Present (Choices (First (Component_Associations (E))))
2553            and then Nkind (First
2554             (Choices (First (Component_Associations (E))))) = N_Others_Choice
2555          then
2556             null;
2557
2558          else
2559             Apply_Length_Check (E, T);
2560          end if;
2561
2562       --  If the type is limited unconstrained with defaulted discriminants
2563       --  and there is no expression, then the object is constrained by the
2564       --  defaults, so it is worthwhile building the corresponding subtype.
2565
2566       elsif (Is_Limited_Record (T)
2567                or else Is_Concurrent_Type (T))
2568         and then not Is_Constrained (T)
2569         and then Has_Discriminants (T)
2570       then
2571          if No (E) then
2572             Act_T := Build_Default_Subtype (T, N);
2573          else
2574             --  Ada 2005:  a limited object may be initialized by means of an
2575             --  aggregate. If the type has default discriminants it has an
2576             --  unconstrained nominal type, Its actual subtype will be obtained
2577             --  from the aggregate, and not from the default discriminants.
2578
2579             Act_T := Etype (E);
2580          end if;
2581
2582          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
2583
2584       elsif Present (Underlying_Type (T))
2585         and then not Is_Constrained (Underlying_Type (T))
2586         and then Has_Discriminants (Underlying_Type (T))
2587         and then Nkind (E) = N_Function_Call
2588         and then Constant_Present (N)
2589       then
2590          --  The back-end has problems with constants of a discriminated type
2591          --  with defaults, if the initial value is a function call. We
2592          --  generate an intermediate temporary for the result of the call.
2593          --  It is unclear why this should make it acceptable to gcc. ???
2594
2595          Remove_Side_Effects (E);
2596       end if;
2597
2598       if T = Standard_Wide_Character or else T = Standard_Wide_Wide_Character
2599         or else Root_Type (T) = Standard_Wide_String
2600         or else Root_Type (T) = Standard_Wide_Wide_String
2601       then
2602          Check_Restriction (No_Wide_Characters, Object_Definition (N));
2603       end if;
2604
2605       --  Indicate this is not set in source. Certainly true for constants,
2606       --  and true for variables so far (will be reset for a variable if and
2607       --  when we encounter a modification in the source).
2608
2609       Set_Never_Set_In_Source (Id, True);
2610
2611       --  Now establish the proper kind and type of the object
2612
2613       if Constant_Present (N) then
2614          Set_Ekind            (Id, E_Constant);
2615          Set_Is_True_Constant (Id, True);
2616
2617       else
2618          Set_Ekind (Id, E_Variable);
2619
2620          --  A variable is set as shared passive if it appears in a shared
2621          --  passive package, and is at the outer level. This is not done
2622          --  for entities generated during expansion, because those are
2623          --  always manipulated locally.
2624
2625          if Is_Shared_Passive (Current_Scope)
2626            and then Is_Library_Level_Entity (Id)
2627            and then Comes_From_Source (Id)
2628          then
2629             Set_Is_Shared_Passive (Id);
2630             Check_Shared_Var (Id, T, N);
2631          end if;
2632
2633          --  Set Has_Initial_Value if initializing expression present. Note
2634          --  that if there is no initializating expression, we leave the state
2635          --  of this flag unchanged (usually it will be False, but notably in
2636          --  the case of exception choice variables, it will already be true).
2637
2638          if Present (E) then
2639             Set_Has_Initial_Value (Id, True);
2640          end if;
2641       end if;
2642
2643       --  Initialize alignment and size
2644
2645       Init_Alignment (Id);
2646       Init_Esize     (Id);
2647
2648       --  Deal with aliased case
2649
2650       if Aliased_Present (N) then
2651          Set_Is_Aliased (Id);
2652
2653          --  If the object is aliased and the type is unconstrained with
2654          --  defaulted discriminants and there is no expression, then the
2655          --  object is constrained by the defaults, so it is worthwhile
2656          --  building the corresponding subtype.
2657
2658          --  Ada 2005 (AI-363): If the aliased object is discriminated and
2659          --  unconstrained, then only establish an actual subtype if the
2660          --  nominal subtype is indefinite. In definite cases the object is
2661          --  unconstrained in Ada 2005.
2662
2663          if No (E)
2664            and then Is_Record_Type (T)
2665            and then not Is_Constrained (T)
2666            and then Has_Discriminants (T)
2667            and then (Ada_Version < Ada_05 or else Is_Indefinite_Subtype (T))
2668          then
2669             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
2670          end if;
2671       end if;
2672
2673       --  Now we can set the type of the object
2674
2675       Set_Etype (Id, Act_T);
2676
2677       --  Deal with controlled types
2678
2679       if Has_Controlled_Component (Etype (Id))
2680         or else Is_Controlled (Etype (Id))
2681       then
2682          if not Is_Library_Level_Entity (Id) then
2683             Check_Restriction (No_Nested_Finalization, N);
2684          else
2685             Validate_Controlled_Object (Id);
2686          end if;
2687
2688          --  Generate a warning when an initialization causes an obvious ABE
2689          --  violation. If the init expression is a simple aggregate there
2690          --  shouldn't be any initialize/adjust call generated. This will be
2691          --  true as soon as aggregates are built in place when possible.
2692
2693          --  ??? at the moment we do not generate warnings for temporaries
2694          --  created for those aggregates although Program_Error might be
2695          --  generated if compiled with -gnato.
2696
2697          if Is_Controlled (Etype (Id))
2698             and then Comes_From_Source (Id)
2699          then
2700             declare
2701                BT : constant Entity_Id := Base_Type (Etype (Id));
2702
2703                Implicit_Call : Entity_Id;
2704                pragma Warnings (Off, Implicit_Call);
2705                --  ??? what is this for (never referenced!)
2706
2707                function Is_Aggr (N : Node_Id) return Boolean;
2708                --  Check that N is an aggregate
2709
2710                -------------
2711                -- Is_Aggr --
2712                -------------
2713
2714                function Is_Aggr (N : Node_Id) return Boolean is
2715                begin
2716                   case Nkind (Original_Node (N)) is
2717                      when N_Aggregate | N_Extension_Aggregate =>
2718                         return True;
2719
2720                      when N_Qualified_Expression |
2721                           N_Type_Conversion      |
2722                           N_Unchecked_Type_Conversion =>
2723                         return Is_Aggr (Expression (Original_Node (N)));
2724
2725                      when others =>
2726                         return False;
2727                   end case;
2728                end Is_Aggr;
2729
2730             begin
2731                --  If no underlying type, we already are in an error situation.
2732                --  Do not try to add a warning since we do not have access to
2733                --  prim-op list.
2734
2735                if No (Underlying_Type (BT)) then
2736                   Implicit_Call := Empty;
2737
2738                --  A generic type does not have usable primitive operators.
2739                --  Initialization calls are built for instances.
2740
2741                elsif Is_Generic_Type (BT) then
2742                   Implicit_Call := Empty;
2743
2744                --  If the init expression is not an aggregate, an adjust call
2745                --  will be generated
2746
2747                elsif Present (E) and then not Is_Aggr (E) then
2748                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
2749
2750                --  If no init expression and we are not in the deferred
2751                --  constant case, an Initialize call will be generated
2752
2753                elsif No (E) and then not Constant_Present (N) then
2754                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
2755
2756                else
2757                   Implicit_Call := Empty;
2758                end if;
2759             end;
2760          end if;
2761       end if;
2762
2763       if Has_Task (Etype (Id)) then
2764          Check_Restriction (No_Tasking, N);
2765
2766          if Is_Library_Level_Entity (Id) then
2767             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
2768          else
2769             Check_Restriction (Max_Tasks, N);
2770             Check_Restriction (No_Task_Hierarchy, N);
2771             Check_Potentially_Blocking_Operation (N);
2772          end if;
2773
2774          --  A rather specialized test. If we see two tasks being declared
2775          --  of the same type in the same object declaration, and the task
2776          --  has an entry with an address clause, we know that program error
2777          --  will be raised at run-time since we can't have two tasks with
2778          --  entries at the same address.
2779
2780          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
2781             declare
2782                E : Entity_Id;
2783
2784             begin
2785                E := First_Entity (Etype (Id));
2786                while Present (E) loop
2787                   if Ekind (E) = E_Entry
2788                     and then Present (Get_Attribute_Definition_Clause
2789                                         (E, Attribute_Address))
2790                   then
2791                      Error_Msg_N
2792                        ("?more than one task with same entry address", N);
2793                      Error_Msg_N
2794                        ("\?Program_Error will be raised at run time", N);
2795                      Insert_Action (N,
2796                        Make_Raise_Program_Error (Loc,
2797                          Reason => PE_Duplicated_Entry_Address));
2798                      exit;
2799                   end if;
2800
2801                   Next_Entity (E);
2802                end loop;
2803             end;
2804          end if;
2805       end if;
2806
2807       --  Some simple constant-propagation: if the expression is a constant
2808       --  string initialized with a literal, share the literal. This avoids
2809       --  a run-time copy.
2810
2811       if Present (E)
2812         and then Is_Entity_Name (E)
2813         and then Ekind (Entity (E)) = E_Constant
2814         and then Base_Type (Etype (E)) = Standard_String
2815       then
2816          declare
2817             Val : constant Node_Id := Constant_Value (Entity (E));
2818          begin
2819             if Present (Val)
2820               and then Nkind (Val) = N_String_Literal
2821             then
2822                Rewrite (E, New_Copy (Val));
2823             end if;
2824          end;
2825       end if;
2826
2827       --  Another optimization: if the nominal subtype is unconstrained and
2828       --  the expression is a function call that returns an unconstrained
2829       --  type, rewrite the declaration as a renaming of the result of the
2830       --  call. The exceptions below are cases where the copy is expected,
2831       --  either by the back end (Aliased case) or by the semantics, as for
2832       --  initializing controlled types or copying tags for classwide types.
2833
2834       if Present (E)
2835         and then Nkind (E) = N_Explicit_Dereference
2836         and then Nkind (Original_Node (E)) = N_Function_Call
2837         and then not Is_Library_Level_Entity (Id)
2838         and then not Is_Constrained (Underlying_Type (T))
2839         and then not Is_Aliased (Id)
2840         and then not Is_Class_Wide_Type (T)
2841         and then not Is_Controlled (T)
2842         and then not Has_Controlled_Component (Base_Type (T))
2843         and then Expander_Active
2844       then
2845          Rewrite (N,
2846            Make_Object_Renaming_Declaration (Loc,
2847              Defining_Identifier => Id,
2848              Access_Definition   => Empty,
2849              Subtype_Mark        => New_Occurrence_Of
2850                                       (Base_Type (Etype (Id)), Loc),
2851              Name                => E));
2852
2853          Set_Renamed_Object (Id, E);
2854
2855          --  Force generation of debugging information for the constant and for
2856          --  the renamed function call.
2857
2858          Set_Needs_Debug_Info (Id);
2859          Set_Needs_Debug_Info (Entity (Prefix (E)));
2860       end if;
2861
2862       if Present (Prev_Entity)
2863         and then Is_Frozen (Prev_Entity)
2864         and then not Error_Posted (Id)
2865       then
2866          Error_Msg_N ("full constant declaration appears too late", N);
2867       end if;
2868
2869       Check_Eliminated (Id);
2870
2871       --  Deal with setting In_Private_Part flag if in private part
2872
2873       if Ekind (Scope (Id)) = E_Package
2874         and then In_Private_Part (Scope (Id))
2875       then
2876          Set_In_Private_Part (Id);
2877       end if;
2878    end Analyze_Object_Declaration;
2879
2880    ---------------------------
2881    -- Analyze_Others_Choice --
2882    ---------------------------
2883
2884    --  Nothing to do for the others choice node itself, the semantic analysis
2885    --  of the others choice will occur as part of the processing of the parent
2886
2887    procedure Analyze_Others_Choice (N : Node_Id) is
2888       pragma Warnings (Off, N);
2889    begin
2890       null;
2891    end Analyze_Others_Choice;
2892
2893    --------------------------------
2894    -- Analyze_Per_Use_Expression --
2895    --------------------------------
2896
2897    procedure Analyze_Per_Use_Expression (N : Node_Id; T : Entity_Id) is
2898       Save_In_Default_Expression : constant Boolean := In_Default_Expression;
2899    begin
2900       In_Default_Expression := True;
2901       Pre_Analyze_And_Resolve (N, T);
2902       In_Default_Expression := Save_In_Default_Expression;
2903    end Analyze_Per_Use_Expression;
2904
2905    -------------------------------------------
2906    -- Analyze_Private_Extension_Declaration --
2907    -------------------------------------------
2908
2909    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
2910       T           : constant Entity_Id := Defining_Identifier (N);
2911       Indic       : constant Node_Id   := Subtype_Indication (N);
2912       Parent_Type : Entity_Id;
2913       Parent_Base : Entity_Id;
2914
2915    begin
2916       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
2917
2918       if Is_Non_Empty_List (Interface_List (N)) then
2919          declare
2920             Intf : Node_Id;
2921             T    : Entity_Id;
2922
2923          begin
2924             Intf := First (Interface_List (N));
2925             while Present (Intf) loop
2926                T := Find_Type_Of_Subtype_Indic (Intf);
2927
2928                if not Is_Interface (T) then
2929                   Error_Msg_NE ("(Ada 2005) & must be an interface", Intf, T);
2930                end if;
2931
2932                Next (Intf);
2933             end loop;
2934          end;
2935       end if;
2936
2937       Generate_Definition (T);
2938       Enter_Name (T);
2939
2940       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
2941       Parent_Base := Base_Type (Parent_Type);
2942
2943       if Parent_Type = Any_Type
2944         or else Etype (Parent_Type) = Any_Type
2945       then
2946          Set_Ekind (T, Ekind (Parent_Type));
2947          Set_Etype (T, Any_Type);
2948          return;
2949
2950       elsif not Is_Tagged_Type (Parent_Type) then
2951          Error_Msg_N
2952            ("parent of type extension must be a tagged type ", Indic);
2953          return;
2954
2955       elsif Ekind (Parent_Type) = E_Void
2956         or else Ekind (Parent_Type) = E_Incomplete_Type
2957       then
2958          Error_Msg_N ("premature derivation of incomplete type", Indic);
2959          return;
2960
2961       elsif Is_Concurrent_Type (Parent_Type) then
2962          Error_Msg_N
2963            ("parent type of a private extension cannot be "
2964             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
2965
2966          Set_Etype              (T, Any_Type);
2967          Set_Ekind              (T, E_Limited_Private_Type);
2968          Set_Private_Dependents (T, New_Elmt_List);
2969          Set_Error_Posted       (T);
2970          return;
2971       end if;
2972
2973       --  Perhaps the parent type should be changed to the class-wide type's
2974       --  specific type in this case to prevent cascading errors ???
2975
2976       if Is_Class_Wide_Type (Parent_Type) then
2977          Error_Msg_N
2978            ("parent of type extension must not be a class-wide type", Indic);
2979          return;
2980       end if;
2981
2982       if (not Is_Package_Or_Generic_Package (Current_Scope)
2983            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
2984         or else In_Private_Part (Current_Scope)
2985
2986       then
2987          Error_Msg_N ("invalid context for private extension", N);
2988       end if;
2989
2990       --  Set common attributes
2991
2992       Set_Is_Pure          (T, Is_Pure (Current_Scope));
2993       Set_Scope            (T, Current_Scope);
2994       Set_Ekind            (T, E_Record_Type_With_Private);
2995       Init_Size_Align      (T);
2996
2997       Set_Etype            (T,            Parent_Base);
2998       Set_Has_Task         (T, Has_Task  (Parent_Base));
2999
3000       Set_Convention       (T, Convention     (Parent_Type));
3001       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3002       Set_Is_First_Subtype (T);
3003       Make_Class_Wide_Type (T);
3004
3005       if Unknown_Discriminants_Present (N) then
3006          Set_Discriminant_Constraint (T, No_Elist);
3007       end if;
3008
3009       Build_Derived_Record_Type (N, Parent_Type, T);
3010
3011       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3012       --  synchronized formal derived type.
3013
3014       if Ada_Version >= Ada_05
3015         and then Synchronized_Present (N)
3016       then
3017          Set_Is_Limited_Record (T);
3018
3019          --  Formal derived type case
3020
3021          if Is_Generic_Type (T) then
3022
3023             --  The parent must be a tagged limited type or a synchronized
3024             --  interface.
3025
3026             if (not Is_Tagged_Type (Parent_Type)
3027                   or else not Is_Limited_Type (Parent_Type))
3028               and then
3029                (not Is_Interface (Parent_Type)
3030                   or else not Is_Synchronized_Interface (Parent_Type))
3031             then
3032                Error_Msg_NE ("parent type of & must be tagged limited " &
3033                              "or synchronized", N, T);
3034             end if;
3035
3036             --  The progenitors (if any) must be limited or synchronized
3037             --  interfaces.
3038
3039             if Present (Abstract_Interfaces (T)) then
3040                declare
3041                   Iface      : Entity_Id;
3042                   Iface_Elmt : Elmt_Id;
3043
3044                begin
3045                   Iface_Elmt := First_Elmt (Abstract_Interfaces (T));
3046                   while Present (Iface_Elmt) loop
3047                      Iface := Node (Iface_Elmt);
3048
3049                      if not Is_Limited_Interface (Iface)
3050                        and then not Is_Synchronized_Interface (Iface)
3051                      then
3052                         Error_Msg_NE ("progenitor & must be limited " &
3053                                       "or synchronized", N, Iface);
3054                      end if;
3055
3056                      Next_Elmt (Iface_Elmt);
3057                   end loop;
3058                end;
3059             end if;
3060
3061          --  Regular derived extension, the parent must be a limited or
3062          --  synchronized interface.
3063
3064          else
3065             if not Is_Interface (Parent_Type)
3066               or else (not Is_Limited_Interface (Parent_Type)
3067                          and then
3068                        not Is_Synchronized_Interface (Parent_Type))
3069             then
3070                Error_Msg_NE
3071                  ("parent type of & must be limited interface", N, T);
3072             end if;
3073          end if;
3074
3075       elsif Limited_Present (N) then
3076          Set_Is_Limited_Record (T);
3077
3078          if not Is_Limited_Type (Parent_Type)
3079            and then
3080              (not Is_Interface (Parent_Type)
3081                or else not Is_Limited_Interface (Parent_Type))
3082          then
3083             Error_Msg_NE ("parent type& of limited extension must be limited",
3084               N, Parent_Type);
3085          end if;
3086       end if;
3087    end Analyze_Private_Extension_Declaration;
3088
3089    ---------------------------------
3090    -- Analyze_Subtype_Declaration --
3091    ---------------------------------
3092
3093    procedure Analyze_Subtype_Declaration
3094      (N    : Node_Id;
3095       Skip : Boolean := False)
3096    is
3097       Id       : constant Entity_Id := Defining_Identifier (N);
3098       T        : Entity_Id;
3099       R_Checks : Check_Result;
3100
3101    begin
3102       Generate_Definition (Id);
3103       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3104       Init_Size_Align (Id);
3105
3106       --  The following guard condition on Enter_Name is to handle cases where
3107       --  the defining identifier has already been entered into the scope but
3108       --  the declaration as a whole needs to be analyzed.
3109
3110       --  This case in particular happens for derived enumeration types. The
3111       --  derived enumeration type is processed as an inserted enumeration type
3112       --  declaration followed by a rewritten subtype declaration. The defining
3113       --  identifier, however, is entered into the name scope very early in the
3114       --  processing of the original type declaration and therefore needs to be
3115       --  avoided here, when the created subtype declaration is analyzed. (See
3116       --  Build_Derived_Types)
3117
3118       --  This also happens when the full view of a private type is derived
3119       --  type with constraints. In this case the entity has been introduced
3120       --  in the private declaration.
3121
3122       if Skip
3123         or else (Present (Etype (Id))
3124                    and then (Is_Private_Type (Etype (Id))
3125                                or else Is_Task_Type (Etype (Id))
3126                                or else Is_Rewrite_Substitution (N)))
3127       then
3128          null;
3129
3130       else
3131          Enter_Name (Id);
3132       end if;
3133
3134       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
3135
3136       --  Inherit common attributes
3137
3138       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
3139       Set_Is_Volatile       (Id, Is_Volatile       (T));
3140       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
3141       Set_Is_Atomic         (Id, Is_Atomic         (T));
3142       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
3143
3144       --  In the case where there is no constraint given in the subtype
3145       --  indication, Process_Subtype just returns the Subtype_Mark, so its
3146       --  semantic attributes must be established here.
3147
3148       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
3149          Set_Etype (Id, Base_Type (T));
3150
3151          case Ekind (T) is
3152             when Array_Kind =>
3153                Set_Ekind                       (Id, E_Array_Subtype);
3154                Copy_Array_Subtype_Attributes   (Id, T);
3155
3156             when Decimal_Fixed_Point_Kind =>
3157                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
3158                Set_Digits_Value         (Id, Digits_Value       (T));
3159                Set_Delta_Value          (Id, Delta_Value        (T));
3160                Set_Scale_Value          (Id, Scale_Value        (T));
3161                Set_Small_Value          (Id, Small_Value        (T));
3162                Set_Scalar_Range         (Id, Scalar_Range       (T));
3163                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
3164                Set_Is_Constrained       (Id, Is_Constrained     (T));
3165                Set_RM_Size              (Id, RM_Size            (T));
3166
3167             when Enumeration_Kind =>
3168                Set_Ekind                (Id, E_Enumeration_Subtype);
3169                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
3170                Set_Scalar_Range         (Id, Scalar_Range       (T));
3171                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
3172                Set_Is_Constrained       (Id, Is_Constrained     (T));
3173                Set_RM_Size              (Id, RM_Size            (T));
3174
3175             when Ordinary_Fixed_Point_Kind =>
3176                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
3177                Set_Scalar_Range         (Id, Scalar_Range       (T));
3178                Set_Small_Value          (Id, Small_Value        (T));
3179                Set_Delta_Value          (Id, Delta_Value        (T));
3180                Set_Is_Constrained       (Id, Is_Constrained     (T));
3181                Set_RM_Size              (Id, RM_Size            (T));
3182
3183             when Float_Kind =>
3184                Set_Ekind                (Id, E_Floating_Point_Subtype);
3185                Set_Scalar_Range         (Id, Scalar_Range       (T));
3186                Set_Digits_Value         (Id, Digits_Value       (T));
3187                Set_Is_Constrained       (Id, Is_Constrained     (T));
3188
3189             when Signed_Integer_Kind =>
3190                Set_Ekind                (Id, E_Signed_Integer_Subtype);
3191                Set_Scalar_Range         (Id, Scalar_Range       (T));
3192                Set_Is_Constrained       (Id, Is_Constrained     (T));
3193                Set_RM_Size              (Id, RM_Size            (T));
3194
3195             when Modular_Integer_Kind =>
3196                Set_Ekind                (Id, E_Modular_Integer_Subtype);
3197                Set_Scalar_Range         (Id, Scalar_Range       (T));
3198                Set_Is_Constrained       (Id, Is_Constrained     (T));
3199                Set_RM_Size              (Id, RM_Size            (T));
3200
3201             when Class_Wide_Kind =>
3202                Set_Ekind                (Id, E_Class_Wide_Subtype);
3203                Set_First_Entity         (Id, First_Entity       (T));
3204                Set_Last_Entity          (Id, Last_Entity        (T));
3205                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
3206                Set_Cloned_Subtype       (Id, T);
3207                Set_Is_Tagged_Type       (Id, True);
3208                Set_Has_Unknown_Discriminants
3209                                         (Id, True);
3210
3211                if Ekind (T) = E_Class_Wide_Subtype then
3212                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
3213                end if;
3214
3215             when E_Record_Type | E_Record_Subtype =>
3216                Set_Ekind                (Id, E_Record_Subtype);
3217
3218                if Ekind (T) = E_Record_Subtype
3219                  and then Present (Cloned_Subtype (T))
3220                then
3221                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
3222                else
3223                   Set_Cloned_Subtype    (Id, T);
3224                end if;
3225
3226                Set_First_Entity         (Id, First_Entity       (T));
3227                Set_Last_Entity          (Id, Last_Entity        (T));
3228                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
3229                Set_Is_Constrained       (Id, Is_Constrained     (T));
3230                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
3231                Set_Has_Unknown_Discriminants
3232                                         (Id, Has_Unknown_Discriminants (T));
3233
3234                if Has_Discriminants (T) then
3235                   Set_Discriminant_Constraint
3236                                         (Id, Discriminant_Constraint (T));
3237                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3238
3239                elsif Has_Unknown_Discriminants (Id) then
3240                   Set_Discriminant_Constraint (Id, No_Elist);
3241                end if;
3242
3243                if Is_Tagged_Type (T) then
3244                   Set_Is_Tagged_Type    (Id);
3245                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
3246                   Set_Primitive_Operations
3247                                         (Id, Primitive_Operations (T));
3248                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
3249
3250                   if Is_Interface (T) then
3251                      Set_Is_Interface (Id);
3252                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
3253                   end if;
3254                end if;
3255
3256             when Private_Kind =>
3257                Set_Ekind              (Id, Subtype_Kind (Ekind   (T)));
3258                Set_Has_Discriminants  (Id, Has_Discriminants     (T));
3259                Set_Is_Constrained     (Id, Is_Constrained        (T));
3260                Set_First_Entity       (Id, First_Entity          (T));
3261                Set_Last_Entity        (Id, Last_Entity           (T));
3262                Set_Private_Dependents (Id, New_Elmt_List);
3263                Set_Is_Limited_Record  (Id, Is_Limited_Record     (T));
3264                Set_Has_Unknown_Discriminants
3265                                       (Id, Has_Unknown_Discriminants (T));
3266
3267                if Is_Tagged_Type (T) then
3268                   Set_Is_Tagged_Type       (Id);
3269                   Set_Is_Abstract_Type     (Id, Is_Abstract_Type (T));
3270                   Set_Primitive_Operations (Id, Primitive_Operations (T));
3271                   Set_Class_Wide_Type      (Id, Class_Wide_Type (T));
3272                end if;
3273
3274                --  In general the attributes of the subtype of a private type
3275                --  are the attributes of the partial view of parent. However,
3276                --  the full view may be a discriminated type, and the subtype
3277                --  must share the discriminant constraint to generate correct
3278                --  calls to initialization procedures.
3279
3280                if Has_Discriminants (T) then
3281                   Set_Discriminant_Constraint
3282                                      (Id, Discriminant_Constraint (T));
3283                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3284
3285                elsif Present (Full_View (T))
3286                  and then Has_Discriminants (Full_View (T))
3287                then
3288                   Set_Discriminant_Constraint
3289                                (Id, Discriminant_Constraint (Full_View (T)));
3290                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3291
3292                   --  This would seem semantically correct, but apparently
3293                   --  confuses the back-end (4412-009). To be explained ???
3294
3295                   --  Set_Has_Discriminants (Id);
3296                end if;
3297
3298                Prepare_Private_Subtype_Completion (Id, N);
3299
3300             when Access_Kind =>
3301                Set_Ekind             (Id, E_Access_Subtype);
3302                Set_Is_Constrained    (Id, Is_Constrained        (T));
3303                Set_Is_Access_Constant
3304                                      (Id, Is_Access_Constant    (T));
3305                Set_Directly_Designated_Type
3306                                      (Id, Designated_Type       (T));
3307                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
3308
3309                --  A Pure library_item must not contain the declaration of a
3310                --  named access type, except within a subprogram, generic
3311                --  subprogram, task unit, or protected unit (RM 10.2.1(16)).
3312
3313                if Comes_From_Source (Id)
3314                  and then In_Pure_Unit
3315                  and then not In_Subprogram_Task_Protected_Unit
3316                then
3317                   Error_Msg_N
3318                     ("named access types not allowed in pure unit", N);
3319                end if;
3320
3321             when Concurrent_Kind =>
3322                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
3323                Set_Corresponding_Record_Type (Id,
3324                                          Corresponding_Record_Type (T));
3325                Set_First_Entity         (Id, First_Entity          (T));
3326                Set_First_Private_Entity (Id, First_Private_Entity  (T));
3327                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
3328                Set_Is_Constrained       (Id, Is_Constrained        (T));
3329                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
3330                Set_Last_Entity          (Id, Last_Entity           (T));
3331
3332                if Has_Discriminants (T) then
3333                   Set_Discriminant_Constraint (Id,
3334                                            Discriminant_Constraint (T));
3335                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3336                end if;
3337
3338             when E_Incomplete_Type =>
3339                if Ada_Version >= Ada_05 then
3340                   Set_Ekind (Id, E_Incomplete_Subtype);
3341
3342                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
3343                   --  of an incomplete type visible through a limited
3344                   --  with clause.
3345
3346                   if From_With_Type (T)
3347                     and then Present (Non_Limited_View (T))
3348                   then
3349                      Set_From_With_Type   (Id);
3350                      Set_Non_Limited_View (Id, Non_Limited_View (T));
3351
3352                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
3353                   --  to the private dependents of the original incomplete
3354                   --  type for future transformation.
3355
3356                   else
3357                      Append_Elmt (Id, Private_Dependents (T));
3358                   end if;
3359
3360                --  If the subtype name denotes an incomplete type an error
3361                --  was already reported by Process_Subtype.
3362
3363                else
3364                   Set_Etype (Id, Any_Type);
3365                end if;
3366
3367             when others =>
3368                raise Program_Error;
3369          end case;
3370       end if;
3371
3372       if Etype (Id) = Any_Type then
3373          return;
3374       end if;
3375
3376       --  Some common processing on all types
3377
3378       Set_Size_Info      (Id,                 T);
3379       Set_First_Rep_Item (Id, First_Rep_Item (T));
3380
3381       T := Etype (Id);
3382
3383       Set_Is_Immediately_Visible   (Id, True);
3384       Set_Depends_On_Private       (Id, Has_Private_Component (T));
3385       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
3386
3387       if Is_Interface (T) then
3388          Set_Is_Interface (Id);
3389       end if;
3390
3391       if Present (Generic_Parent_Type (N))
3392         and then
3393           (Nkind
3394              (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
3395             or else Nkind
3396               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
3397                 /=  N_Formal_Private_Type_Definition)
3398       then
3399          if Is_Tagged_Type (Id) then
3400
3401             --  If this is a generic actual subtype for a synchronized type,
3402             --  the primitive operations are those of the corresponding record
3403             --  for which there is a separate subtype declaration.
3404
3405             if Is_Concurrent_Type (Id) then
3406                null;
3407             elsif Is_Class_Wide_Type (Id) then
3408                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
3409             else
3410                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
3411             end if;
3412
3413          elsif Scope (Etype (Id)) /= Standard_Standard then
3414             Derive_Subprograms (Generic_Parent_Type (N), Id);
3415          end if;
3416       end if;
3417
3418       if Is_Private_Type (T)
3419         and then Present (Full_View (T))
3420       then
3421          Conditional_Delay (Id, Full_View (T));
3422
3423       --  The subtypes of components or subcomponents of protected types
3424       --  do not need freeze nodes, which would otherwise appear in the
3425       --  wrong scope (before the freeze node for the protected type). The
3426       --  proper subtypes are those of the subcomponents of the corresponding
3427       --  record.
3428
3429       elsif Ekind (Scope (Id)) /= E_Protected_Type
3430         and then Present (Scope (Scope (Id))) -- error defense!
3431         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
3432       then
3433          Conditional_Delay (Id, T);
3434       end if;
3435
3436       --  Check that constraint_error is raised for a scalar subtype
3437       --  indication when the lower or upper bound of a non-null range
3438       --  lies outside the range of the type mark.
3439
3440       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
3441          if Is_Scalar_Type (Etype (Id))
3442             and then Scalar_Range (Id) /=
3443                      Scalar_Range (Etype (Subtype_Mark
3444                                            (Subtype_Indication (N))))
3445          then
3446             Apply_Range_Check
3447               (Scalar_Range (Id),
3448                Etype (Subtype_Mark (Subtype_Indication (N))));
3449
3450          elsif Is_Array_Type (Etype (Id))
3451            and then Present (First_Index (Id))
3452          then
3453             --  This really should be a subprogram that finds the indications
3454             --  to check???
3455
3456             if ((Nkind (First_Index (Id)) = N_Identifier
3457                    and then Ekind (Entity (First_Index (Id))) in Scalar_Kind)
3458                  or else Nkind (First_Index (Id)) = N_Subtype_Indication)
3459               and then
3460                 Nkind (Scalar_Range (Etype (First_Index (Id)))) = N_Range
3461             then
3462                declare
3463                   Target_Typ : constant Entity_Id :=
3464                                  Etype
3465                                    (First_Index (Etype
3466                                      (Subtype_Mark (Subtype_Indication (N)))));
3467                begin
3468                   R_Checks :=
3469                     Get_Range_Checks
3470                       (Scalar_Range (Etype (First_Index (Id))),
3471                        Target_Typ,
3472                        Etype (First_Index (Id)),
3473                        Defining_Identifier (N));
3474
3475                   Insert_Range_Checks
3476                     (R_Checks,
3477                      N,
3478                      Target_Typ,
3479                      Sloc (Defining_Identifier (N)));
3480                end;
3481             end if;
3482          end if;
3483       end if;
3484
3485       Check_Eliminated (Id);
3486    end Analyze_Subtype_Declaration;
3487
3488    --------------------------------
3489    -- Analyze_Subtype_Indication --
3490    --------------------------------
3491
3492    procedure Analyze_Subtype_Indication (N : Node_Id) is
3493       T : constant Entity_Id := Subtype_Mark (N);
3494       R : constant Node_Id   := Range_Expression (Constraint (N));
3495
3496    begin
3497       Analyze (T);
3498
3499       if R /= Error then
3500          Analyze (R);
3501          Set_Etype (N, Etype (R));
3502          Resolve (R, Entity (T));
3503       else
3504          Set_Error_Posted (R);
3505          Set_Error_Posted (T);
3506       end if;
3507    end Analyze_Subtype_Indication;
3508
3509    ------------------------------
3510    -- Analyze_Type_Declaration --
3511    ------------------------------
3512
3513    procedure Analyze_Type_Declaration (N : Node_Id) is
3514       Def    : constant Node_Id   := Type_Definition (N);
3515       Def_Id : constant Entity_Id := Defining_Identifier (N);
3516       T      : Entity_Id;
3517       Prev   : Entity_Id;
3518
3519       Is_Remote : constant Boolean :=
3520                     (Is_Remote_Types (Current_Scope)
3521                        or else Is_Remote_Call_Interface (Current_Scope))
3522                     and then not (In_Private_Part (Current_Scope)
3523                                     or else In_Package_Body (Current_Scope));
3524
3525       procedure Check_Ops_From_Incomplete_Type;
3526       --  If there is a tagged incomplete partial view of the type, transfer
3527       --  its operations to the full view, and indicate that the type of the
3528       --  controlling parameter (s) is this full view.
3529
3530       ------------------------------------
3531       -- Check_Ops_From_Incomplete_Type --
3532       ------------------------------------
3533
3534       procedure Check_Ops_From_Incomplete_Type is
3535          Elmt   : Elmt_Id;
3536          Formal : Entity_Id;
3537          Op     : Entity_Id;
3538
3539       begin
3540          if Prev /= T
3541            and then Ekind (Prev) = E_Incomplete_Type
3542            and then Is_Tagged_Type (Prev)
3543            and then Is_Tagged_Type (T)
3544          then
3545             Elmt := First_Elmt (Primitive_Operations (Prev));
3546             while Present (Elmt) loop
3547                Op := Node (Elmt);
3548                Prepend_Elmt (Op, Primitive_Operations (T));
3549
3550                Formal := First_Formal (Op);
3551                while Present (Formal) loop
3552                   if Etype (Formal) = Prev then
3553                      Set_Etype (Formal, T);
3554                   end if;
3555
3556                   Next_Formal (Formal);
3557                end loop;
3558
3559                if Etype (Op) = Prev then
3560                   Set_Etype (Op, T);
3561                end if;
3562
3563                Next_Elmt (Elmt);
3564             end loop;
3565          end if;
3566       end Check_Ops_From_Incomplete_Type;
3567
3568    --  Start of processing for Analyze_Type_Declaration
3569
3570    begin
3571       Prev := Find_Type_Name (N);
3572
3573       --  The full view, if present, now points to the current type
3574
3575       --  Ada 2005 (AI-50217): If the type was previously decorated when
3576       --  imported through a LIMITED WITH clause, it appears as incomplete
3577       --  but has no full view.
3578       --  If the incomplete view is tagged, a class_wide type has been
3579       --  created already. Use it for the full view as well, to prevent
3580       --  multiple incompatible class-wide types that may be  created for
3581       --  self-referential anonymous access components.
3582
3583       if Ekind (Prev) = E_Incomplete_Type
3584         and then Present (Full_View (Prev))
3585       then
3586          T := Full_View (Prev);
3587
3588          if Is_Tagged_Type (Prev)
3589            and then Present (Class_Wide_Type (Prev))
3590          then
3591             Set_Ekind (T, Ekind (Prev));         --  will be reset later
3592             Set_Class_Wide_Type (T, Class_Wide_Type (Prev));
3593             Set_Etype (Class_Wide_Type (T), T);
3594          end if;
3595
3596       else
3597          T := Prev;
3598       end if;
3599
3600       Set_Is_Pure (T, Is_Pure (Current_Scope));
3601
3602       --  We set the flag Is_First_Subtype here. It is needed to set the
3603       --  corresponding flag for the Implicit class-wide-type created
3604       --  during tagged types processing.
3605
3606       Set_Is_First_Subtype (T, True);
3607
3608       --  Only composite types other than array types are allowed to have
3609       --  discriminants.
3610
3611       case Nkind (Def) is
3612
3613          --  For derived types, the rule will be checked once we've figured
3614          --  out the parent type.
3615
3616          when N_Derived_Type_Definition =>
3617             null;
3618
3619          --  For record types, discriminants are allowed
3620
3621          when N_Record_Definition =>
3622             null;
3623
3624          when others =>
3625             if Present (Discriminant_Specifications (N)) then
3626                Error_Msg_N
3627                  ("elementary or array type cannot have discriminants",
3628                   Defining_Identifier
3629                   (First (Discriminant_Specifications (N))));
3630             end if;
3631       end case;
3632
3633       --  Elaborate the type definition according to kind, and generate
3634       --  subsidiary (implicit) subtypes where needed. We skip this if it was
3635       --  already done (this happens during the reanalysis that follows a call
3636       --  to the high level optimizer).
3637
3638       if not Analyzed (T) then
3639          Set_Analyzed (T);
3640
3641          case Nkind (Def) is
3642
3643             when N_Access_To_Subprogram_Definition =>
3644                Access_Subprogram_Declaration (T, Def);
3645
3646                --  If this is a remote access to subprogram, we must create the
3647                --  equivalent fat pointer type, and related subprograms.
3648
3649                if Is_Remote then
3650                   Process_Remote_AST_Declaration (N);
3651                end if;
3652
3653                --  Validate categorization rule against access type declaration
3654                --  usually a violation in Pure unit, Shared_Passive unit.
3655
3656                Validate_Access_Type_Declaration (T, N);
3657
3658             when N_Access_To_Object_Definition =>
3659                Access_Type_Declaration (T, Def);
3660
3661                --  Validate categorization rule against access type declaration
3662                --  usually a violation in Pure unit, Shared_Passive unit.
3663
3664                Validate_Access_Type_Declaration (T, N);
3665
3666                --  If we are in a Remote_Call_Interface package and define
3667                --  a RACW, Read and Write attribute must be added.
3668
3669                if Is_Remote
3670                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
3671                then
3672                   Add_RACW_Features (Def_Id);
3673                end if;
3674
3675                --  Set no strict aliasing flag if config pragma seen
3676
3677                if Opt.No_Strict_Aliasing then
3678                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
3679                end if;
3680
3681             when N_Array_Type_Definition =>
3682                Array_Type_Declaration (T, Def);
3683
3684             when N_Derived_Type_Definition =>
3685                Derived_Type_Declaration (T, N, T /= Def_Id);
3686
3687             when N_Enumeration_Type_Definition =>
3688                Enumeration_Type_Declaration (T, Def);
3689
3690             when N_Floating_Point_Definition =>
3691                Floating_Point_Type_Declaration (T, Def);
3692
3693             when N_Decimal_Fixed_Point_Definition =>
3694                Decimal_Fixed_Point_Type_Declaration (T, Def);
3695
3696             when N_Ordinary_Fixed_Point_Definition =>
3697                Ordinary_Fixed_Point_Type_Declaration (T, Def);
3698
3699             when N_Signed_Integer_Type_Definition =>
3700                Signed_Integer_Type_Declaration (T, Def);
3701
3702             when N_Modular_Type_Definition =>
3703                Modular_Type_Declaration (T, Def);
3704
3705             when N_Record_Definition =>
3706                Record_Type_Declaration (T, N, Prev);
3707
3708             when others =>
3709                raise Program_Error;
3710
3711          end case;
3712       end if;
3713
3714       if Etype (T) = Any_Type then
3715          return;
3716       end if;
3717
3718       --  Some common processing for all types
3719
3720       Set_Depends_On_Private (T, Has_Private_Component (T));
3721       Check_Ops_From_Incomplete_Type;
3722
3723       --  Both the declared entity, and its anonymous base type if one
3724       --  was created, need freeze nodes allocated.
3725
3726       declare
3727          B : constant Entity_Id := Base_Type (T);
3728
3729       begin
3730          --  In the case where the base type is different from the first
3731          --  subtype, we pre-allocate a freeze node, and set the proper link
3732          --  to the first subtype. Freeze_Entity will use this preallocated
3733          --  freeze node when it freezes the entity.
3734
3735          if B /= T then
3736             Ensure_Freeze_Node (B);
3737             Set_First_Subtype_Link (Freeze_Node (B), T);
3738          end if;
3739
3740          if not From_With_Type (T) then
3741             Set_Has_Delayed_Freeze (T);
3742          end if;
3743       end;
3744
3745       --  Case of T is the full declaration of some private type which has
3746       --  been swapped in Defining_Identifier (N).
3747
3748       if T /= Def_Id and then Is_Private_Type (Def_Id) then
3749          Process_Full_View (N, T, Def_Id);
3750
3751          --  Record the reference. The form of this is a little strange,
3752          --  since the full declaration has been swapped in. So the first
3753          --  parameter here represents the entity to which a reference is
3754          --  made which is the "real" entity, i.e. the one swapped in,
3755          --  and the second parameter provides the reference location.
3756
3757          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
3758          --  since we don't want a complaint about the full type being an
3759          --  unwanted reference to the private type
3760
3761          declare
3762             B : constant Boolean := Has_Pragma_Unreferenced (T);
3763          begin
3764             Set_Has_Pragma_Unreferenced (T, False);
3765             Generate_Reference (T, T, 'c');
3766             Set_Has_Pragma_Unreferenced (T, B);
3767          end;
3768
3769          Set_Completion_Referenced (Def_Id);
3770
3771       --  For completion of incomplete type, process incomplete dependents
3772       --  and always mark the full type as referenced (it is the incomplete
3773       --  type that we get for any real reference).
3774
3775       elsif Ekind (Prev) = E_Incomplete_Type then
3776          Process_Incomplete_Dependents (N, T, Prev);
3777          Generate_Reference (Prev, Def_Id, 'c');
3778          Set_Completion_Referenced (Def_Id);
3779
3780       --  If not private type or incomplete type completion, this is a real
3781       --  definition of a new entity, so record it.
3782
3783       else
3784          Generate_Definition (Def_Id);
3785       end if;
3786
3787       if Chars (Scope (Def_Id)) =  Name_System
3788         and then Chars (Def_Id) = Name_Address
3789         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
3790       then
3791          Set_Is_Descendent_Of_Address (Def_Id);
3792          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
3793          Set_Is_Descendent_Of_Address (Prev);
3794       end if;
3795
3796       Check_Eliminated (Def_Id);
3797    end Analyze_Type_Declaration;
3798
3799    --------------------------
3800    -- Analyze_Variant_Part --
3801    --------------------------
3802
3803    procedure Analyze_Variant_Part (N : Node_Id) is
3804
3805       procedure Non_Static_Choice_Error (Choice : Node_Id);
3806       --  Error routine invoked by the generic instantiation below when
3807       --  the variant part has a non static choice.
3808
3809       procedure Process_Declarations (Variant : Node_Id);
3810       --  Analyzes all the declarations associated with a Variant.
3811       --  Needed by the generic instantiation below.
3812
3813       package Variant_Choices_Processing is new
3814         Generic_Choices_Processing
3815           (Get_Alternatives          => Variants,
3816            Get_Choices               => Discrete_Choices,
3817            Process_Empty_Choice      => No_OP,
3818            Process_Non_Static_Choice => Non_Static_Choice_Error,
3819            Process_Associated_Node   => Process_Declarations);
3820       use Variant_Choices_Processing;
3821       --  Instantiation of the generic choice processing package
3822
3823       -----------------------------
3824       -- Non_Static_Choice_Error --
3825       -----------------------------
3826
3827       procedure Non_Static_Choice_Error (Choice : Node_Id) is
3828       begin
3829          Flag_Non_Static_Expr
3830            ("choice given in variant part is not static!", Choice);
3831       end Non_Static_Choice_Error;
3832
3833       --------------------------
3834       -- Process_Declarations --
3835       --------------------------
3836
3837       procedure Process_Declarations (Variant : Node_Id) is
3838       begin
3839          if not Null_Present (Component_List (Variant)) then
3840             Analyze_Declarations (Component_Items (Component_List (Variant)));
3841
3842             if Present (Variant_Part (Component_List (Variant))) then
3843                Analyze (Variant_Part (Component_List (Variant)));
3844             end if;
3845          end if;
3846       end Process_Declarations;
3847
3848       --  Variables local to Analyze_Case_Statement
3849
3850       Discr_Name : Node_Id;
3851       Discr_Type : Entity_Id;
3852
3853       Case_Table     : Choice_Table_Type (1 .. Number_Of_Choices (N));
3854       Last_Choice    : Nat;
3855       Dont_Care      : Boolean;
3856       Others_Present : Boolean := False;
3857
3858       pragma Warnings (Off, Case_Table);
3859       pragma Warnings (Off, Last_Choice);
3860       pragma Warnings (Off, Dont_Care);
3861       pragma Warnings (Off, Others_Present);
3862       --  We don't care about the assigned values of any of these
3863
3864    --  Start of processing for Analyze_Variant_Part
3865
3866    begin
3867       Discr_Name := Name (N);
3868       Analyze (Discr_Name);
3869
3870       if Etype (Discr_Name) = Any_Type then
3871
3872          --  Prevent cascaded errors
3873
3874          return;
3875
3876       elsif Ekind (Entity (Discr_Name)) /= E_Discriminant then
3877          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
3878       end if;
3879
3880       Discr_Type := Etype (Entity (Discr_Name));
3881
3882       if not Is_Discrete_Type (Discr_Type) then
3883          Error_Msg_N
3884            ("discriminant in a variant part must be of a discrete type",
3885              Name (N));
3886          return;
3887       end if;
3888
3889       --  Call the instantiated Analyze_Choices which does the rest of the work
3890
3891       Analyze_Choices
3892         (N, Discr_Type, Case_Table, Last_Choice, Dont_Care, Others_Present);
3893    end Analyze_Variant_Part;
3894
3895    ----------------------------
3896    -- Array_Type_Declaration --
3897    ----------------------------
3898
3899    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
3900       Component_Def : constant Node_Id := Component_Definition (Def);
3901       Element_Type  : Entity_Id;
3902       Implicit_Base : Entity_Id;
3903       Index         : Node_Id;
3904       Related_Id    : Entity_Id := Empty;
3905       Nb_Index      : Nat;
3906       P             : constant Node_Id := Parent (Def);
3907       Priv          : Entity_Id;
3908
3909    begin
3910       if Nkind (Def) = N_Constrained_Array_Definition then
3911          Index := First (Discrete_Subtype_Definitions (Def));
3912       else
3913          Index := First (Subtype_Marks (Def));
3914       end if;
3915
3916       --  Find proper names for the implicit types which may be public.
3917       --  in case of anonymous arrays we use the name of the first object
3918       --  of that type as prefix.
3919
3920       if No (T) then
3921          Related_Id :=  Defining_Identifier (P);
3922       else
3923          Related_Id := T;
3924       end if;
3925
3926       Nb_Index := 1;
3927       while Present (Index) loop
3928          Analyze (Index);
3929
3930          --  Add a subtype declaration for each index of private array type
3931          --  declaration whose etype is also private. For example:
3932
3933          --     package Pkg is
3934          --        type Index is private;
3935          --     private
3936          --        type Table is array (Index) of ...
3937          --     end;
3938
3939          --  This is currently required by the expander to generate the
3940          --  internally generated equality subprogram of records with variant
3941          --  parts in which the etype of some component is such private type.
3942
3943          if Ekind (Current_Scope) = E_Package
3944            and then In_Private_Part (Current_Scope)
3945            and then Has_Private_Declaration (Etype (Index))
3946          then
3947             declare
3948                Loc   : constant Source_Ptr := Sloc (Def);
3949                New_E : Entity_Id;
3950                Decl  : Entity_Id;
3951
3952             begin
3953                New_E :=
3954                  Make_Defining_Identifier (Loc,
3955                    Chars => New_Internal_Name ('T'));
3956                Set_Is_Internal (New_E);
3957
3958                Decl :=
3959                  Make_Subtype_Declaration (Loc,
3960                    Defining_Identifier => New_E,
3961                    Subtype_Indication  =>
3962                      New_Occurrence_Of (Etype (Index), Loc));
3963
3964                Insert_Before (Parent (Def), Decl);
3965                Analyze (Decl);
3966                Set_Etype (Index, New_E);
3967
3968                --  If the index is a range the Entity attribute is not
3969                --  available. Example:
3970
3971                --     package Pkg is
3972                --        type T is private;
3973                --     private
3974                --        type T is new Natural;
3975                --        Table : array (T(1) .. T(10)) of Boolean;
3976                --     end Pkg;
3977
3978                if Nkind (Index) /= N_Range then
3979                   Set_Entity (Index, New_E);
3980                end if;
3981             end;
3982          end if;
3983
3984          Make_Index (Index, P, Related_Id, Nb_Index);
3985          Next_Index (Index);
3986          Nb_Index := Nb_Index + 1;
3987       end loop;
3988
3989       --  Process subtype indication if one is present
3990
3991       if Present (Subtype_Indication (Component_Def)) then
3992          Element_Type :=
3993            Process_Subtype
3994              (Subtype_Indication (Component_Def), P, Related_Id, 'C');
3995
3996       --  Ada 2005 (AI-230): Access Definition case
3997
3998       else pragma Assert (Present (Access_Definition (Component_Def)));
3999
4000          --  Indicate that the anonymous access type is created by the
4001          --  array type declaration.
4002
4003          Element_Type := Access_Definition
4004                            (Related_Nod => P,
4005                             N           => Access_Definition (Component_Def));
4006          Set_Is_Local_Anonymous_Access (Element_Type);
4007
4008          --  Propagate the parent. This field is needed if we have to generate
4009          --  the master_id associated with an anonymous access to task type
4010          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4011
4012          Set_Parent (Element_Type, Parent (T));
4013
4014          --  Ada 2005 (AI-230): In case of components that are anonymous
4015          --  access types the level of accessibility depends on the enclosing
4016          --  type declaration
4017
4018          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4019
4020          --  Ada 2005 (AI-254)
4021
4022          declare
4023             CD : constant Node_Id :=
4024                    Access_To_Subprogram_Definition
4025                      (Access_Definition (Component_Def));
4026          begin
4027             if Present (CD) and then Protected_Present (CD) then
4028                Element_Type :=
4029                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4030             end if;
4031          end;
4032       end if;
4033
4034       --  Constrained array case
4035
4036       if No (T) then
4037          T := Create_Itype (E_Void, P, Related_Id, 'T');
4038       end if;
4039
4040       if Nkind (Def) = N_Constrained_Array_Definition then
4041
4042          --  Establish Implicit_Base as unconstrained base type
4043
4044          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4045
4046          Init_Size_Align        (Implicit_Base);
4047          Set_Etype              (Implicit_Base, Implicit_Base);
4048          Set_Scope              (Implicit_Base, Current_Scope);
4049          Set_Has_Delayed_Freeze (Implicit_Base);
4050
4051          --  The constrained array type is a subtype of the unconstrained one
4052
4053          Set_Ekind          (T, E_Array_Subtype);
4054          Init_Size_Align    (T);
4055          Set_Etype          (T, Implicit_Base);
4056          Set_Scope          (T, Current_Scope);
4057          Set_Is_Constrained (T, True);
4058          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4059          Set_Has_Delayed_Freeze (T);
4060
4061          --  Complete setup of implicit base type
4062
4063          Set_First_Index       (Implicit_Base, First_Index (T));
4064          Set_Component_Type    (Implicit_Base, Element_Type);
4065          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4066          Set_Component_Size    (Implicit_Base, Uint_0);
4067          Set_Packed_Array_Type (Implicit_Base, Empty);
4068          Set_Has_Controlled_Component
4069                                (Implicit_Base, Has_Controlled_Component
4070                                                         (Element_Type)
4071                                                  or else Is_Controlled
4072                                                         (Element_Type));
4073          Set_Finalize_Storage_Only
4074                                (Implicit_Base, Finalize_Storage_Only
4075                                                         (Element_Type));
4076
4077       --  Unconstrained array case
4078
4079       else
4080          Set_Ekind                    (T, E_Array_Type);
4081          Init_Size_Align              (T);
4082          Set_Etype                    (T, T);
4083          Set_Scope                    (T, Current_Scope);
4084          Set_Component_Size           (T, Uint_0);
4085          Set_Is_Constrained           (T, False);
4086          Set_First_Index              (T, First (Subtype_Marks (Def)));
4087          Set_Has_Delayed_Freeze       (T, True);
4088          Set_Has_Task                 (T, Has_Task      (Element_Type));
4089          Set_Has_Controlled_Component (T, Has_Controlled_Component
4090                                                         (Element_Type)
4091                                             or else
4092                                           Is_Controlled (Element_Type));
4093          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4094                                                         (Element_Type));
4095       end if;
4096
4097       --  Common attributes for both cases
4098
4099       Set_Component_Type (Base_Type (T), Element_Type);
4100       Set_Packed_Array_Type (T, Empty);
4101
4102       if Aliased_Present (Component_Definition (Def)) then
4103          Set_Has_Aliased_Components (Etype (T));
4104       end if;
4105
4106       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4107       --  array type to ensure that objects of this type are initialized.
4108
4109       if Ada_Version >= Ada_05
4110         and then Can_Never_Be_Null (Element_Type)
4111       then
4112          Set_Can_Never_Be_Null (T);
4113
4114          if Null_Exclusion_Present (Component_Definition (Def))
4115
4116             --  No need to check itypes because in their case this check
4117             --  was done at their point of creation
4118
4119            and then not Is_Itype (Element_Type)
4120          then
4121             Error_Msg_N
4122               ("`NOT NULL` not allowed (null already excluded)",
4123                Subtype_Indication (Component_Definition (Def)));
4124          end if;
4125       end if;
4126
4127       Priv := Private_Component (Element_Type);
4128
4129       if Present (Priv) then
4130
4131          --  Check for circular definitions
4132
4133          if Priv = Any_Type then
4134             Set_Component_Type (Etype (T), Any_Type);
4135
4136          --  There is a gap in the visibility of operations on the composite
4137          --  type only if the component type is defined in a different scope.
4138
4139          elsif Scope (Priv) = Current_Scope then
4140             null;
4141
4142          elsif Is_Limited_Type (Priv) then
4143             Set_Is_Limited_Composite (Etype (T));
4144             Set_Is_Limited_Composite (T);
4145          else
4146             Set_Is_Private_Composite (Etype (T));
4147             Set_Is_Private_Composite (T);
4148          end if;
4149       end if;
4150
4151       --  A syntax error in the declaration itself may lead to an empty
4152       --  index list, in which case do a minimal patch.
4153
4154       if No (First_Index (T)) then
4155          Error_Msg_N ("missing index definition in array type declaration", T);
4156
4157          declare
4158             Indices : constant List_Id :=
4159                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4160          begin
4161             Set_Discrete_Subtype_Definitions (Def, Indices);
4162             Set_First_Index (T, First (Indices));
4163             return;
4164          end;
4165       end if;
4166
4167       --  Create a concatenation operator for the new type. Internal array
4168       --  types created for packed entities do not need such, they are
4169       --  compatible with the user-defined type.
4170
4171       if Number_Dimensions (T) = 1
4172          and then not Is_Packed_Array_Type (T)
4173       then
4174          New_Concatenation_Op (T);
4175       end if;
4176
4177       --  In the case of an unconstrained array the parser has already verified
4178       --  that all the indices are unconstrained but we still need to make sure
4179       --  that the element type is constrained.
4180
4181       if Is_Indefinite_Subtype (Element_Type) then
4182          Error_Msg_N
4183            ("unconstrained element type in array declaration",
4184             Subtype_Indication (Component_Def));
4185
4186       elsif Is_Abstract_Type (Element_Type) then
4187          Error_Msg_N
4188            ("the type of a component cannot be abstract",
4189             Subtype_Indication (Component_Def));
4190       end if;
4191
4192    end Array_Type_Declaration;
4193
4194    ------------------------------------------------------
4195    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4196    ------------------------------------------------------
4197
4198    function Replace_Anonymous_Access_To_Protected_Subprogram
4199      (N : Node_Id) return Entity_Id
4200    is
4201       Loc : constant Source_Ptr := Sloc (N);
4202
4203       Curr_Scope : constant Scope_Stack_Entry :=
4204                      Scope_Stack.Table (Scope_Stack.Last);
4205
4206       Anon : constant Entity_Id :=
4207                Make_Defining_Identifier (Loc,
4208                  Chars => New_Internal_Name ('S'));
4209
4210       Acc  : Node_Id;
4211       Comp : Node_Id;
4212       Decl : Node_Id;
4213       P    : Node_Id;
4214
4215    begin
4216       Set_Is_Internal (Anon);
4217
4218       case Nkind (N) is
4219          when N_Component_Declaration       |
4220            N_Unconstrained_Array_Definition |
4221            N_Constrained_Array_Definition   =>
4222             Comp := Component_Definition (N);
4223             Acc  := Access_Definition (Comp);
4224
4225          when N_Discriminant_Specification =>
4226             Comp := Discriminant_Type (N);
4227             Acc  := Comp;
4228
4229          when N_Parameter_Specification =>
4230             Comp := Parameter_Type (N);
4231             Acc  := Comp;
4232
4233          when N_Access_Function_Definition  =>
4234             Comp := Result_Definition (N);
4235             Acc  := Comp;
4236
4237          when N_Object_Declaration  =>
4238             Comp := Object_Definition (N);
4239             Acc  := Comp;
4240
4241          when others =>
4242             raise Program_Error;
4243       end case;
4244
4245       Decl := Make_Full_Type_Declaration (Loc,
4246                 Defining_Identifier => Anon,
4247                 Type_Definition   =>
4248                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
4249
4250       Mark_Rewrite_Insertion (Decl);
4251
4252       --  Insert the new declaration in the nearest enclosing scope
4253
4254       P := Parent (N);
4255       while Present (P) and then not Has_Declarations (P) loop
4256          P := Parent (P);
4257       end loop;
4258
4259       pragma Assert (Present (P));
4260
4261       if Nkind (P) = N_Package_Specification then
4262          Prepend (Decl, Visible_Declarations (P));
4263       else
4264          Prepend (Decl, Declarations (P));
4265       end if;
4266
4267       --  Replace the anonymous type with an occurrence of the new declaration.
4268       --  In all cases the rewritten node does not have the null-exclusion
4269       --  attribute because (if present) it was already inherited by the
4270       --  anonymous entity (Anon). Thus, in case of components we do not
4271       --  inherit this attribute.
4272
4273       if Nkind (N) = N_Parameter_Specification then
4274          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4275          Set_Etype (Defining_Identifier (N), Anon);
4276          Set_Null_Exclusion_Present (N, False);
4277
4278       elsif Nkind (N) = N_Object_Declaration then
4279          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4280          Set_Etype (Defining_Identifier (N), Anon);
4281
4282       elsif Nkind (N) = N_Access_Function_Definition then
4283          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4284
4285       else
4286          Rewrite (Comp,
4287            Make_Component_Definition (Loc,
4288              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
4289       end if;
4290
4291       Mark_Rewrite_Insertion (Comp);
4292
4293       --  Temporarily remove the current scope from the stack to add the new
4294       --  declarations to the enclosing scope
4295
4296       if Nkind (N) = N_Object_Declaration
4297         or else Nkind (N) = N_Access_Function_Definition
4298       then
4299          Analyze (Decl);
4300
4301       else
4302          Scope_Stack.Decrement_Last;
4303          Analyze (Decl);
4304          Set_Is_Itype (Anon);
4305          Scope_Stack.Append (Curr_Scope);
4306       end if;
4307
4308       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
4309       return Anon;
4310    end Replace_Anonymous_Access_To_Protected_Subprogram;
4311
4312    -------------------------------
4313    -- Build_Derived_Access_Type --
4314    -------------------------------
4315
4316    procedure Build_Derived_Access_Type
4317      (N            : Node_Id;
4318       Parent_Type  : Entity_Id;
4319       Derived_Type : Entity_Id)
4320    is
4321       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
4322
4323       Desig_Type      : Entity_Id;
4324       Discr           : Entity_Id;
4325       Discr_Con_Elist : Elist_Id;
4326       Discr_Con_El    : Elmt_Id;
4327       Subt            : Entity_Id;
4328
4329    begin
4330       --  Set the designated type so it is available in case this is an access
4331       --  to a self-referential type, e.g. a standard list type with a next
4332       --  pointer. Will be reset after subtype is built.
4333
4334       Set_Directly_Designated_Type
4335         (Derived_Type, Designated_Type (Parent_Type));
4336
4337       Subt := Process_Subtype (S, N);
4338
4339       if Nkind (S) /= N_Subtype_Indication
4340         and then Subt /= Base_Type (Subt)
4341       then
4342          Set_Ekind (Derived_Type, E_Access_Subtype);
4343       end if;
4344
4345       if Ekind (Derived_Type) = E_Access_Subtype then
4346          declare
4347             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
4348             Ibase      : constant Entity_Id :=
4349                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
4350             Svg_Chars  : constant Name_Id   := Chars (Ibase);
4351             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
4352
4353          begin
4354             Copy_Node (Pbase, Ibase);
4355
4356             Set_Chars             (Ibase, Svg_Chars);
4357             Set_Next_Entity       (Ibase, Svg_Next_E);
4358             Set_Sloc              (Ibase, Sloc (Derived_Type));
4359             Set_Scope             (Ibase, Scope (Derived_Type));
4360             Set_Freeze_Node       (Ibase, Empty);
4361             Set_Is_Frozen         (Ibase, False);
4362             Set_Comes_From_Source (Ibase, False);
4363             Set_Is_First_Subtype  (Ibase, False);
4364
4365             Set_Etype (Ibase, Pbase);
4366             Set_Etype (Derived_Type, Ibase);
4367          end;
4368       end if;
4369
4370       Set_Directly_Designated_Type
4371         (Derived_Type, Designated_Type (Subt));
4372
4373       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
4374       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
4375       Set_Size_Info          (Derived_Type,                     Parent_Type);
4376       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
4377       Set_Depends_On_Private (Derived_Type,
4378                               Has_Private_Component (Derived_Type));
4379       Conditional_Delay      (Derived_Type, Subt);
4380
4381       --  Ada 2005 (AI-231). Set the null-exclusion attribute
4382
4383       if Null_Exclusion_Present (Type_Definition (N))
4384         or else Can_Never_Be_Null (Parent_Type)
4385       then
4386          Set_Can_Never_Be_Null (Derived_Type);
4387       end if;
4388
4389       --  Note: we do not copy the Storage_Size_Variable, since we always go to
4390       --  the root type for this information.
4391
4392       --  Apply range checks to discriminants for derived record case
4393       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
4394
4395       Desig_Type := Designated_Type (Derived_Type);
4396       if Is_Composite_Type (Desig_Type)
4397         and then (not Is_Array_Type (Desig_Type))
4398         and then Has_Discriminants (Desig_Type)
4399         and then Base_Type (Desig_Type) /= Desig_Type
4400       then
4401          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
4402          Discr_Con_El := First_Elmt (Discr_Con_Elist);
4403
4404          Discr := First_Discriminant (Base_Type (Desig_Type));
4405          while Present (Discr_Con_El) loop
4406             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
4407             Next_Elmt (Discr_Con_El);
4408             Next_Discriminant (Discr);
4409          end loop;
4410       end if;
4411    end Build_Derived_Access_Type;
4412
4413    ------------------------------
4414    -- Build_Derived_Array_Type --
4415    ------------------------------
4416
4417    procedure Build_Derived_Array_Type
4418      (N            : Node_Id;
4419       Parent_Type  : Entity_Id;
4420       Derived_Type : Entity_Id)
4421    is
4422       Loc           : constant Source_Ptr := Sloc (N);
4423       Tdef          : constant Node_Id    := Type_Definition (N);
4424       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
4425       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
4426       Implicit_Base : Entity_Id;
4427       New_Indic     : Node_Id;
4428
4429       procedure Make_Implicit_Base;
4430       --  If the parent subtype is constrained, the derived type is a subtype
4431       --  of an implicit base type derived from the parent base.
4432
4433       ------------------------
4434       -- Make_Implicit_Base --
4435       ------------------------
4436
4437       procedure Make_Implicit_Base is
4438       begin
4439          Implicit_Base :=
4440            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
4441
4442          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
4443          Set_Etype (Implicit_Base, Parent_Base);
4444
4445          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
4446          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
4447
4448          Set_Has_Delayed_Freeze (Implicit_Base, True);
4449       end Make_Implicit_Base;
4450
4451    --  Start of processing for Build_Derived_Array_Type
4452
4453    begin
4454       if not Is_Constrained (Parent_Type) then
4455          if Nkind (Indic) /= N_Subtype_Indication then
4456             Set_Ekind (Derived_Type, E_Array_Type);
4457
4458             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
4459             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
4460
4461             Set_Has_Delayed_Freeze (Derived_Type, True);
4462
4463          else
4464             Make_Implicit_Base;
4465             Set_Etype (Derived_Type, Implicit_Base);
4466
4467             New_Indic :=
4468               Make_Subtype_Declaration (Loc,
4469                 Defining_Identifier => Derived_Type,
4470                 Subtype_Indication  =>
4471                   Make_Subtype_Indication (Loc,
4472                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
4473                     Constraint => Constraint (Indic)));
4474
4475             Rewrite (N, New_Indic);
4476             Analyze (N);
4477          end if;
4478
4479       else
4480          if Nkind (Indic) /= N_Subtype_Indication then
4481             Make_Implicit_Base;
4482
4483             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
4484             Set_Etype             (Derived_Type, Implicit_Base);
4485             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
4486
4487          else
4488             Error_Msg_N ("illegal constraint on constrained type", Indic);
4489          end if;
4490       end if;
4491
4492       --  If parent type is not a derived type itself, and is declared in
4493       --  closed scope (e.g. a subprogram), then we must explicitly introduce
4494       --  the new type's concatenation operator since Derive_Subprograms
4495       --  will not inherit the parent's operator. If the parent type is
4496       --  unconstrained, the operator is of the unconstrained base type.
4497
4498       if Number_Dimensions (Parent_Type) = 1
4499         and then not Is_Limited_Type (Parent_Type)
4500         and then not Is_Derived_Type (Parent_Type)
4501         and then not Is_Package_Or_Generic_Package
4502                        (Scope (Base_Type (Parent_Type)))
4503       then
4504          if not Is_Constrained (Parent_Type)
4505            and then Is_Constrained (Derived_Type)
4506          then
4507             New_Concatenation_Op (Implicit_Base);
4508          else
4509             New_Concatenation_Op (Derived_Type);
4510          end if;
4511       end if;
4512    end Build_Derived_Array_Type;
4513
4514    -----------------------------------
4515    -- Build_Derived_Concurrent_Type --
4516    -----------------------------------
4517
4518    procedure Build_Derived_Concurrent_Type
4519      (N            : Node_Id;
4520       Parent_Type  : Entity_Id;
4521       Derived_Type : Entity_Id)
4522    is
4523       D_Constraint : Node_Id;
4524       Disc_Spec    : Node_Id;
4525       Old_Disc     : Entity_Id;
4526       New_Disc     : Entity_Id;
4527
4528       Constraint_Present : constant Boolean :=
4529                              Nkind (Subtype_Indication (Type_Definition (N)))
4530                                                      = N_Subtype_Indication;
4531
4532    begin
4533       Set_Stored_Constraint (Derived_Type, No_Elist);
4534
4535       if Is_Task_Type (Parent_Type) then
4536          Set_Storage_Size_Variable (Derived_Type,
4537            Storage_Size_Variable (Parent_Type));
4538       end if;
4539
4540       if Present (Discriminant_Specifications (N)) then
4541          Push_Scope (Derived_Type);
4542          Check_Or_Process_Discriminants (N, Derived_Type);
4543          End_Scope;
4544
4545       elsif Constraint_Present then
4546
4547          --  Build constrained subtype and derive from it
4548
4549          declare
4550             Loc  : constant Source_Ptr := Sloc (N);
4551             Anon : constant Entity_Id :=
4552                      Make_Defining_Identifier (Loc,
4553                        New_External_Name (Chars (Derived_Type), 'T'));
4554             Decl : Node_Id;
4555
4556          begin
4557             Decl :=
4558               Make_Subtype_Declaration (Loc,
4559                 Defining_Identifier => Anon,
4560                 Subtype_Indication =>
4561                   Subtype_Indication (Type_Definition (N)));
4562             Insert_Before (N, Decl);
4563             Analyze (Decl);
4564
4565             Rewrite (Subtype_Indication (Type_Definition (N)),
4566               New_Occurrence_Of (Anon, Loc));
4567             Set_Analyzed (Derived_Type, False);
4568             Analyze (N);
4569             return;
4570          end;
4571       end if;
4572
4573       --  All attributes are inherited from parent. In particular,
4574       --  entries and the corresponding record type are the same.
4575       --  Discriminants may be renamed, and must be treated separately.
4576
4577       Set_Has_Discriminants
4578         (Derived_Type, Has_Discriminants         (Parent_Type));
4579       Set_Corresponding_Record_Type
4580         (Derived_Type, Corresponding_Record_Type (Parent_Type));
4581
4582       --  Is_Constrained is set according the parent subtype, but is set to
4583       --  False if the derived type is declared with new discriminants.
4584
4585       Set_Is_Constrained
4586         (Derived_Type,
4587          (Is_Constrained (Parent_Type) or else Constraint_Present)
4588            and then not Present (Discriminant_Specifications (N)));
4589
4590       if Constraint_Present then
4591          if not Has_Discriminants (Parent_Type) then
4592             Error_Msg_N ("untagged parent must have discriminants", N);
4593
4594          elsif Present (Discriminant_Specifications (N)) then
4595
4596             --  Verify that new discriminants are used to constrain old ones
4597
4598             D_Constraint :=
4599               First
4600                 (Constraints
4601                   (Constraint (Subtype_Indication (Type_Definition (N)))));
4602
4603             Old_Disc  := First_Discriminant (Parent_Type);
4604             New_Disc  := First_Discriminant (Derived_Type);
4605             Disc_Spec := First (Discriminant_Specifications (N));
4606             while Present (Old_Disc) and then Present (Disc_Spec) loop
4607                if Nkind (Discriminant_Type (Disc_Spec)) /=
4608                                               N_Access_Definition
4609                then
4610                   Analyze (Discriminant_Type (Disc_Spec));
4611
4612                   if not Subtypes_Statically_Compatible (
4613                              Etype (Discriminant_Type (Disc_Spec)),
4614                                Etype (Old_Disc))
4615                   then
4616                      Error_Msg_N
4617                        ("not statically compatible with parent discriminant",
4618                         Discriminant_Type (Disc_Spec));
4619                   end if;
4620                end if;
4621
4622                if Nkind (D_Constraint) = N_Identifier
4623                  and then Chars (D_Constraint) /=
4624                    Chars (Defining_Identifier (Disc_Spec))
4625                then
4626                   Error_Msg_N ("new discriminants must constrain old ones",
4627                     D_Constraint);
4628                else
4629                   Set_Corresponding_Discriminant (New_Disc, Old_Disc);
4630                end if;
4631
4632                Next_Discriminant (Old_Disc);
4633                Next_Discriminant (New_Disc);
4634                Next (Disc_Spec);
4635             end loop;
4636
4637             if Present (Old_Disc) or else Present (Disc_Spec) then
4638                Error_Msg_N ("discriminant mismatch in derivation", N);
4639             end if;
4640
4641          end if;
4642
4643       elsif Present (Discriminant_Specifications (N)) then
4644          Error_Msg_N
4645            ("missing discriminant constraint in untagged derivation",
4646             N);
4647       end if;
4648
4649       if Present (Discriminant_Specifications (N)) then
4650          Old_Disc := First_Discriminant (Parent_Type);
4651          while Present (Old_Disc) loop
4652
4653             if No (Next_Entity (Old_Disc))
4654               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
4655             then
4656                Set_Next_Entity (Last_Entity (Derived_Type),
4657                                          Next_Entity (Old_Disc));
4658                exit;
4659             end if;
4660
4661             Next_Discriminant (Old_Disc);
4662          end loop;
4663
4664       else
4665          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
4666          if Has_Discriminants (Parent_Type) then
4667             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
4668             Set_Discriminant_Constraint (
4669               Derived_Type, Discriminant_Constraint (Parent_Type));
4670          end if;
4671       end if;
4672
4673       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
4674
4675       Set_Has_Completion (Derived_Type);
4676    end Build_Derived_Concurrent_Type;
4677
4678    ------------------------------------
4679    -- Build_Derived_Enumeration_Type --
4680    ------------------------------------
4681
4682    procedure Build_Derived_Enumeration_Type
4683      (N            : Node_Id;
4684       Parent_Type  : Entity_Id;
4685       Derived_Type : Entity_Id)
4686    is
4687       Loc           : constant Source_Ptr := Sloc (N);
4688       Def           : constant Node_Id    := Type_Definition (N);
4689       Indic         : constant Node_Id    := Subtype_Indication (Def);
4690       Implicit_Base : Entity_Id;
4691       Literal       : Entity_Id;
4692       New_Lit       : Entity_Id;
4693       Literals_List : List_Id;
4694       Type_Decl     : Node_Id;
4695       Hi, Lo        : Node_Id;
4696       Rang_Expr     : Node_Id;
4697
4698    begin
4699       --  Since types Standard.Character and Standard.Wide_Character do
4700       --  not have explicit literals lists we need to process types derived
4701       --  from them specially. This is handled by Derived_Standard_Character.
4702       --  If the parent type is a generic type, there are no literals either,
4703       --  and we construct the same skeletal representation as for the generic
4704       --  parent type.
4705
4706       if Root_Type (Parent_Type) = Standard_Character
4707         or else Root_Type (Parent_Type) = Standard_Wide_Character
4708         or else Root_Type (Parent_Type) = Standard_Wide_Wide_Character
4709       then
4710          Derived_Standard_Character (N, Parent_Type, Derived_Type);
4711
4712       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
4713          declare
4714             Lo : Node_Id;
4715             Hi : Node_Id;
4716
4717          begin
4718             Lo :=
4719                Make_Attribute_Reference (Loc,
4720                  Attribute_Name => Name_First,
4721                  Prefix => New_Reference_To (Derived_Type, Loc));
4722             Set_Etype (Lo, Derived_Type);
4723
4724             Hi :=
4725                Make_Attribute_Reference (Loc,
4726                  Attribute_Name => Name_Last,
4727                  Prefix => New_Reference_To (Derived_Type, Loc));
4728             Set_Etype (Hi, Derived_Type);
4729
4730             Set_Scalar_Range (Derived_Type,
4731                Make_Range (Loc,
4732                  Low_Bound => Lo,
4733                  High_Bound => Hi));
4734          end;
4735
4736       else
4737          --  If a constraint is present, analyze the bounds to catch
4738          --  premature usage of the derived literals.
4739
4740          if Nkind (Indic) = N_Subtype_Indication
4741            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
4742          then
4743             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
4744             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
4745          end if;
4746
4747          --  Introduce an implicit base type for the derived type even if there
4748          --  is no constraint attached to it, since this seems closer to the
4749          --  Ada semantics. Build a full type declaration tree for the derived
4750          --  type using the implicit base type as the defining identifier. The
4751          --  build a subtype declaration tree which applies the constraint (if
4752          --  any) have it replace the derived type declaration.
4753
4754          Literal := First_Literal (Parent_Type);
4755          Literals_List := New_List;
4756          while Present (Literal)
4757            and then Ekind (Literal) = E_Enumeration_Literal
4758          loop
4759             --  Literals of the derived type have the same representation as
4760             --  those of the parent type, but this representation can be
4761             --  overridden by an explicit representation clause. Indicate
4762             --  that there is no explicit representation given yet. These
4763             --  derived literals are implicit operations of the new type,
4764             --  and can be overridden by explicit ones.
4765
4766             if Nkind (Literal) = N_Defining_Character_Literal then
4767                New_Lit :=
4768                  Make_Defining_Character_Literal (Loc, Chars (Literal));
4769             else
4770                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
4771             end if;
4772
4773             Set_Ekind                (New_Lit, E_Enumeration_Literal);
4774             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
4775             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
4776             Set_Enumeration_Rep_Expr (New_Lit, Empty);
4777             Set_Alias                (New_Lit, Literal);
4778             Set_Is_Known_Valid       (New_Lit, True);
4779
4780             Append (New_Lit, Literals_List);
4781             Next_Literal (Literal);
4782          end loop;
4783
4784          Implicit_Base :=
4785            Make_Defining_Identifier (Sloc (Derived_Type),
4786              New_External_Name (Chars (Derived_Type), 'B'));
4787
4788          --  Indicate the proper nature of the derived type. This must be done
4789          --  before analysis of the literals, to recognize cases when a literal
4790          --  may be hidden by a previous explicit function definition (cf.
4791          --  c83031a).
4792
4793          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
4794          Set_Etype (Derived_Type, Implicit_Base);
4795
4796          Type_Decl :=
4797            Make_Full_Type_Declaration (Loc,
4798              Defining_Identifier => Implicit_Base,
4799              Discriminant_Specifications => No_List,
4800              Type_Definition =>
4801                Make_Enumeration_Type_Definition (Loc, Literals_List));
4802
4803          Mark_Rewrite_Insertion (Type_Decl);
4804          Insert_Before (N, Type_Decl);
4805          Analyze (Type_Decl);
4806
4807          --  After the implicit base is analyzed its Etype needs to be changed
4808          --  to reflect the fact that it is derived from the parent type which
4809          --  was ignored during analysis. We also set the size at this point.
4810
4811          Set_Etype (Implicit_Base, Parent_Type);
4812
4813          Set_Size_Info      (Implicit_Base,                 Parent_Type);
4814          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
4815          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
4816
4817          Set_Has_Non_Standard_Rep
4818                             (Implicit_Base, Has_Non_Standard_Rep
4819                                                            (Parent_Type));
4820          Set_Has_Delayed_Freeze (Implicit_Base);
4821
4822          --  Process the subtype indication including a validation check on the
4823          --  constraint, if any. If a constraint is given, its bounds must be
4824          --  implicitly converted to the new type.
4825
4826          if Nkind (Indic) = N_Subtype_Indication then
4827             declare
4828                R : constant Node_Id :=
4829                      Range_Expression (Constraint (Indic));
4830
4831             begin
4832                if Nkind (R) = N_Range then
4833                   Hi := Build_Scalar_Bound
4834                           (High_Bound (R), Parent_Type, Implicit_Base);
4835                   Lo := Build_Scalar_Bound
4836                           (Low_Bound  (R), Parent_Type, Implicit_Base);
4837
4838                else
4839                   --  Constraint is a Range attribute. Replace with explicit
4840                   --  mention of the bounds of the prefix, which must be a
4841                   --  subtype.
4842
4843                   Analyze (Prefix (R));
4844                   Hi :=
4845                     Convert_To (Implicit_Base,
4846                       Make_Attribute_Reference (Loc,
4847                         Attribute_Name => Name_Last,
4848                         Prefix =>
4849                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
4850
4851                   Lo :=
4852                     Convert_To (Implicit_Base,
4853                       Make_Attribute_Reference (Loc,
4854                         Attribute_Name => Name_First,
4855                         Prefix =>
4856                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
4857                end if;
4858             end;
4859
4860          else
4861             Hi :=
4862               Build_Scalar_Bound
4863                 (Type_High_Bound (Parent_Type),
4864                  Parent_Type, Implicit_Base);
4865             Lo :=
4866                Build_Scalar_Bound
4867                  (Type_Low_Bound (Parent_Type),
4868                   Parent_Type, Implicit_Base);
4869          end if;
4870
4871          Rang_Expr :=
4872            Make_Range (Loc,
4873              Low_Bound  => Lo,
4874              High_Bound => Hi);
4875
4876          --  If we constructed a default range for the case where no range
4877          --  was given, then the expressions in the range must not freeze
4878          --  since they do not correspond to expressions in the source.
4879
4880          if Nkind (Indic) /= N_Subtype_Indication then
4881             Set_Must_Not_Freeze (Lo);
4882             Set_Must_Not_Freeze (Hi);
4883             Set_Must_Not_Freeze (Rang_Expr);
4884          end if;
4885
4886          Rewrite (N,
4887            Make_Subtype_Declaration (Loc,
4888              Defining_Identifier => Derived_Type,
4889              Subtype_Indication =>
4890                Make_Subtype_Indication (Loc,
4891                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
4892                  Constraint =>
4893                    Make_Range_Constraint (Loc,
4894                      Range_Expression => Rang_Expr))));
4895
4896          Analyze (N);
4897
4898          --  If pragma Discard_Names applies on the first subtype of the parent
4899          --  type, then it must be applied on this subtype as well.
4900
4901          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
4902             Set_Discard_Names (Derived_Type);
4903          end if;
4904
4905          --  Apply a range check. Since this range expression doesn't have an
4906          --  Etype, we have to specifically pass the Source_Typ parameter. Is
4907          --  this right???
4908
4909          if Nkind (Indic) = N_Subtype_Indication then
4910             Apply_Range_Check (Range_Expression (Constraint (Indic)),
4911                                Parent_Type,
4912                                Source_Typ => Entity (Subtype_Mark (Indic)));
4913          end if;
4914       end if;
4915    end Build_Derived_Enumeration_Type;
4916
4917    --------------------------------
4918    -- Build_Derived_Numeric_Type --
4919    --------------------------------
4920
4921    procedure Build_Derived_Numeric_Type
4922      (N            : Node_Id;
4923       Parent_Type  : Entity_Id;
4924       Derived_Type : Entity_Id)
4925    is
4926       Loc           : constant Source_Ptr := Sloc (N);
4927       Tdef          : constant Node_Id    := Type_Definition (N);
4928       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
4929       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
4930       No_Constraint : constant Boolean    := Nkind (Indic) /=
4931                                                   N_Subtype_Indication;
4932       Implicit_Base : Entity_Id;
4933
4934       Lo : Node_Id;
4935       Hi : Node_Id;
4936
4937    begin
4938       --  Process the subtype indication including a validation check on
4939       --  the constraint if any.
4940
4941       Discard_Node (Process_Subtype (Indic, N));
4942
4943       --  Introduce an implicit base type for the derived type even if there
4944       --  is no constraint attached to it, since this seems closer to the Ada
4945       --  semantics.
4946
4947       Implicit_Base :=
4948         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
4949
4950       Set_Etype          (Implicit_Base, Parent_Base);
4951       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
4952       Set_Size_Info      (Implicit_Base,                 Parent_Base);
4953       Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Base));
4954       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
4955       Set_Parent         (Implicit_Base, Parent (Derived_Type));
4956
4957       if Is_Discrete_Or_Fixed_Point_Type (Parent_Base) then
4958          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
4959       end if;
4960
4961       Set_Has_Delayed_Freeze (Implicit_Base);
4962
4963       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
4964       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
4965
4966       Set_Scalar_Range (Implicit_Base,
4967         Make_Range (Loc,
4968           Low_Bound  => Lo,
4969           High_Bound => Hi));
4970
4971       if Has_Infinities (Parent_Base) then
4972          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
4973       end if;
4974
4975       --  The Derived_Type, which is the entity of the declaration, is a
4976       --  subtype of the implicit base. Its Ekind is a subtype, even in the
4977       --  absence of an explicit constraint.
4978
4979       Set_Etype (Derived_Type, Implicit_Base);
4980
4981       --  If we did not have a constraint, then the Ekind is set from the
4982       --  parent type (otherwise Process_Subtype has set the bounds)
4983
4984       if No_Constraint then
4985          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
4986       end if;
4987
4988       --  If we did not have a range constraint, then set the range from the
4989       --  parent type. Otherwise, the call to Process_Subtype has set the
4990       --  bounds.
4991
4992       if No_Constraint
4993         or else not Has_Range_Constraint (Indic)
4994       then
4995          Set_Scalar_Range (Derived_Type,
4996            Make_Range (Loc,
4997              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
4998              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
4999          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5000
5001          if Has_Infinities (Parent_Type) then
5002             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5003          end if;
5004       end if;
5005
5006       Set_Is_Descendent_Of_Address (Derived_Type,
5007         Is_Descendent_Of_Address (Parent_Type));
5008       Set_Is_Descendent_Of_Address (Implicit_Base,
5009         Is_Descendent_Of_Address (Parent_Type));
5010
5011       --  Set remaining type-specific fields, depending on numeric type
5012
5013       if Is_Modular_Integer_Type (Parent_Type) then
5014          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5015
5016          Set_Non_Binary_Modulus
5017            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5018
5019       elsif Is_Floating_Point_Type (Parent_Type) then
5020
5021          --  Digits of base type is always copied from the digits value of
5022          --  the parent base type, but the digits of the derived type will
5023          --  already have been set if there was a constraint present.
5024
5025          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5026          Set_Vax_Float    (Implicit_Base, Vax_Float    (Parent_Base));
5027
5028          if No_Constraint then
5029             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5030          end if;
5031
5032       elsif Is_Fixed_Point_Type (Parent_Type) then
5033
5034          --  Small of base type and derived type are always copied from the
5035          --  parent base type, since smalls never change. The delta of the
5036          --  base type is also copied from the parent base type. However the
5037          --  delta of the derived type will have been set already if a
5038          --  constraint was present.
5039
5040          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5041          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5042          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5043
5044          if No_Constraint then
5045             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5046          end if;
5047
5048          --  The scale and machine radix in the decimal case are always
5049          --  copied from the parent base type.
5050
5051          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
5052             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
5053             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
5054
5055             Set_Machine_Radix_10
5056               (Derived_Type,  Machine_Radix_10 (Parent_Base));
5057             Set_Machine_Radix_10
5058               (Implicit_Base, Machine_Radix_10 (Parent_Base));
5059
5060             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5061
5062             if No_Constraint then
5063                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
5064
5065             else
5066                --  the analysis of the subtype_indication sets the
5067                --  digits value of the derived type.
5068
5069                null;
5070             end if;
5071          end if;
5072       end if;
5073
5074       --  The type of the bounds is that of the parent type, and they
5075       --  must be converted to the derived type.
5076
5077       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
5078
5079       --  The implicit_base should be frozen when the derived type is frozen,
5080       --  but note that it is used in the conversions of the bounds. For fixed
5081       --  types we delay the determination of the bounds until the proper
5082       --  freezing point. For other numeric types this is rejected by GCC, for
5083       --  reasons that are currently unclear (???), so we choose to freeze the
5084       --  implicit base now. In the case of integers and floating point types
5085       --  this is harmless because subsequent representation clauses cannot
5086       --  affect anything, but it is still baffling that we cannot use the
5087       --  same mechanism for all derived numeric types.
5088
5089       --  There is a further complication: actually *some* representation
5090       --  clauses can affect the implicit base type. Namely, attribute
5091       --  definition clauses for stream-oriented attributes need to set the
5092       --  corresponding TSS entries on the base type, and this normally cannot
5093       --  be done after the base type is frozen, so the circuitry in
5094       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
5095       --  not use Set_TSS in this case.
5096
5097       if Is_Fixed_Point_Type (Parent_Type) then
5098          Conditional_Delay (Implicit_Base, Parent_Type);
5099       else
5100          Freeze_Before (N, Implicit_Base);
5101       end if;
5102    end Build_Derived_Numeric_Type;
5103
5104    --------------------------------
5105    -- Build_Derived_Private_Type --
5106    --------------------------------
5107
5108    procedure Build_Derived_Private_Type
5109      (N             : Node_Id;
5110       Parent_Type   : Entity_Id;
5111       Derived_Type  : Entity_Id;
5112       Is_Completion : Boolean;
5113       Derive_Subps  : Boolean := True)
5114    is
5115       Der_Base    : Entity_Id;
5116       Discr       : Entity_Id;
5117       Full_Decl   : Node_Id := Empty;
5118       Full_Der    : Entity_Id;
5119       Full_P      : Entity_Id;
5120       Last_Discr  : Entity_Id;
5121       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
5122       Swapped     : Boolean := False;
5123
5124       procedure Copy_And_Build;
5125       --  Copy derived type declaration, replace parent with its full view,
5126       --  and analyze new declaration.
5127
5128       --------------------
5129       -- Copy_And_Build --
5130       --------------------
5131
5132       procedure Copy_And_Build is
5133          Full_N : Node_Id;
5134
5135       begin
5136          if Ekind (Parent_Type) in Record_Kind
5137            or else
5138              (Ekind (Parent_Type) in Enumeration_Kind
5139                and then Root_Type (Parent_Type) /= Standard_Character
5140                and then Root_Type (Parent_Type) /= Standard_Wide_Character
5141                and then Root_Type (Parent_Type) /= Standard_Wide_Wide_Character
5142                and then not Is_Generic_Type (Root_Type (Parent_Type)))
5143          then
5144             Full_N := New_Copy_Tree (N);
5145             Insert_After (N, Full_N);
5146             Build_Derived_Type (
5147               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
5148
5149          else
5150             Build_Derived_Type (
5151               N, Parent_Type, Full_Der, True, Derive_Subps => False);
5152          end if;
5153       end Copy_And_Build;
5154
5155    --  Start of processing for Build_Derived_Private_Type
5156
5157    begin
5158       if Is_Tagged_Type (Parent_Type) then
5159          Build_Derived_Record_Type
5160            (N, Parent_Type, Derived_Type, Derive_Subps);
5161          return;
5162
5163       elsif Has_Discriminants (Parent_Type) then
5164          if Present (Full_View (Parent_Type)) then
5165             if not Is_Completion then
5166
5167                --  Copy declaration for subsequent analysis, to provide a
5168                --  completion for what is a private declaration. Indicate that
5169                --  the full type is internally generated.
5170
5171                Full_Decl := New_Copy_Tree (N);
5172                Full_Der  := New_Copy (Derived_Type);
5173                Set_Comes_From_Source (Full_Decl, False);
5174                Set_Comes_From_Source (Full_Der, False);
5175
5176                Insert_After (N, Full_Decl);
5177
5178             else
5179                --  If this is a completion, the full view being built is
5180                --  itself private. We build a subtype of the parent with
5181                --  the same constraints as this full view, to convey to the
5182                --  back end the constrained components and the size of this
5183                --  subtype. If the parent is constrained, its full view can
5184                --  serve as the underlying full view of the derived type.
5185
5186                if No (Discriminant_Specifications (N)) then
5187                   if Nkind (Subtype_Indication (Type_Definition (N))) =
5188                                                         N_Subtype_Indication
5189                   then
5190                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
5191
5192                   elsif Is_Constrained (Full_View (Parent_Type)) then
5193                      Set_Underlying_Full_View (Derived_Type,
5194                        Full_View (Parent_Type));
5195                   end if;
5196
5197                else
5198                   --  If there are new discriminants, the parent subtype is
5199                   --  constrained by them, but it is not clear how to build
5200                   --  the underlying_full_view in this case ???
5201
5202                   null;
5203                end if;
5204             end if;
5205          end if;
5206
5207          --  Build partial view of derived type from partial view of parent
5208
5209          Build_Derived_Record_Type
5210            (N, Parent_Type, Derived_Type, Derive_Subps);
5211
5212          if Present (Full_View (Parent_Type))
5213            and then not Is_Completion
5214          then
5215             if not In_Open_Scopes (Par_Scope)
5216               or else not In_Same_Source_Unit (N, Parent_Type)
5217             then
5218                --  Swap partial and full views temporarily
5219
5220                Install_Private_Declarations (Par_Scope);
5221                Install_Visible_Declarations (Par_Scope);
5222                Swapped := True;
5223             end if;
5224
5225             --  Build full view of derived type from full view of parent which
5226             --  is now installed. Subprograms have been derived on the partial
5227             --  view, the completion does not derive them anew.
5228
5229             if not Is_Tagged_Type (Parent_Type) then
5230
5231                --  If the parent is itself derived from another private type,
5232                --  installing the private declarations has not affected its
5233                --  privacy status, so use its own full view explicitly.
5234
5235                if Is_Private_Type (Parent_Type) then
5236                   Build_Derived_Record_Type
5237                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
5238                else
5239                   Build_Derived_Record_Type
5240                     (Full_Decl, Parent_Type, Full_Der, False);
5241                end if;
5242
5243             else
5244                --  If full view of parent is tagged, the completion
5245                --  inherits the proper primitive operations.
5246
5247                Set_Defining_Identifier (Full_Decl, Full_Der);
5248                Build_Derived_Record_Type
5249                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
5250                Set_Analyzed (Full_Decl);
5251             end if;
5252
5253             if Swapped then
5254                Uninstall_Declarations (Par_Scope);
5255
5256                if In_Open_Scopes (Par_Scope) then
5257                   Install_Visible_Declarations (Par_Scope);
5258                end if;
5259             end if;
5260
5261             Der_Base := Base_Type (Derived_Type);
5262             Set_Full_View (Derived_Type, Full_Der);
5263             Set_Full_View (Der_Base, Base_Type (Full_Der));
5264
5265             --  Copy the discriminant list from full view to the partial views
5266             --  (base type and its subtype). Gigi requires that the partial
5267             --  and full views have the same discriminants.
5268
5269             --  Note that since the partial view is pointing to discriminants
5270             --  in the full view, their scope will be that of the full view.
5271             --  This might cause some front end problems and need
5272             --  adjustment???
5273
5274             Discr := First_Discriminant (Base_Type (Full_Der));
5275             Set_First_Entity (Der_Base, Discr);
5276
5277             loop
5278                Last_Discr := Discr;
5279                Next_Discriminant (Discr);
5280                exit when No (Discr);
5281             end loop;
5282
5283             Set_Last_Entity (Der_Base, Last_Discr);
5284
5285             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
5286             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
5287             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
5288
5289          else
5290             --  If this is a completion, the derived type stays private
5291             --  and there is no need to create a further full view, except
5292             --  in the unusual case when the derivation is nested within a
5293             --  child unit, see below.
5294
5295             null;
5296          end if;
5297
5298       elsif Present (Full_View (Parent_Type))
5299         and then  Has_Discriminants (Full_View (Parent_Type))
5300       then
5301          if Has_Unknown_Discriminants (Parent_Type)
5302            and then Nkind (Subtype_Indication (Type_Definition (N)))
5303              = N_Subtype_Indication
5304          then
5305             Error_Msg_N
5306               ("cannot constrain type with unknown discriminants",
5307                Subtype_Indication (Type_Definition (N)));
5308             return;
5309          end if;
5310
5311          --  If full view of parent is a record type, Build full view as
5312          --  a derivation from the parent's full view. Partial view remains
5313          --  private. For code generation and linking, the full view must
5314          --  have the same public status as the partial one. This full view
5315          --  is only needed if the parent type is in an enclosing scope, so
5316          --  that the full view may actually become visible, e.g. in a child
5317          --  unit. This is both more efficient, and avoids order of freezing
5318          --  problems with the added entities.
5319
5320          if not Is_Private_Type (Full_View (Parent_Type))
5321            and then (In_Open_Scopes (Scope (Parent_Type)))
5322          then
5323             Full_Der := Make_Defining_Identifier (Sloc (Derived_Type),
5324                                               Chars (Derived_Type));
5325             Set_Is_Itype (Full_Der);
5326             Set_Has_Private_Declaration (Full_Der);
5327             Set_Has_Private_Declaration (Derived_Type);
5328             Set_Associated_Node_For_Itype (Full_Der, N);
5329             Set_Parent (Full_Der, Parent (Derived_Type));
5330             Set_Full_View (Derived_Type, Full_Der);
5331             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
5332             Full_P := Full_View (Parent_Type);
5333             Exchange_Declarations (Parent_Type);
5334             Copy_And_Build;
5335             Exchange_Declarations (Full_P);
5336
5337          else
5338             Build_Derived_Record_Type
5339               (N, Full_View (Parent_Type), Derived_Type,
5340                 Derive_Subps => False);
5341          end if;
5342
5343          --  In any case, the primitive operations are inherited from
5344          --  the parent type, not from the internal full view.
5345
5346          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
5347
5348          if Derive_Subps then
5349             Derive_Subprograms (Parent_Type, Derived_Type);
5350          end if;
5351
5352       else
5353          --  Untagged type, No discriminants on either view
5354
5355          if Nkind (Subtype_Indication (Type_Definition (N))) =
5356                                                    N_Subtype_Indication
5357          then
5358             Error_Msg_N
5359               ("illegal constraint on type without discriminants", N);
5360          end if;
5361
5362          if Present (Discriminant_Specifications (N))
5363            and then Present (Full_View (Parent_Type))
5364            and then not Is_Tagged_Type (Full_View (Parent_Type))
5365          then
5366             Error_Msg_N
5367               ("cannot add discriminants to untagged type", N);
5368          end if;
5369
5370          Set_Stored_Constraint (Derived_Type, No_Elist);
5371          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
5372          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
5373          Set_Has_Controlled_Component
5374                                (Derived_Type, Has_Controlled_Component
5375                                                              (Parent_Type));
5376
5377          --  Direct controlled types do not inherit Finalize_Storage_Only flag
5378
5379          if not Is_Controlled  (Parent_Type) then
5380             Set_Finalize_Storage_Only
5381               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
5382          end if;
5383
5384          --  Construct the implicit full view by deriving from full view of
5385          --  the parent type. In order to get proper visibility, we install
5386          --  the parent scope and its declarations.
5387
5388          --  ??? if the parent is untagged private and its completion is
5389          --  tagged, this mechanism will not work because we cannot derive
5390          --  from the tagged full view unless we have an extension
5391
5392          if Present (Full_View (Parent_Type))
5393            and then not Is_Tagged_Type (Full_View (Parent_Type))
5394            and then not Is_Completion
5395          then
5396             Full_Der :=
5397               Make_Defining_Identifier (Sloc (Derived_Type),
5398                 Chars => Chars (Derived_Type));
5399             Set_Is_Itype (Full_Der);
5400             Set_Has_Private_Declaration (Full_Der);
5401             Set_Has_Private_Declaration (Derived_Type);
5402             Set_Associated_Node_For_Itype (Full_Der, N);
5403             Set_Parent (Full_Der, Parent (Derived_Type));
5404             Set_Full_View (Derived_Type, Full_Der);
5405
5406             if not In_Open_Scopes (Par_Scope) then
5407                Install_Private_Declarations (Par_Scope);
5408                Install_Visible_Declarations (Par_Scope);
5409                Copy_And_Build;
5410                Uninstall_Declarations (Par_Scope);
5411
5412             --  If parent scope is open and in another unit, and parent has a
5413             --  completion, then the derivation is taking place in the visible
5414             --  part of a child unit. In that case retrieve the full view of
5415             --  the parent momentarily.
5416
5417             elsif not In_Same_Source_Unit (N, Parent_Type) then
5418                Full_P := Full_View (Parent_Type);
5419                Exchange_Declarations (Parent_Type);
5420                Copy_And_Build;
5421                Exchange_Declarations (Full_P);
5422
5423             --  Otherwise it is a local derivation
5424
5425             else
5426                Copy_And_Build;
5427             end if;
5428
5429             Set_Scope                (Full_Der, Current_Scope);
5430             Set_Is_First_Subtype     (Full_Der,
5431                                        Is_First_Subtype (Derived_Type));
5432             Set_Has_Size_Clause      (Full_Der, False);
5433             Set_Has_Alignment_Clause (Full_Der, False);
5434             Set_Next_Entity          (Full_Der, Empty);
5435             Set_Has_Delayed_Freeze   (Full_Der);
5436             Set_Is_Frozen            (Full_Der, False);
5437             Set_Freeze_Node          (Full_Der, Empty);
5438             Set_Depends_On_Private   (Full_Der,
5439                                         Has_Private_Component    (Full_Der));
5440             Set_Public_Status        (Full_Der);
5441          end if;
5442       end if;
5443
5444       Set_Has_Unknown_Discriminants (Derived_Type,
5445         Has_Unknown_Discriminants (Parent_Type));
5446
5447       if Is_Private_Type (Derived_Type) then
5448          Set_Private_Dependents (Derived_Type, New_Elmt_List);
5449       end if;
5450
5451       if Is_Private_Type (Parent_Type)
5452         and then Base_Type (Parent_Type) = Parent_Type
5453         and then In_Open_Scopes (Scope (Parent_Type))
5454       then
5455          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
5456
5457          if Is_Child_Unit (Scope (Current_Scope))
5458            and then Is_Completion
5459            and then In_Private_Part (Current_Scope)
5460            and then Scope (Parent_Type) /= Current_Scope
5461          then
5462             --  This is the unusual case where a type completed by a private
5463             --  derivation occurs within a package nested in a child unit,
5464             --  and the parent is declared in an ancestor. In this case, the
5465             --  full view of the parent type will become visible in the body
5466             --  of the enclosing child, and only then will the current type
5467             --  be possibly non-private. We build a underlying full view that
5468             --  will be installed when the enclosing child body is compiled.
5469
5470             Full_Der :=
5471               Make_Defining_Identifier (Sloc (Derived_Type),
5472                 Chars => Chars (Derived_Type));
5473             Set_Is_Itype (Full_Der);
5474             Build_Itype_Reference (Full_Der, N);
5475
5476             --  The full view will be used to swap entities on entry/exit to
5477             --  the body, and must appear in the entity list for the package.
5478
5479             Append_Entity (Full_Der, Scope (Derived_Type));
5480             Set_Has_Private_Declaration (Full_Der);
5481             Set_Has_Private_Declaration (Derived_Type);
5482             Set_Associated_Node_For_Itype (Full_Der, N);
5483             Set_Parent (Full_Der, Parent (Derived_Type));
5484             Full_P := Full_View (Parent_Type);
5485             Exchange_Declarations (Parent_Type);
5486             Copy_And_Build;
5487             Exchange_Declarations (Full_P);
5488             Set_Underlying_Full_View (Derived_Type, Full_Der);
5489          end if;
5490       end if;
5491    end Build_Derived_Private_Type;
5492
5493    -------------------------------
5494    -- Build_Derived_Record_Type --
5495    -------------------------------
5496
5497    --  1. INTRODUCTION
5498
5499    --  Ideally we would like to use the same model of type derivation for
5500    --  tagged and untagged record types. Unfortunately this is not quite
5501    --  possible because the semantics of representation clauses is different
5502    --  for tagged and untagged records under inheritance. Consider the
5503    --  following:
5504
5505    --     type R (...) is [tagged] record ... end record;
5506    --     type T (...) is new R (...) [with ...];
5507
5508    --  The representation clauses for T can specify a completely different
5509    --  record layout from R's. Hence the same component can be placed in two
5510    --  very different positions in objects of type T and R. If R and are tagged
5511    --  types, representation clauses for T can only specify the layout of non
5512    --  inherited components, thus components that are common in R and T have
5513    --  the same position in objects of type R and T.
5514
5515    --  This has two implications. The first is that the entire tree for R's
5516    --  declaration needs to be copied for T in the untagged case, so that T
5517    --  can be viewed as a record type of its own with its own representation
5518    --  clauses. The second implication is the way we handle discriminants.
5519    --  Specifically, in the untagged case we need a way to communicate to Gigi
5520    --  what are the real discriminants in the record, while for the semantics
5521    --  we need to consider those introduced by the user to rename the
5522    --  discriminants in the parent type. This is handled by introducing the
5523    --  notion of stored discriminants. See below for more.
5524
5525    --  Fortunately the way regular components are inherited can be handled in
5526    --  the same way in tagged and untagged types.
5527
5528    --  To complicate things a bit more the private view of a private extension
5529    --  cannot be handled in the same way as the full view (for one thing the
5530    --  semantic rules are somewhat different). We will explain what differs
5531    --  below.
5532
5533    --  2. DISCRIMINANTS UNDER INHERITANCE
5534
5535    --  The semantic rules governing the discriminants of derived types are
5536    --  quite subtle.
5537
5538    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
5539    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
5540
5541    --  If parent type has discriminants, then the discriminants that are
5542    --  declared in the derived type are [3.4 (11)]:
5543
5544    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
5545    --    there is one;
5546
5547    --  o Otherwise, each discriminant of the parent type (implicitly declared
5548    --    in the same order with the same specifications). In this case, the
5549    --    discriminants are said to be "inherited", or if unknown in the parent
5550    --    are also unknown in the derived type.
5551
5552    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
5553
5554    --  o The parent subtype shall be constrained;
5555
5556    --  o If the parent type is not a tagged type, then each discriminant of
5557    --    the derived type shall be used in the constraint defining a parent
5558    --    subtype. [Implementation note: This ensures that the new discriminant
5559    --    can share storage with an existing discriminant.]
5560
5561    --  For the derived type each discriminant of the parent type is either
5562    --  inherited, constrained to equal some new discriminant of the derived
5563    --  type, or constrained to the value of an expression.
5564
5565    --  When inherited or constrained to equal some new discriminant, the
5566    --  parent discriminant and the discriminant of the derived type are said
5567    --  to "correspond".
5568
5569    --  If a discriminant of the parent type is constrained to a specific value
5570    --  in the derived type definition, then the discriminant is said to be
5571    --  "specified" by that derived type definition.
5572
5573    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
5574
5575    --  We have spoken about stored discriminants in point 1 (introduction)
5576    --  above. There are two sort of stored discriminants: implicit and
5577    --  explicit. As long as the derived type inherits the same discriminants as
5578    --  the root record type, stored discriminants are the same as regular
5579    --  discriminants, and are said to be implicit. However, if any discriminant
5580    --  in the root type was renamed in the derived type, then the derived
5581    --  type will contain explicit stored discriminants. Explicit stored
5582    --  discriminants are discriminants in addition to the semantically visible
5583    --  discriminants defined for the derived type. Stored discriminants are
5584    --  used by Gigi to figure out what are the physical discriminants in
5585    --  objects of the derived type (see precise definition in einfo.ads).
5586    --  As an example, consider the following:
5587
5588    --           type R  (D1, D2, D3 : Int) is record ... end record;
5589    --           type T1 is new R;
5590    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
5591    --           type T3 is new T2;
5592    --           type T4 (Y : Int) is new T3 (Y, 99);
5593
5594    --  The following table summarizes the discriminants and stored
5595    --  discriminants in R and T1 through T4.
5596
5597    --   Type      Discrim     Stored Discrim  Comment
5598    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
5599    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
5600    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
5601    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
5602    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
5603
5604    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
5605    --  find the corresponding discriminant in the parent type, while
5606    --  Original_Record_Component (abbreviated ORC below), the actual physical
5607    --  component that is renamed. Finally the field Is_Completely_Hidden
5608    --  (abbreviated ICH below) is set for all explicit stored discriminants
5609    --  (see einfo.ads for more info). For the above example this gives:
5610
5611    --                 Discrim     CD        ORC     ICH
5612    --                 ^^^^^^^     ^^        ^^^     ^^^
5613    --                 D1 in R    empty     itself    no
5614    --                 D2 in R    empty     itself    no
5615    --                 D3 in R    empty     itself    no
5616
5617    --                 D1 in T1  D1 in R    itself    no
5618    --                 D2 in T1  D2 in R    itself    no
5619    --                 D3 in T1  D3 in R    itself    no
5620
5621    --                 X1 in T2  D3 in T1  D3 in T2   no
5622    --                 X2 in T2  D1 in T1  D1 in T2   no
5623    --                 D1 in T2   empty    itself    yes
5624    --                 D2 in T2   empty    itself    yes
5625    --                 D3 in T2   empty    itself    yes
5626
5627    --                 X1 in T3  X1 in T2  D3 in T3   no
5628    --                 X2 in T3  X2 in T2  D1 in T3   no
5629    --                 D1 in T3   empty    itself    yes
5630    --                 D2 in T3   empty    itself    yes
5631    --                 D3 in T3   empty    itself    yes
5632
5633    --                 Y  in T4  X1 in T3  D3 in T3   no
5634    --                 D1 in T3   empty    itself    yes
5635    --                 D2 in T3   empty    itself    yes
5636    --                 D3 in T3   empty    itself    yes
5637
5638    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
5639
5640    --  Type derivation for tagged types is fairly straightforward. If no
5641    --  discriminants are specified by the derived type, these are inherited
5642    --  from the parent. No explicit stored discriminants are ever necessary.
5643    --  The only manipulation that is done to the tree is that of adding a
5644    --  _parent field with parent type and constrained to the same constraint
5645    --  specified for the parent in the derived type definition. For instance:
5646
5647    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
5648    --           type T1 is new R with null record;
5649    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
5650
5651    --  are changed into:
5652
5653    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
5654    --              _parent : R (D1, D2, D3);
5655    --           end record;
5656
5657    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
5658    --              _parent : T1 (X2, 88, X1);
5659    --           end record;
5660
5661    --  The discriminants actually present in R, T1 and T2 as well as their CD,
5662    --  ORC and ICH fields are:
5663
5664    --                 Discrim     CD        ORC     ICH
5665    --                 ^^^^^^^     ^^        ^^^     ^^^
5666    --                 D1 in R    empty     itself    no
5667    --                 D2 in R    empty     itself    no
5668    --                 D3 in R    empty     itself    no
5669
5670    --                 D1 in T1  D1 in R    D1 in R   no
5671    --                 D2 in T1  D2 in R    D2 in R   no
5672    --                 D3 in T1  D3 in R    D3 in R   no
5673
5674    --                 X1 in T2  D3 in T1   D3 in R   no
5675    --                 X2 in T2  D1 in T1   D1 in R   no
5676
5677    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
5678    --
5679    --  Regardless of whether we dealing with a tagged or untagged type
5680    --  we will transform all derived type declarations of the form
5681    --
5682    --               type T is new R (...) [with ...];
5683    --  or
5684    --               subtype S is R (...);
5685    --               type T is new S [with ...];
5686    --  into
5687    --               type BT is new R [with ...];
5688    --               subtype T is BT (...);
5689    --
5690    --  That is, the base derived type is constrained only if it has no
5691    --  discriminants. The reason for doing this is that GNAT's semantic model
5692    --  assumes that a base type with discriminants is unconstrained.
5693    --
5694    --  Note that, strictly speaking, the above transformation is not always
5695    --  correct. Consider for instance the following excerpt from ACVC b34011a:
5696    --
5697    --       procedure B34011A is
5698    --          type REC (D : integer := 0) is record
5699    --             I : Integer;
5700    --          end record;
5701
5702    --          package P is
5703    --             type T6 is new Rec;
5704    --             function F return T6;
5705    --          end P;
5706
5707    --          use P;
5708    --          package Q6 is
5709    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
5710    --          end Q6;
5711    --
5712    --  The definition of Q6.U is illegal. However transforming Q6.U into
5713
5714    --             type BaseU is new T6;
5715    --             subtype U is BaseU (Q6.F.I)
5716
5717    --  turns U into a legal subtype, which is incorrect. To avoid this problem
5718    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
5719    --  the transformation described above.
5720
5721    --  There is another instance where the above transformation is incorrect.
5722    --  Consider:
5723
5724    --          package Pack is
5725    --             type Base (D : Integer) is tagged null record;
5726    --             procedure P (X : Base);
5727
5728    --             type Der is new Base (2) with null record;
5729    --             procedure P (X : Der);
5730    --          end Pack;
5731
5732    --  Then the above transformation turns this into
5733
5734    --             type Der_Base is new Base with null record;
5735    --             --  procedure P (X : Base) is implicitly inherited here
5736    --             --  as procedure P (X : Der_Base).
5737
5738    --             subtype Der is Der_Base (2);
5739    --             procedure P (X : Der);
5740    --             --  The overriding of P (X : Der_Base) is illegal since we
5741    --             --  have a parameter conformance problem.
5742
5743    --  To get around this problem, after having semantically processed Der_Base
5744    --  and the rewritten subtype declaration for Der, we copy Der_Base field
5745    --  Discriminant_Constraint from Der so that when parameter conformance is
5746    --  checked when P is overridden, no semantic errors are flagged.
5747
5748    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
5749
5750    --  Regardless of whether we are dealing with a tagged or untagged type
5751    --  we will transform all derived type declarations of the form
5752
5753    --               type R (D1, .., Dn : ...) is [tagged] record ...;
5754    --               type T is new R [with ...];
5755    --  into
5756    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
5757
5758    --  The reason for such transformation is that it allows us to implement a
5759    --  very clean form of component inheritance as explained below.
5760
5761    --  Note that this transformation is not achieved by direct tree rewriting
5762    --  and manipulation, but rather by redoing the semantic actions that the
5763    --  above transformation will entail. This is done directly in routine
5764    --  Inherit_Components.
5765
5766    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
5767
5768    --  In both tagged and untagged derived types, regular non discriminant
5769    --  components are inherited in the derived type from the parent type. In
5770    --  the absence of discriminants component, inheritance is straightforward
5771    --  as components can simply be copied from the parent.
5772
5773    --  If the parent has discriminants, inheriting components constrained with
5774    --  these discriminants requires caution. Consider the following example:
5775
5776    --      type R  (D1, D2 : Positive) is [tagged] record
5777    --         S : String (D1 .. D2);
5778    --      end record;
5779
5780    --      type T1                is new R        [with null record];
5781    --      type T2 (X : positive) is new R (1, X) [with null record];
5782
5783    --  As explained in 6. above, T1 is rewritten as
5784    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
5785    --  which makes the treatment for T1 and T2 identical.
5786
5787    --  What we want when inheriting S, is that references to D1 and D2 in R are
5788    --  replaced with references to their correct constraints, ie D1 and D2 in
5789    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
5790    --  with either discriminant references in the derived type or expressions.
5791    --  This replacement is achieved as follows: before inheriting R's
5792    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
5793    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
5794    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
5795    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
5796    --  by String (1 .. X).
5797
5798    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
5799
5800    --  We explain here the rules governing private type extensions relevant to
5801    --  type derivation. These rules are explained on the following example:
5802
5803    --      type D [(...)] is new A [(...)] with private;      <-- partial view
5804    --      type D [(...)] is new P [(...)] with null record;  <-- full view
5805
5806    --  Type A is called the ancestor subtype of the private extension.
5807    --  Type P is the parent type of the full view of the private extension. It
5808    --  must be A or a type derived from A.
5809
5810    --  The rules concerning the discriminants of private type extensions are
5811    --  [7.3(10-13)]:
5812
5813    --  o If a private extension inherits known discriminants from the ancestor
5814    --    subtype, then the full view shall also inherit its discriminants from
5815    --    the ancestor subtype and the parent subtype of the full view shall be
5816    --    constrained if and only if the ancestor subtype is constrained.
5817
5818    --  o If a partial view has unknown discriminants, then the full view may
5819    --    define a definite or an indefinite subtype, with or without
5820    --    discriminants.
5821
5822    --  o If a partial view has neither known nor unknown discriminants, then
5823    --    the full view shall define a definite subtype.
5824
5825    --  o If the ancestor subtype of a private extension has constrained
5826    --    discriminants, then the parent subtype of the full view shall impose a
5827    --    statically matching constraint on those discriminants.
5828
5829    --  This means that only the following forms of private extensions are
5830    --  allowed:
5831
5832    --      type D is new A with private;      <-- partial view
5833    --      type D is new P with null record;  <-- full view
5834
5835    --  If A has no discriminants than P has no discriminants, otherwise P must
5836    --  inherit A's discriminants.
5837
5838    --      type D is new A (...) with private;      <-- partial view
5839    --      type D is new P (:::) with null record;  <-- full view
5840
5841    --  P must inherit A's discriminants and (...) and (:::) must statically
5842    --  match.
5843
5844    --      subtype A is R (...);
5845    --      type D is new A with private;      <-- partial view
5846    --      type D is new P with null record;  <-- full view
5847
5848    --  P must have inherited R's discriminants and must be derived from A or
5849    --  any of its subtypes.
5850
5851    --      type D (..) is new A with private;              <-- partial view
5852    --      type D (..) is new P [(:::)] with null record;  <-- full view
5853
5854    --  No specific constraints on P's discriminants or constraint (:::).
5855    --  Note that A can be unconstrained, but the parent subtype P must either
5856    --  be constrained or (:::) must be present.
5857
5858    --      type D (..) is new A [(...)] with private;      <-- partial view
5859    --      type D (..) is new P [(:::)] with null record;  <-- full view
5860
5861    --  P's constraints on A's discriminants must statically match those
5862    --  imposed by (...).
5863
5864    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
5865
5866    --  The full view of a private extension is handled exactly as described
5867    --  above. The model chose for the private view of a private extension is
5868    --  the same for what concerns discriminants (ie they receive the same
5869    --  treatment as in the tagged case). However, the private view of the
5870    --  private extension always inherits the components of the parent base,
5871    --  without replacing any discriminant reference. Strictly speaking this is
5872    --  incorrect. However, Gigi never uses this view to generate code so this
5873    --  is a purely semantic issue. In theory, a set of transformations similar
5874    --  to those given in 5. and 6. above could be applied to private views of
5875    --  private extensions to have the same model of component inheritance as
5876    --  for non private extensions. However, this is not done because it would
5877    --  further complicate private type processing. Semantically speaking, this
5878    --  leaves us in an uncomfortable situation. As an example consider:
5879
5880    --          package Pack is
5881    --             type R (D : integer) is tagged record
5882    --                S : String (1 .. D);
5883    --             end record;
5884    --             procedure P (X : R);
5885    --             type T is new R (1) with private;
5886    --          private
5887    --             type T is new R (1) with null record;
5888    --          end;
5889
5890    --  This is transformed into:
5891
5892    --          package Pack is
5893    --             type R (D : integer) is tagged record
5894    --                S : String (1 .. D);
5895    --             end record;
5896    --             procedure P (X : R);
5897    --             type T is new R (1) with private;
5898    --          private
5899    --             type BaseT is new R with null record;
5900    --             subtype  T is BaseT (1);
5901    --          end;
5902
5903    --  (strictly speaking the above is incorrect Ada)
5904
5905    --  From the semantic standpoint the private view of private extension T
5906    --  should be flagged as constrained since one can clearly have
5907    --
5908    --             Obj : T;
5909    --
5910    --  in a unit withing Pack. However, when deriving subprograms for the
5911    --  private view of private extension T, T must be seen as unconstrained
5912    --  since T has discriminants (this is a constraint of the current
5913    --  subprogram derivation model). Thus, when processing the private view of
5914    --  a private extension such as T, we first mark T as unconstrained, we
5915    --  process it, we perform program derivation and just before returning from
5916    --  Build_Derived_Record_Type we mark T as constrained.
5917
5918    --  ??? Are there are other uncomfortable cases that we will have to
5919    --      deal with.
5920
5921    --  10. RECORD_TYPE_WITH_PRIVATE complications
5922
5923    --  Types that are derived from a visible record type and have a private
5924    --  extension present other peculiarities. They behave mostly like private
5925    --  types, but if they have primitive operations defined, these will not
5926    --  have the proper signatures for further inheritance, because other
5927    --  primitive operations will use the implicit base that we define for
5928    --  private derivations below. This affect subprogram inheritance (see
5929    --  Derive_Subprograms for details). We also derive the implicit base from
5930    --  the base type of the full view, so that the implicit base is a record
5931    --  type and not another private type, This avoids infinite loops.
5932
5933    procedure Build_Derived_Record_Type
5934      (N            : Node_Id;
5935       Parent_Type  : Entity_Id;
5936       Derived_Type : Entity_Id;
5937       Derive_Subps : Boolean := True)
5938    is
5939       Loc          : constant Source_Ptr := Sloc (N);
5940       Parent_Base  : Entity_Id;
5941       Type_Def     : Node_Id;
5942       Indic        : Node_Id;
5943       Discrim      : Entity_Id;
5944       Last_Discrim : Entity_Id;
5945       Constrs      : Elist_Id;
5946
5947       Discs : Elist_Id := New_Elmt_List;
5948       --  An empty Discs list means that there were no constraints in the
5949       --  subtype indication or that there was an error processing it.
5950
5951       Assoc_List : Elist_Id;
5952       New_Discrs : Elist_Id;
5953       New_Base   : Entity_Id;
5954       New_Decl   : Node_Id;
5955       New_Indic  : Node_Id;
5956
5957       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
5958       Discriminant_Specs : constant Boolean :=
5959                              Present (Discriminant_Specifications (N));
5960       Private_Extension  : constant Boolean :=
5961                              (Nkind (N) = N_Private_Extension_Declaration);
5962
5963       Constraint_Present : Boolean;
5964       Inherit_Discrims   : Boolean := False;
5965       Save_Etype         : Entity_Id;
5966       Save_Discr_Constr  : Elist_Id;
5967       Save_Next_Entity   : Entity_Id;
5968
5969    begin
5970       if Ekind (Parent_Type) = E_Record_Type_With_Private
5971         and then Present (Full_View (Parent_Type))
5972         and then Has_Discriminants (Parent_Type)
5973       then
5974          Parent_Base := Base_Type (Full_View (Parent_Type));
5975       else
5976          Parent_Base := Base_Type (Parent_Type);
5977       end if;
5978
5979       --  Before we start the previously documented transformations, here is
5980       --  little fix for size and alignment of tagged types. Normally when we
5981       --  derive type D from type P, we copy the size and alignment of P as the
5982       --  default for D, and in the absence of explicit representation clauses
5983       --  for D, the size and alignment are indeed the same as the parent.
5984
5985       --  But this is wrong for tagged types, since fields may be added, and
5986       --  the default size may need to be larger, and the default alignment may
5987       --  need to be larger.
5988
5989       --  We therefore reset the size and alignment fields in the tagged case.
5990       --  Note that the size and alignment will in any case be at least as
5991       --  large as the parent type (since the derived type has a copy of the
5992       --  parent type in the _parent field)
5993
5994       --  The type is also marked as being tagged here, which is needed when
5995       --  processing components with a self-referential anonymous access type
5996       --  in the call to Check_Anonymous_Access_Components below. Note that
5997       --  this flag is also set later on for completeness.
5998
5999       if Is_Tagged then
6000          Set_Is_Tagged_Type (Derived_Type);
6001          Init_Size_Align    (Derived_Type);
6002       end if;
6003
6004       --  STEP 0a: figure out what kind of derived type declaration we have
6005
6006       if Private_Extension then
6007          Type_Def := N;
6008          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
6009
6010       else
6011          Type_Def := Type_Definition (N);
6012
6013          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
6014          --  Parent_Base can be a private type or private extension. However,
6015          --  for tagged types with an extension the newly added fields are
6016          --  visible and hence the Derived_Type is always an E_Record_Type.
6017          --  (except that the parent may have its own private fields).
6018          --  For untagged types we preserve the Ekind of the Parent_Base.
6019
6020          if Present (Record_Extension_Part (Type_Def)) then
6021             Set_Ekind (Derived_Type, E_Record_Type);
6022
6023             --  Create internal access types for components with anonymous
6024             --  access types.
6025
6026             if Ada_Version >= Ada_05 then
6027                Check_Anonymous_Access_Components
6028                  (N, Derived_Type, Derived_Type,
6029                    Component_List (Record_Extension_Part (Type_Def)));
6030             end if;
6031
6032          else
6033             Set_Ekind (Derived_Type, Ekind (Parent_Base));
6034          end if;
6035       end if;
6036
6037       --  Indic can either be an N_Identifier if the subtype indication
6038       --  contains no constraint or an N_Subtype_Indication if the subtype
6039       --  indication has a constraint.
6040
6041       Indic := Subtype_Indication (Type_Def);
6042       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
6043
6044       --  Check that the type has visible discriminants. The type may be
6045       --  a private type with unknown discriminants whose full view has
6046       --  discriminants which are invisible.
6047
6048       if Constraint_Present then
6049          if not Has_Discriminants (Parent_Base)
6050            or else
6051              (Has_Unknown_Discriminants (Parent_Base)
6052                 and then Is_Private_Type (Parent_Base))
6053          then
6054             Error_Msg_N
6055               ("invalid constraint: type has no discriminant",
6056                  Constraint (Indic));
6057
6058             Constraint_Present := False;
6059             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6060
6061          elsif Is_Constrained (Parent_Type) then
6062             Error_Msg_N
6063                ("invalid constraint: parent type is already constrained",
6064                   Constraint (Indic));
6065
6066             Constraint_Present := False;
6067             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6068          end if;
6069       end if;
6070
6071       --  STEP 0b: If needed, apply transformation given in point 5. above
6072
6073       if not Private_Extension
6074         and then Has_Discriminants (Parent_Type)
6075         and then not Discriminant_Specs
6076         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
6077       then
6078          --  First, we must analyze the constraint (see comment in point 5.)
6079
6080          if Constraint_Present then
6081             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
6082
6083             if Has_Discriminants (Derived_Type)
6084               and then Has_Private_Declaration (Derived_Type)
6085               and then Present (Discriminant_Constraint (Derived_Type))
6086             then
6087                --  Verify that constraints of the full view conform to those
6088                --  given in partial view.
6089
6090                declare
6091                   C1, C2 : Elmt_Id;
6092
6093                begin
6094                   C1 := First_Elmt (New_Discrs);
6095                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
6096                   while Present (C1) and then Present (C2) loop
6097                      if not
6098                        Fully_Conformant_Expressions (Node (C1), Node (C2))
6099                      then
6100                         Error_Msg_N (
6101                           "constraint not conformant to previous declaration",
6102                              Node (C1));
6103                      end if;
6104
6105                      Next_Elmt (C1);
6106                      Next_Elmt (C2);
6107                   end loop;
6108                end;
6109             end if;
6110          end if;
6111
6112          --  Insert and analyze the declaration for the unconstrained base type
6113
6114          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
6115
6116          New_Decl :=
6117            Make_Full_Type_Declaration (Loc,
6118               Defining_Identifier => New_Base,
6119               Type_Definition     =>
6120                 Make_Derived_Type_Definition (Loc,
6121                   Abstract_Present      => Abstract_Present (Type_Def),
6122                   Subtype_Indication    =>
6123                     New_Occurrence_Of (Parent_Base, Loc),
6124                   Record_Extension_Part =>
6125                     Relocate_Node (Record_Extension_Part (Type_Def))));
6126
6127          Set_Parent (New_Decl, Parent (N));
6128          Mark_Rewrite_Insertion (New_Decl);
6129          Insert_Before (N, New_Decl);
6130
6131          --  Note that this call passes False for the Derive_Subps parameter
6132          --  because subprogram derivation is deferred until after creating
6133          --  the subtype (see below).
6134
6135          Build_Derived_Type
6136            (New_Decl, Parent_Base, New_Base,
6137             Is_Completion => True, Derive_Subps => False);
6138
6139          --  ??? This needs re-examination to determine whether the
6140          --  above call can simply be replaced by a call to Analyze.
6141
6142          Set_Analyzed (New_Decl);
6143
6144          --  Insert and analyze the declaration for the constrained subtype
6145
6146          if Constraint_Present then
6147             New_Indic :=
6148               Make_Subtype_Indication (Loc,
6149                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6150                 Constraint   => Relocate_Node (Constraint (Indic)));
6151
6152          else
6153             declare
6154                Constr_List : constant List_Id := New_List;
6155                C           : Elmt_Id;
6156                Expr        : Node_Id;
6157
6158             begin
6159                C := First_Elmt (Discriminant_Constraint (Parent_Type));
6160                while Present (C) loop
6161                   Expr := Node (C);
6162
6163                   --  It is safe here to call New_Copy_Tree since
6164                   --  Force_Evaluation was called on each constraint in
6165                   --  Build_Discriminant_Constraints.
6166
6167                   Append (New_Copy_Tree (Expr), To => Constr_List);
6168
6169                   Next_Elmt (C);
6170                end loop;
6171
6172                New_Indic :=
6173                  Make_Subtype_Indication (Loc,
6174                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6175                    Constraint   =>
6176                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
6177             end;
6178          end if;
6179
6180          Rewrite (N,
6181            Make_Subtype_Declaration (Loc,
6182              Defining_Identifier => Derived_Type,
6183              Subtype_Indication  => New_Indic));
6184
6185          Analyze (N);
6186
6187          --  Derivation of subprograms must be delayed until the full subtype
6188          --  has been established to ensure proper overriding of subprograms
6189          --  inherited by full types. If the derivations occurred as part of
6190          --  the call to Build_Derived_Type above, then the check for type
6191          --  conformance would fail because earlier primitive subprograms
6192          --  could still refer to the full type prior the change to the new
6193          --  subtype and hence would not match the new base type created here.
6194
6195          Derive_Subprograms (Parent_Type, Derived_Type);
6196
6197          --  For tagged types the Discriminant_Constraint of the new base itype
6198          --  is inherited from the first subtype so that no subtype conformance
6199          --  problem arise when the first subtype overrides primitive
6200          --  operations inherited by the implicit base type.
6201
6202          if Is_Tagged then
6203             Set_Discriminant_Constraint
6204               (New_Base, Discriminant_Constraint (Derived_Type));
6205          end if;
6206
6207          return;
6208       end if;
6209
6210       --  If we get here Derived_Type will have no discriminants or it will be
6211       --  a discriminated unconstrained base type.
6212
6213       --  STEP 1a: perform preliminary actions/checks for derived tagged types
6214
6215       if Is_Tagged then
6216
6217          --  The parent type is frozen for non-private extensions (RM 13.14(7))
6218          --  The declaration of a specific descendant of an interface type
6219          --  freezes the interface type (RM 13.14).
6220
6221          if not Private_Extension
6222            or else Is_Interface (Parent_Base)
6223          then
6224             Freeze_Before (N, Parent_Type);
6225          end if;
6226
6227          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
6228          --  cannot be declared at a deeper level than its parent type is
6229          --  removed. The check on derivation within a generic body is also
6230          --  relaxed, but there's a restriction that a derived tagged type
6231          --  cannot be declared in a generic body if it's derived directly
6232          --  or indirectly from a formal type of that generic.
6233
6234          if Ada_Version >= Ada_05 then
6235             if Present (Enclosing_Generic_Body (Derived_Type)) then
6236                declare
6237                   Ancestor_Type : Entity_Id;
6238
6239                begin
6240                   --  Check to see if any ancestor of the derived type is a
6241                   --  formal type.
6242
6243                   Ancestor_Type := Parent_Type;
6244                   while not Is_Generic_Type (Ancestor_Type)
6245                     and then Etype (Ancestor_Type) /= Ancestor_Type
6246                   loop
6247                      Ancestor_Type := Etype (Ancestor_Type);
6248                   end loop;
6249
6250                   --  If the derived type does have a formal type as an
6251                   --  ancestor, then it's an error if the derived type is
6252                   --  declared within the body of the generic unit that
6253                   --  declares the formal type in its generic formal part. It's
6254                   --  sufficient to check whether the ancestor type is declared
6255                   --  inside the same generic body as the derived type (such as
6256                   --  within a nested generic spec), in which case the
6257                   --  derivation is legal. If the formal type is declared
6258                   --  outside of that generic body, then it's guaranteed that
6259                   --  the derived type is declared within the generic body of
6260                   --  the generic unit declaring the formal type.
6261
6262                   if Is_Generic_Type (Ancestor_Type)
6263                     and then Enclosing_Generic_Body (Ancestor_Type) /=
6264                                Enclosing_Generic_Body (Derived_Type)
6265                   then
6266                      Error_Msg_NE
6267                        ("parent type of& must not be descendant of formal type"
6268                           & " of an enclosing generic body",
6269                             Indic, Derived_Type);
6270                   end if;
6271                end;
6272             end if;
6273
6274          elsif Type_Access_Level (Derived_Type) /=
6275                  Type_Access_Level (Parent_Type)
6276            and then not Is_Generic_Type (Derived_Type)
6277          then
6278             if Is_Controlled (Parent_Type) then
6279                Error_Msg_N
6280                  ("controlled type must be declared at the library level",
6281                   Indic);
6282             else
6283                Error_Msg_N
6284                  ("type extension at deeper accessibility level than parent",
6285                   Indic);
6286             end if;
6287
6288          else
6289             declare
6290                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
6291
6292             begin
6293                if Present (GB)
6294                  and then GB /= Enclosing_Generic_Body (Parent_Base)
6295                then
6296                   Error_Msg_NE
6297                     ("parent type of& must not be outside generic body"
6298                        & " (RM 3.9.1(4))",
6299                          Indic, Derived_Type);
6300                end if;
6301             end;
6302          end if;
6303       end if;
6304
6305       --  Ada 2005 (AI-251)
6306
6307       if Ada_Version = Ada_05
6308         and then Is_Tagged
6309       then
6310          --  "The declaration of a specific descendant of an interface type
6311          --  freezes the interface type" (RM 13.14).
6312
6313          declare
6314             Iface : Node_Id;
6315          begin
6316             if Is_Non_Empty_List (Interface_List (Type_Def)) then
6317                Iface := First (Interface_List (Type_Def));
6318                while Present (Iface) loop
6319                   Freeze_Before (N, Etype (Iface));
6320                   Next (Iface);
6321                end loop;
6322             end if;
6323          end;
6324       end if;
6325
6326       --  STEP 1b : preliminary cleanup of the full view of private types
6327
6328       --  If the type is already marked as having discriminants, then it's the
6329       --  completion of a private type or private extension and we need to
6330       --  retain the discriminants from the partial view if the current
6331       --  declaration has Discriminant_Specifications so that we can verify
6332       --  conformance. However, we must remove any existing components that
6333       --  were inherited from the parent (and attached in Copy_And_Swap)
6334       --  because the full type inherits all appropriate components anyway, and
6335       --  we do not want the partial view's components interfering.
6336
6337       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
6338          Discrim := First_Discriminant (Derived_Type);
6339          loop
6340             Last_Discrim := Discrim;
6341             Next_Discriminant (Discrim);
6342             exit when No (Discrim);
6343          end loop;
6344
6345          Set_Last_Entity (Derived_Type, Last_Discrim);
6346
6347       --  In all other cases wipe out the list of inherited components (even
6348       --  inherited discriminants), it will be properly rebuilt here.
6349
6350       else
6351          Set_First_Entity (Derived_Type, Empty);
6352          Set_Last_Entity  (Derived_Type, Empty);
6353       end if;
6354
6355       --  STEP 1c: Initialize some flags for the Derived_Type
6356
6357       --  The following flags must be initialized here so that
6358       --  Process_Discriminants can check that discriminants of tagged types do
6359       --  not have a default initial value and that access discriminants are
6360       --  only specified for limited records. For completeness, these flags are
6361       --  also initialized along with all the other flags below.
6362
6363       --  AI-419: Limitedness is not inherited from an interface parent, so to
6364       --  be limited in that case the type must be explicitly declared as
6365       --  limited. However, task and protected interfaces are always limited.
6366
6367       if Limited_Present (Type_Def) then
6368          Set_Is_Limited_Record (Derived_Type);
6369
6370       elsif Is_Limited_Record (Parent_Type) then
6371          if not Is_Interface (Parent_Type)
6372            or else Is_Synchronized_Interface (Parent_Type)
6373            or else Is_Protected_Interface (Parent_Type)
6374            or else Is_Task_Interface (Parent_Type)
6375          then
6376             Set_Is_Limited_Record (Derived_Type);
6377          end if;
6378       end if;
6379
6380       --  STEP 2a: process discriminants of derived type if any
6381
6382       Push_Scope (Derived_Type);
6383
6384       if Discriminant_Specs then
6385          Set_Has_Unknown_Discriminants (Derived_Type, False);
6386
6387          --  The following call initializes fields Has_Discriminants and
6388          --  Discriminant_Constraint, unless we are processing the completion
6389          --  of a private type declaration.
6390
6391          Check_Or_Process_Discriminants (N, Derived_Type);
6392
6393          --  For non-tagged types the constraint on the Parent_Type must be
6394          --  present and is used to rename the discriminants.
6395
6396          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
6397             Error_Msg_N ("untagged parent must have discriminants", Indic);
6398
6399          elsif not Is_Tagged and then not Constraint_Present then
6400             Error_Msg_N
6401               ("discriminant constraint needed for derived untagged records",
6402                Indic);
6403
6404          --  Otherwise the parent subtype must be constrained unless we have a
6405          --  private extension.
6406
6407          elsif not Constraint_Present
6408            and then not Private_Extension
6409            and then not Is_Constrained (Parent_Type)
6410          then
6411             Error_Msg_N
6412               ("unconstrained type not allowed in this context", Indic);
6413
6414          elsif Constraint_Present then
6415             --  The following call sets the field Corresponding_Discriminant
6416             --  for the discriminants in the Derived_Type.
6417
6418             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
6419
6420             --  For untagged types all new discriminants must rename
6421             --  discriminants in the parent. For private extensions new
6422             --  discriminants cannot rename old ones (implied by [7.3(13)]).
6423
6424             Discrim := First_Discriminant (Derived_Type);
6425             while Present (Discrim) loop
6426                if not Is_Tagged
6427                  and then No (Corresponding_Discriminant (Discrim))
6428                then
6429                   Error_Msg_N
6430                     ("new discriminants must constrain old ones", Discrim);
6431
6432                elsif Private_Extension
6433                  and then Present (Corresponding_Discriminant (Discrim))
6434                then
6435                   Error_Msg_N
6436                     ("only static constraints allowed for parent"
6437                      & " discriminants in the partial view", Indic);
6438                   exit;
6439                end if;
6440
6441                --  If a new discriminant is used in the constraint, then its
6442                --  subtype must be statically compatible with the parent
6443                --  discriminant's subtype (3.7(15)).
6444
6445                if Present (Corresponding_Discriminant (Discrim))
6446                  and then
6447                    not Subtypes_Statically_Compatible
6448                          (Etype (Discrim),
6449                           Etype (Corresponding_Discriminant (Discrim)))
6450                then
6451                   Error_Msg_N
6452                     ("subtype must be compatible with parent discriminant",
6453                      Discrim);
6454                end if;
6455
6456                Next_Discriminant (Discrim);
6457             end loop;
6458
6459             --  Check whether the constraints of the full view statically
6460             --  match those imposed by the parent subtype [7.3(13)].
6461
6462             if Present (Stored_Constraint (Derived_Type)) then
6463                declare
6464                   C1, C2 : Elmt_Id;
6465
6466                begin
6467                   C1 := First_Elmt (Discs);
6468                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
6469                   while Present (C1) and then Present (C2) loop
6470                      if not
6471                        Fully_Conformant_Expressions (Node (C1), Node (C2))
6472                      then
6473                         Error_Msg_N
6474                           ("not conformant with previous declaration",
6475                            Node (C1));
6476                      end if;
6477
6478                      Next_Elmt (C1);
6479                      Next_Elmt (C2);
6480                   end loop;
6481                end;
6482             end if;
6483          end if;
6484
6485       --  STEP 2b: No new discriminants, inherit discriminants if any
6486
6487       else
6488          if Private_Extension then
6489             Set_Has_Unknown_Discriminants
6490               (Derived_Type,
6491                Has_Unknown_Discriminants (Parent_Type)
6492                  or else Unknown_Discriminants_Present (N));
6493
6494          --  The partial view of the parent may have unknown discriminants,
6495          --  but if the full view has discriminants and the parent type is
6496          --  in scope they must be inherited.
6497
6498          elsif Has_Unknown_Discriminants (Parent_Type)
6499            and then
6500             (not Has_Discriminants (Parent_Type)
6501               or else not In_Open_Scopes (Scope (Parent_Type)))
6502          then
6503             Set_Has_Unknown_Discriminants (Derived_Type);
6504          end if;
6505
6506          if not Has_Unknown_Discriminants (Derived_Type)
6507            and then not Has_Unknown_Discriminants (Parent_Base)
6508            and then Has_Discriminants (Parent_Type)
6509          then
6510             Inherit_Discrims := True;
6511             Set_Has_Discriminants
6512               (Derived_Type, True);
6513             Set_Discriminant_Constraint
6514               (Derived_Type, Discriminant_Constraint (Parent_Base));
6515          end if;
6516
6517          --  The following test is true for private types (remember
6518          --  transformation 5. is not applied to those) and in an error
6519          --  situation.
6520
6521          if Constraint_Present then
6522             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
6523          end if;
6524
6525          --  For now mark a new derived type as constrained only if it has no
6526          --  discriminants. At the end of Build_Derived_Record_Type we properly
6527          --  set this flag in the case of private extensions. See comments in
6528          --  point 9. just before body of Build_Derived_Record_Type.
6529
6530          Set_Is_Constrained
6531            (Derived_Type,
6532             not (Inherit_Discrims
6533                    or else Has_Unknown_Discriminants (Derived_Type)));
6534       end if;
6535
6536       --  STEP 3: initialize fields of derived type
6537
6538       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
6539       Set_Stored_Constraint (Derived_Type, No_Elist);
6540
6541       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
6542       --  but cannot be interfaces
6543
6544       if not Private_Extension
6545          and then Ekind (Derived_Type) /= E_Private_Type
6546          and then Ekind (Derived_Type) /= E_Limited_Private_Type
6547       then
6548          if Interface_Present (Type_Def) then
6549             Analyze_Interface_Declaration (Derived_Type, Type_Def);
6550          end if;
6551
6552          Set_Abstract_Interfaces (Derived_Type, No_Elist);
6553       end if;
6554
6555       --  Fields inherited from the Parent_Type
6556
6557       Set_Discard_Names
6558         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
6559       Set_Has_Specified_Layout
6560         (Derived_Type, Has_Specified_Layout (Parent_Type));
6561       Set_Is_Limited_Composite
6562         (Derived_Type, Is_Limited_Composite (Parent_Type));
6563       Set_Is_Private_Composite
6564         (Derived_Type, Is_Private_Composite (Parent_Type));
6565
6566       --  Fields inherited from the Parent_Base
6567
6568       Set_Has_Controlled_Component
6569         (Derived_Type, Has_Controlled_Component (Parent_Base));
6570       Set_Has_Non_Standard_Rep
6571         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
6572       Set_Has_Primitive_Operations
6573         (Derived_Type, Has_Primitive_Operations (Parent_Base));
6574
6575       --  For non-private case, we also inherit Has_Complex_Representation
6576
6577       if Ekind (Derived_Type) = E_Record_Type then
6578          Set_Has_Complex_Representation
6579            (Derived_Type, Has_Complex_Representation (Parent_Base));
6580       end if;
6581
6582       --  Direct controlled types do not inherit Finalize_Storage_Only flag
6583
6584       if not Is_Controlled (Parent_Type) then
6585          Set_Finalize_Storage_Only
6586            (Derived_Type, Finalize_Storage_Only (Parent_Type));
6587       end if;
6588
6589       --  Set fields for private derived types
6590
6591       if Is_Private_Type (Derived_Type) then
6592          Set_Depends_On_Private (Derived_Type, True);
6593          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6594
6595       --  Inherit fields from non private record types. If this is the
6596       --  completion of a derivation from a private type, the parent itself
6597       --  is private, and the attributes come from its full view, which must
6598       --  be present.
6599
6600       else
6601          if Is_Private_Type (Parent_Base)
6602            and then not Is_Record_Type (Parent_Base)
6603          then
6604             Set_Component_Alignment
6605               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
6606             Set_C_Pass_By_Copy
6607               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
6608          else
6609             Set_Component_Alignment
6610               (Derived_Type, Component_Alignment (Parent_Base));
6611
6612             Set_C_Pass_By_Copy
6613               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
6614          end if;
6615       end if;
6616
6617       --  Set fields for tagged types
6618
6619       if Is_Tagged then
6620          Set_Primitive_Operations (Derived_Type, New_Elmt_List);
6621
6622          --  All tagged types defined in Ada.Finalization are controlled
6623
6624          if Chars (Scope (Derived_Type)) = Name_Finalization
6625            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
6626            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
6627          then
6628             Set_Is_Controlled (Derived_Type);
6629          else
6630             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
6631          end if;
6632
6633          Make_Class_Wide_Type (Derived_Type);
6634          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
6635
6636          if Has_Discriminants (Derived_Type)
6637            and then Constraint_Present
6638          then
6639             Set_Stored_Constraint
6640               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
6641          end if;
6642
6643          if Ada_Version >= Ada_05 then
6644             declare
6645                Ifaces_List : Elist_Id;
6646
6647             begin
6648                --  Checks rules 3.9.4 (13/2 and 14/2)
6649
6650                if Comes_From_Source (Derived_Type)
6651                  and then not Is_Private_Type (Derived_Type)
6652                  and then Is_Interface (Parent_Type)
6653                  and then not Is_Interface (Derived_Type)
6654                then
6655                   if Is_Task_Interface (Parent_Type) then
6656                      Error_Msg_N
6657                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
6658                         Derived_Type);
6659
6660                   elsif Is_Protected_Interface (Parent_Type) then
6661                      Error_Msg_N
6662                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
6663                         Derived_Type);
6664                   end if;
6665                end if;
6666
6667                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
6668
6669                Check_Abstract_Interfaces (N, Type_Def);
6670
6671                --  Ada 2005 (AI-251): Collect the list of progenitors that are
6672                --  not already in the parents.
6673
6674                Collect_Abstract_Interfaces
6675                  (T                         => Derived_Type,
6676                   Ifaces_List               => Ifaces_List,
6677                   Exclude_Parent_Interfaces => True);
6678                Set_Abstract_Interfaces (Derived_Type, Ifaces_List);
6679             end;
6680          end if;
6681
6682       else
6683          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
6684          Set_Has_Non_Standard_Rep
6685                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
6686       end if;
6687
6688       --  STEP 4: Inherit components from the parent base and constrain them.
6689       --          Apply the second transformation described in point 6. above.
6690
6691       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
6692         or else not Has_Discriminants (Parent_Type)
6693         or else not Is_Constrained (Parent_Type)
6694       then
6695          Constrs := Discs;
6696       else
6697          Constrs := Discriminant_Constraint (Parent_Type);
6698       end if;
6699
6700       Assoc_List :=
6701         Inherit_Components
6702           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
6703
6704       --  STEP 5a: Copy the parent record declaration for untagged types
6705
6706       if not Is_Tagged then
6707
6708          --  Discriminant_Constraint (Derived_Type) has been properly
6709          --  constructed. Save it and temporarily set it to Empty because we
6710          --  do not want the call to New_Copy_Tree below to mess this list.
6711
6712          if Has_Discriminants (Derived_Type) then
6713             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
6714             Set_Discriminant_Constraint (Derived_Type, No_Elist);
6715          else
6716             Save_Discr_Constr := No_Elist;
6717          end if;
6718
6719          --  Save the Etype field of Derived_Type. It is correctly set now,
6720          --  but the call to New_Copy tree may remap it to point to itself,
6721          --  which is not what we want. Ditto for the Next_Entity field.
6722
6723          Save_Etype       := Etype (Derived_Type);
6724          Save_Next_Entity := Next_Entity (Derived_Type);
6725
6726          --  Assoc_List maps all stored discriminants in the Parent_Base to
6727          --  stored discriminants in the Derived_Type. It is fundamental that
6728          --  no types or itypes with discriminants other than the stored
6729          --  discriminants appear in the entities declared inside
6730          --  Derived_Type, since the back end cannot deal with it.
6731
6732          New_Decl :=
6733            New_Copy_Tree
6734              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
6735
6736          --  Restore the fields saved prior to the New_Copy_Tree call
6737          --  and compute the stored constraint.
6738
6739          Set_Etype       (Derived_Type, Save_Etype);
6740          Set_Next_Entity (Derived_Type, Save_Next_Entity);
6741
6742          if Has_Discriminants (Derived_Type) then
6743             Set_Discriminant_Constraint
6744               (Derived_Type, Save_Discr_Constr);
6745             Set_Stored_Constraint
6746               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
6747             Replace_Components (Derived_Type, New_Decl);
6748          end if;
6749
6750          --  Insert the new derived type declaration
6751
6752          Rewrite (N, New_Decl);
6753
6754       --  STEP 5b: Complete the processing for record extensions in generics
6755
6756       --  There is no completion for record extensions declared in the
6757       --  parameter part of a generic, so we need to complete processing for
6758       --  these generic record extensions here. The Record_Type_Definition call
6759       --  will change the Ekind of the components from E_Void to E_Component.
6760
6761       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
6762          Record_Type_Definition (Empty, Derived_Type);
6763
6764       --  STEP 5c: Process the record extension for non private tagged types
6765
6766       elsif not Private_Extension then
6767
6768          --  Add the _parent field in the derived type
6769
6770          Expand_Record_Extension (Derived_Type, Type_Def);
6771
6772          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
6773          --  implemented interfaces if we are in expansion mode
6774
6775          if Expander_Active
6776            and then Has_Abstract_Interfaces (Derived_Type)
6777          then
6778             Add_Interface_Tag_Components (N, Derived_Type);
6779          end if;
6780
6781          --  Analyze the record extension
6782
6783          Record_Type_Definition
6784            (Record_Extension_Part (Type_Def), Derived_Type);
6785       end if;
6786
6787       End_Scope;
6788
6789       --  Nothing else to do if there is an error in the derivation.
6790       --  An unusual case: the full view may be derived from a type in an
6791       --  instance, when the partial view was used illegally as an actual
6792       --  in that instance, leading to a circular definition.
6793
6794       if Etype (Derived_Type) = Any_Type
6795         or else Etype (Parent_Type) = Derived_Type
6796       then
6797          return;
6798       end if;
6799
6800       --  Set delayed freeze and then derive subprograms, we need to do
6801       --  this in this order so that derived subprograms inherit the
6802       --  derived freeze if necessary.
6803
6804       Set_Has_Delayed_Freeze (Derived_Type);
6805
6806       if Derive_Subps then
6807          Derive_Subprograms (Parent_Type, Derived_Type);
6808       end if;
6809
6810       --  If we have a private extension which defines a constrained derived
6811       --  type mark as constrained here after we have derived subprograms. See
6812       --  comment on point 9. just above the body of Build_Derived_Record_Type.
6813
6814       if Private_Extension and then Inherit_Discrims then
6815          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
6816             Set_Is_Constrained          (Derived_Type, True);
6817             Set_Discriminant_Constraint (Derived_Type, Discs);
6818
6819          elsif Is_Constrained (Parent_Type) then
6820             Set_Is_Constrained
6821               (Derived_Type, True);
6822             Set_Discriminant_Constraint
6823               (Derived_Type, Discriminant_Constraint (Parent_Type));
6824          end if;
6825       end if;
6826
6827       --  Update the class_wide type, which shares the now-completed
6828       --  entity list with its specific type.
6829
6830       if Is_Tagged then
6831          Set_First_Entity
6832            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
6833          Set_Last_Entity
6834            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
6835       end if;
6836
6837       --  Update the scope of anonymous access types of discriminants and other
6838       --  components, to prevent scope anomalies in gigi, when the derivation
6839       --  appears in a scope nested within that of the parent.
6840
6841       declare
6842          D : Entity_Id;
6843
6844       begin
6845          D := First_Entity (Derived_Type);
6846          while Present (D) loop
6847             if Ekind (D) = E_Discriminant
6848               or else Ekind (D) = E_Component
6849             then
6850                if Is_Itype (Etype (D))
6851                   and then Ekind (Etype (D)) = E_Anonymous_Access_Type
6852                then
6853                   Set_Scope (Etype (D), Current_Scope);
6854                end if;
6855             end if;
6856
6857             Next_Entity (D);
6858          end loop;
6859       end;
6860    end Build_Derived_Record_Type;
6861
6862    ------------------------
6863    -- Build_Derived_Type --
6864    ------------------------
6865
6866    procedure Build_Derived_Type
6867      (N             : Node_Id;
6868       Parent_Type   : Entity_Id;
6869       Derived_Type  : Entity_Id;
6870       Is_Completion : Boolean;
6871       Derive_Subps  : Boolean := True)
6872    is
6873       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
6874
6875    begin
6876       --  Set common attributes
6877
6878       Set_Scope         (Derived_Type, Current_Scope);
6879
6880       Set_Ekind         (Derived_Type, Ekind    (Parent_Base));
6881       Set_Etype         (Derived_Type,           Parent_Base);
6882       Set_Has_Task      (Derived_Type, Has_Task (Parent_Base));
6883
6884       Set_Size_Info     (Derived_Type,                Parent_Type);
6885       Set_RM_Size       (Derived_Type, RM_Size       (Parent_Type));
6886       Set_Convention    (Derived_Type, Convention    (Parent_Type));
6887       Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Type));
6888
6889       --  The derived type inherits the representation clauses of the parent.
6890       --  However, for a private type that is completed by a derivation, there
6891       --  may be operation attributes that have been specified already (stream
6892       --  attributes and External_Tag) and those must be provided. Finally,
6893       --  if the partial view is a private extension, the representation items
6894       --  of the parent have been inherited already, and should not be chained
6895       --  twice to the derived type.
6896
6897       if Is_Tagged_Type (Parent_Type)
6898         and then Present (First_Rep_Item (Derived_Type))
6899       then
6900          --  The existing items are either operational items or items inherited
6901          --  from a private extension declaration.
6902
6903          declare
6904             Rep : Node_Id;
6905             --  Used to iterate over representation items of the derived type
6906
6907             Last_Rep : Node_Id;
6908             --  Last representation item of the (non-empty) representation
6909             --  item list of the derived type.
6910
6911             Found : Boolean := False;
6912
6913          begin
6914             Rep      := First_Rep_Item (Derived_Type);
6915             Last_Rep := Rep;
6916             while Present (Rep) loop
6917                if Rep = First_Rep_Item (Parent_Type) then
6918                   Found := True;
6919                   exit;
6920
6921                else
6922                   Rep := Next_Rep_Item (Rep);
6923
6924                   if Present (Rep) then
6925                      Last_Rep := Rep;
6926                   end if;
6927                end if;
6928             end loop;
6929
6930             --  Here if we either encountered the parent type's first rep
6931             --  item on the derived type's rep item list (in which case
6932             --  Found is True, and we have nothing else to do), or if we
6933             --  reached the last rep item of the derived type, which is
6934             --  Last_Rep, in which case we further chain the parent type's
6935             --  rep items to those of the derived type.
6936
6937             if not Found then
6938                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
6939             end if;
6940          end;
6941
6942       else
6943          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
6944       end if;
6945
6946       case Ekind (Parent_Type) is
6947          when Numeric_Kind =>
6948             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
6949
6950          when Array_Kind =>
6951             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
6952
6953          when E_Record_Type
6954             | E_Record_Subtype
6955             | Class_Wide_Kind  =>
6956             Build_Derived_Record_Type
6957               (N, Parent_Type, Derived_Type, Derive_Subps);
6958             return;
6959
6960          when Enumeration_Kind =>
6961             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
6962
6963          when Access_Kind =>
6964             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
6965
6966          when Incomplete_Or_Private_Kind =>
6967             Build_Derived_Private_Type
6968               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
6969
6970             --  For discriminated types, the derivation includes deriving
6971             --  primitive operations. For others it is done below.
6972
6973             if Is_Tagged_Type (Parent_Type)
6974               or else Has_Discriminants (Parent_Type)
6975               or else (Present (Full_View (Parent_Type))
6976                         and then Has_Discriminants (Full_View (Parent_Type)))
6977             then
6978                return;
6979             end if;
6980
6981          when Concurrent_Kind =>
6982             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
6983
6984          when others =>
6985             raise Program_Error;
6986       end case;
6987
6988       if Etype (Derived_Type) = Any_Type then
6989          return;
6990       end if;
6991
6992       --  Set delayed freeze and then derive subprograms, we need to do this
6993       --  in this order so that derived subprograms inherit the derived freeze
6994       --  if necessary.
6995
6996       Set_Has_Delayed_Freeze (Derived_Type);
6997       if Derive_Subps then
6998          Derive_Subprograms (Parent_Type, Derived_Type);
6999       end if;
7000
7001       Set_Has_Primitive_Operations
7002         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
7003    end Build_Derived_Type;
7004
7005    -----------------------
7006    -- Build_Discriminal --
7007    -----------------------
7008
7009    procedure Build_Discriminal (Discrim : Entity_Id) is
7010       D_Minal : Entity_Id;
7011       CR_Disc : Entity_Id;
7012
7013    begin
7014       --  A discriminal has the same name as the discriminant
7015
7016       D_Minal :=
7017         Make_Defining_Identifier (Sloc (Discrim),
7018           Chars => Chars (Discrim));
7019
7020       Set_Ekind     (D_Minal, E_In_Parameter);
7021       Set_Mechanism (D_Minal, Default_Mechanism);
7022       Set_Etype     (D_Minal, Etype (Discrim));
7023
7024       Set_Discriminal (Discrim, D_Minal);
7025       Set_Discriminal_Link (D_Minal, Discrim);
7026
7027       --  For task types, build at once the discriminants of the corresponding
7028       --  record, which are needed if discriminants are used in entry defaults
7029       --  and in family bounds.
7030
7031       if Is_Concurrent_Type (Current_Scope)
7032         or else Is_Limited_Type (Current_Scope)
7033       then
7034          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
7035
7036          Set_Ekind            (CR_Disc, E_In_Parameter);
7037          Set_Mechanism        (CR_Disc, Default_Mechanism);
7038          Set_Etype            (CR_Disc, Etype (Discrim));
7039          Set_Discriminal_Link (CR_Disc, Discrim);
7040          Set_CR_Discriminant  (Discrim, CR_Disc);
7041       end if;
7042    end Build_Discriminal;
7043
7044    ------------------------------------
7045    -- Build_Discriminant_Constraints --
7046    ------------------------------------
7047
7048    function Build_Discriminant_Constraints
7049      (T           : Entity_Id;
7050       Def         : Node_Id;
7051       Derived_Def : Boolean := False) return Elist_Id
7052    is
7053       C        : constant Node_Id := Constraint (Def);
7054       Nb_Discr : constant Nat     := Number_Discriminants (T);
7055
7056       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
7057       --  Saves the expression corresponding to a given discriminant in T
7058
7059       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
7060       --  Return the Position number within array Discr_Expr of a discriminant
7061       --  D within the discriminant list of the discriminated type T.
7062
7063       ------------------
7064       -- Pos_Of_Discr --
7065       ------------------
7066
7067       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
7068          Disc : Entity_Id;
7069
7070       begin
7071          Disc := First_Discriminant (T);
7072          for J in Discr_Expr'Range loop
7073             if Disc = D then
7074                return J;
7075             end if;
7076
7077             Next_Discriminant (Disc);
7078          end loop;
7079
7080          --  Note: Since this function is called on discriminants that are
7081          --  known to belong to the discriminated type, falling through the
7082          --  loop with no match signals an internal compiler error.
7083
7084          raise Program_Error;
7085       end Pos_Of_Discr;
7086
7087       --  Declarations local to Build_Discriminant_Constraints
7088
7089       Discr : Entity_Id;
7090       E     : Entity_Id;
7091       Elist : constant Elist_Id := New_Elmt_List;
7092
7093       Constr   : Node_Id;
7094       Expr     : Node_Id;
7095       Id       : Node_Id;
7096       Position : Nat;
7097       Found    : Boolean;
7098
7099       Discrim_Present : Boolean := False;
7100
7101    --  Start of processing for Build_Discriminant_Constraints
7102
7103    begin
7104       --  The following loop will process positional associations only.
7105       --  For a positional association, the (single) discriminant is
7106       --  implicitly specified by position, in textual order (RM 3.7.2).
7107
7108       Discr  := First_Discriminant (T);
7109       Constr := First (Constraints (C));
7110       for D in Discr_Expr'Range loop
7111          exit when Nkind (Constr) = N_Discriminant_Association;
7112
7113          if No (Constr) then
7114             Error_Msg_N ("too few discriminants given in constraint", C);
7115             return New_Elmt_List;
7116
7117          elsif Nkind (Constr) = N_Range
7118            or else (Nkind (Constr) = N_Attribute_Reference
7119                      and then
7120                     Attribute_Name (Constr) = Name_Range)
7121          then
7122             Error_Msg_N
7123               ("a range is not a valid discriminant constraint", Constr);
7124             Discr_Expr (D) := Error;
7125
7126          else
7127             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
7128             Discr_Expr (D) := Constr;
7129          end if;
7130
7131          Next_Discriminant (Discr);
7132          Next (Constr);
7133       end loop;
7134
7135       if No (Discr) and then Present (Constr) then
7136          Error_Msg_N ("too many discriminants given in constraint", Constr);
7137          return New_Elmt_List;
7138       end if;
7139
7140       --  Named associations can be given in any order, but if both positional
7141       --  and named associations are used in the same discriminant constraint,
7142       --  then positional associations must occur first, at their normal
7143       --  position. Hence once a named association is used, the rest of the
7144       --  discriminant constraint must use only named associations.
7145
7146       while Present (Constr) loop
7147
7148          --  Positional association forbidden after a named association
7149
7150          if Nkind (Constr) /= N_Discriminant_Association then
7151             Error_Msg_N ("positional association follows named one", Constr);
7152             return New_Elmt_List;
7153
7154          --  Otherwise it is a named association
7155
7156          else
7157             --  E records the type of the discriminants in the named
7158             --  association. All the discriminants specified in the same name
7159             --  association must have the same type.
7160
7161             E := Empty;
7162
7163             --  Search the list of discriminants in T to see if the simple name
7164             --  given in the constraint matches any of them.
7165
7166             Id := First (Selector_Names (Constr));
7167             while Present (Id) loop
7168                Found := False;
7169
7170                --  If Original_Discriminant is present, we are processing a
7171                --  generic instantiation and this is an instance node. We need
7172                --  to find the name of the corresponding discriminant in the
7173                --  actual record type T and not the name of the discriminant in
7174                --  the generic formal. Example:
7175
7176                --    generic
7177                --       type G (D : int) is private;
7178                --    package P is
7179                --       subtype W is G (D => 1);
7180                --    end package;
7181                --    type Rec (X : int) is record ... end record;
7182                --    package Q is new P (G => Rec);
7183
7184                --  At the point of the instantiation, formal type G is Rec
7185                --  and therefore when reanalyzing "subtype W is G (D => 1);"
7186                --  which really looks like "subtype W is Rec (D => 1);" at
7187                --  the point of instantiation, we want to find the discriminant
7188                --  that corresponds to D in Rec, ie X.
7189
7190                if Present (Original_Discriminant (Id)) then
7191                   Discr := Find_Corresponding_Discriminant (Id, T);
7192                   Found := True;
7193
7194                else
7195                   Discr := First_Discriminant (T);
7196                   while Present (Discr) loop
7197                      if Chars (Discr) = Chars (Id) then
7198                         Found := True;
7199                         exit;
7200                      end if;
7201
7202                      Next_Discriminant (Discr);
7203                   end loop;
7204
7205                   if not Found then
7206                      Error_Msg_N ("& does not match any discriminant", Id);
7207                      return New_Elmt_List;
7208
7209                   --  The following is only useful for the benefit of generic
7210                   --  instances but it does not interfere with other
7211                   --  processing for the non-generic case so we do it in all
7212                   --  cases (for generics this statement is executed when
7213                   --  processing the generic definition, see comment at the
7214                   --  beginning of this if statement).
7215
7216                   else
7217                      Set_Original_Discriminant (Id, Discr);
7218                   end if;
7219                end if;
7220
7221                Position := Pos_Of_Discr (T, Discr);
7222
7223                if Present (Discr_Expr (Position)) then
7224                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
7225
7226                else
7227                   --  Each discriminant specified in the same named association
7228                   --  must be associated with a separate copy of the
7229                   --  corresponding expression.
7230
7231                   if Present (Next (Id)) then
7232                      Expr := New_Copy_Tree (Expression (Constr));
7233                      Set_Parent (Expr, Parent (Expression (Constr)));
7234                   else
7235                      Expr := Expression (Constr);
7236                   end if;
7237
7238                   Discr_Expr (Position) := Expr;
7239                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
7240                end if;
7241
7242                --  A discriminant association with more than one discriminant
7243                --  name is only allowed if the named discriminants are all of
7244                --  the same type (RM 3.7.1(8)).
7245
7246                if E = Empty then
7247                   E := Base_Type (Etype (Discr));
7248
7249                elsif Base_Type (Etype (Discr)) /= E then
7250                   Error_Msg_N
7251                     ("all discriminants in an association " &
7252                      "must have the same type", Id);
7253                end if;
7254
7255                Next (Id);
7256             end loop;
7257          end if;
7258
7259          Next (Constr);
7260       end loop;
7261
7262       --  A discriminant constraint must provide exactly one value for each
7263       --  discriminant of the type (RM 3.7.1(8)).
7264
7265       for J in Discr_Expr'Range loop
7266          if No (Discr_Expr (J)) then
7267             Error_Msg_N ("too few discriminants given in constraint", C);
7268             return New_Elmt_List;
7269          end if;
7270       end loop;
7271
7272       --  Determine if there are discriminant expressions in the constraint
7273
7274       for J in Discr_Expr'Range loop
7275          if Denotes_Discriminant
7276               (Discr_Expr (J), Check_Concurrent => True)
7277          then
7278             Discrim_Present := True;
7279          end if;
7280       end loop;
7281
7282       --  Build an element list consisting of the expressions given in the
7283       --  discriminant constraint and apply the appropriate checks. The list
7284       --  is constructed after resolving any named discriminant associations
7285       --  and therefore the expressions appear in the textual order of the
7286       --  discriminants.
7287
7288       Discr := First_Discriminant (T);
7289       for J in Discr_Expr'Range loop
7290          if Discr_Expr (J) /= Error then
7291             Append_Elmt (Discr_Expr (J), Elist);
7292
7293             --  If any of the discriminant constraints is given by a
7294             --  discriminant and we are in a derived type declaration we
7295             --  have a discriminant renaming. Establish link between new
7296             --  and old discriminant.
7297
7298             if Denotes_Discriminant (Discr_Expr (J)) then
7299                if Derived_Def then
7300                   Set_Corresponding_Discriminant
7301                     (Entity (Discr_Expr (J)), Discr);
7302                end if;
7303
7304             --  Force the evaluation of non-discriminant expressions.
7305             --  If we have found a discriminant in the constraint 3.4(26)
7306             --  and 3.8(18) demand that no range checks are performed are
7307             --  after evaluation. If the constraint is for a component
7308             --  definition that has a per-object constraint, expressions are
7309             --  evaluated but not checked either. In all other cases perform
7310             --  a range check.
7311
7312             else
7313                if Discrim_Present then
7314                   null;
7315
7316                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
7317                  and then
7318                    Has_Per_Object_Constraint
7319                      (Defining_Identifier (Parent (Parent (Def))))
7320                then
7321                   null;
7322
7323                elsif Is_Access_Type (Etype (Discr)) then
7324                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
7325
7326                else
7327                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
7328                end if;
7329
7330                Force_Evaluation (Discr_Expr (J));
7331             end if;
7332
7333             --  Check that the designated type of an access discriminant's
7334             --  expression is not a class-wide type unless the discriminant's
7335             --  designated type is also class-wide.
7336
7337             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
7338               and then not Is_Class_Wide_Type
7339                          (Designated_Type (Etype (Discr)))
7340               and then Etype (Discr_Expr (J)) /= Any_Type
7341               and then Is_Class_Wide_Type
7342                          (Designated_Type (Etype (Discr_Expr (J))))
7343             then
7344                Wrong_Type (Discr_Expr (J), Etype (Discr));
7345             end if;
7346          end if;
7347
7348          Next_Discriminant (Discr);
7349       end loop;
7350
7351       return Elist;
7352    end Build_Discriminant_Constraints;
7353
7354    ---------------------------------
7355    -- Build_Discriminated_Subtype --
7356    ---------------------------------
7357
7358    procedure Build_Discriminated_Subtype
7359      (T           : Entity_Id;
7360       Def_Id      : Entity_Id;
7361       Elist       : Elist_Id;
7362       Related_Nod : Node_Id;
7363       For_Access  : Boolean := False)
7364    is
7365       Has_Discrs  : constant Boolean := Has_Discriminants (T);
7366       Constrained : constant Boolean :=
7367                       (Has_Discrs
7368                          and then not Is_Empty_Elmt_List (Elist)
7369                          and then not Is_Class_Wide_Type (T))
7370                         or else Is_Constrained (T);
7371
7372    begin
7373       if Ekind (T) = E_Record_Type then
7374          if For_Access then
7375             Set_Ekind (Def_Id, E_Private_Subtype);
7376             Set_Is_For_Access_Subtype (Def_Id, True);
7377          else
7378             Set_Ekind (Def_Id, E_Record_Subtype);
7379          end if;
7380
7381       elsif Ekind (T) = E_Task_Type then
7382          Set_Ekind (Def_Id, E_Task_Subtype);
7383
7384       elsif Ekind (T) = E_Protected_Type then
7385          Set_Ekind (Def_Id, E_Protected_Subtype);
7386
7387       elsif Is_Private_Type (T) then
7388          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
7389
7390       elsif Is_Class_Wide_Type (T) then
7391          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
7392
7393       else
7394          --  Incomplete type. Attach subtype to list of dependents, to be
7395          --  completed with full view of parent type,  unless is it the
7396          --  designated subtype of a record component within an init_proc.
7397          --  This last case arises for a component of an access type whose
7398          --  designated type is incomplete (e.g. a Taft Amendment type).
7399          --  The designated subtype is within an inner scope, and needs no
7400          --  elaboration, because only the access type is needed in the
7401          --  initialization procedure.
7402
7403          Set_Ekind (Def_Id, Ekind (T));
7404
7405          if For_Access and then Within_Init_Proc then
7406             null;
7407          else
7408             Append_Elmt (Def_Id, Private_Dependents (T));
7409          end if;
7410       end if;
7411
7412       Set_Etype             (Def_Id, T);
7413       Init_Size_Align       (Def_Id);
7414       Set_Has_Discriminants (Def_Id, Has_Discrs);
7415       Set_Is_Constrained    (Def_Id, Constrained);
7416
7417       Set_First_Entity      (Def_Id, First_Entity   (T));
7418       Set_Last_Entity       (Def_Id, Last_Entity    (T));
7419       Set_First_Rep_Item    (Def_Id, First_Rep_Item (T));
7420
7421       if Is_Tagged_Type (T) then
7422          Set_Is_Tagged_Type  (Def_Id);
7423          Make_Class_Wide_Type (Def_Id);
7424       end if;
7425
7426       Set_Stored_Constraint (Def_Id, No_Elist);
7427
7428       if Has_Discrs then
7429          Set_Discriminant_Constraint (Def_Id, Elist);
7430          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
7431       end if;
7432
7433       if Is_Tagged_Type (T) then
7434
7435          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
7436          --  concurrent record type (which has the list of primitive
7437          --  operations).
7438
7439          if Ada_Version >= Ada_05
7440            and then Is_Concurrent_Type (T)
7441          then
7442             Set_Corresponding_Record_Type (Def_Id,
7443                Corresponding_Record_Type (T));
7444          else
7445             Set_Primitive_Operations (Def_Id, Primitive_Operations (T));
7446          end if;
7447
7448          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
7449       end if;
7450
7451       --  Subtypes introduced by component declarations do not need to be
7452       --  marked as delayed, and do not get freeze nodes, because the semantics
7453       --  verifies that the parents of the subtypes are frozen before the
7454       --  enclosing record is frozen.
7455
7456       if not Is_Type (Scope (Def_Id)) then
7457          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
7458
7459          if Is_Private_Type (T)
7460            and then Present (Full_View (T))
7461          then
7462             Conditional_Delay (Def_Id, Full_View (T));
7463          else
7464             Conditional_Delay (Def_Id, T);
7465          end if;
7466       end if;
7467
7468       if Is_Record_Type (T) then
7469          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
7470
7471          if Has_Discrs
7472             and then not Is_Empty_Elmt_List (Elist)
7473             and then not For_Access
7474          then
7475             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
7476          elsif not For_Access then
7477             Set_Cloned_Subtype (Def_Id, T);
7478          end if;
7479       end if;
7480    end Build_Discriminated_Subtype;
7481
7482    ---------------------------
7483    -- Build_Itype_Reference --
7484    ---------------------------
7485
7486    procedure Build_Itype_Reference
7487      (Ityp : Entity_Id;
7488       Nod  : Node_Id)
7489    is
7490       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
7491    begin
7492       Set_Itype (IR, Ityp);
7493       Insert_After (Nod, IR);
7494    end Build_Itype_Reference;
7495
7496    ------------------------
7497    -- Build_Scalar_Bound --
7498    ------------------------
7499
7500    function Build_Scalar_Bound
7501      (Bound : Node_Id;
7502       Par_T : Entity_Id;
7503       Der_T : Entity_Id) return Node_Id
7504    is
7505       New_Bound : Entity_Id;
7506
7507    begin
7508       --  Note: not clear why this is needed, how can the original bound
7509       --  be unanalyzed at this point? and if it is, what business do we
7510       --  have messing around with it? and why is the base type of the
7511       --  parent type the right type for the resolution. It probably is
7512       --  not! It is OK for the new bound we are creating, but not for
7513       --  the old one??? Still if it never happens, no problem!
7514
7515       Analyze_And_Resolve (Bound, Base_Type (Par_T));
7516
7517       if Nkind (Bound) = N_Integer_Literal
7518         or else Nkind (Bound) = N_Real_Literal
7519       then
7520          New_Bound := New_Copy (Bound);
7521          Set_Etype (New_Bound, Der_T);
7522          Set_Analyzed (New_Bound);
7523
7524       elsif Is_Entity_Name (Bound) then
7525          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
7526
7527       --  The following is almost certainly wrong. What business do we have
7528       --  relocating a node (Bound) that is presumably still attached to
7529       --  the tree elsewhere???
7530
7531       else
7532          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
7533       end if;
7534
7535       Set_Etype (New_Bound, Der_T);
7536       return New_Bound;
7537    end Build_Scalar_Bound;
7538
7539    --------------------------------
7540    -- Build_Underlying_Full_View --
7541    --------------------------------
7542
7543    procedure Build_Underlying_Full_View
7544      (N   : Node_Id;
7545       Typ : Entity_Id;
7546       Par : Entity_Id)
7547    is
7548       Loc  : constant Source_Ptr := Sloc (N);
7549       Subt : constant Entity_Id :=
7550                Make_Defining_Identifier
7551                  (Loc, New_External_Name (Chars (Typ), 'S'));
7552
7553       Constr : Node_Id;
7554       Indic  : Node_Id;
7555       C      : Node_Id;
7556       Id     : Node_Id;
7557
7558       procedure Set_Discriminant_Name (Id : Node_Id);
7559       --  If the derived type has discriminants, they may rename discriminants
7560       --  of the parent. When building the full view of the parent, we need to
7561       --  recover the names of the original discriminants if the constraint is
7562       --  given by named associations.
7563
7564       ---------------------------
7565       -- Set_Discriminant_Name --
7566       ---------------------------
7567
7568       procedure Set_Discriminant_Name (Id : Node_Id) is
7569          Disc : Entity_Id;
7570
7571       begin
7572          Set_Original_Discriminant (Id, Empty);
7573
7574          if Has_Discriminants (Typ) then
7575             Disc := First_Discriminant (Typ);
7576             while Present (Disc) loop
7577                if Chars (Disc) = Chars (Id)
7578                  and then Present (Corresponding_Discriminant (Disc))
7579                then
7580                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
7581                end if;
7582                Next_Discriminant (Disc);
7583             end loop;
7584          end if;
7585       end Set_Discriminant_Name;
7586
7587    --  Start of processing for Build_Underlying_Full_View
7588
7589    begin
7590       if Nkind (N) = N_Full_Type_Declaration then
7591          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
7592
7593       elsif Nkind (N) = N_Subtype_Declaration then
7594          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
7595
7596       elsif Nkind (N) = N_Component_Declaration then
7597          Constr :=
7598            New_Copy_Tree
7599              (Constraint (Subtype_Indication (Component_Definition (N))));
7600
7601       else
7602          raise Program_Error;
7603       end if;
7604
7605       C := First (Constraints (Constr));
7606       while Present (C) loop
7607          if Nkind (C) = N_Discriminant_Association then
7608             Id := First (Selector_Names (C));
7609             while Present (Id) loop
7610                Set_Discriminant_Name (Id);
7611                Next (Id);
7612             end loop;
7613          end if;
7614
7615          Next (C);
7616       end loop;
7617
7618       Indic :=
7619         Make_Subtype_Declaration (Loc,
7620           Defining_Identifier => Subt,
7621           Subtype_Indication  =>
7622             Make_Subtype_Indication (Loc,
7623               Subtype_Mark => New_Reference_To (Par, Loc),
7624               Constraint   => New_Copy_Tree (Constr)));
7625
7626       --  If this is a component subtype for an outer itype, it is not
7627       --  a list member, so simply set the parent link for analysis: if
7628       --  the enclosing type does not need to be in a declarative list,
7629       --  neither do the components.
7630
7631       if Is_List_Member (N)
7632         and then Nkind (N) /= N_Component_Declaration
7633       then
7634          Insert_Before (N, Indic);
7635       else
7636          Set_Parent (Indic, Parent (N));
7637       end if;
7638
7639       Analyze (Indic);
7640       Set_Underlying_Full_View (Typ, Full_View (Subt));
7641    end Build_Underlying_Full_View;
7642
7643    -------------------------------
7644    -- Check_Abstract_Interfaces --
7645    -------------------------------
7646
7647    procedure Check_Abstract_Interfaces (N : Node_Id; Def : Node_Id) is
7648
7649       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
7650       --  Local subprogram used to avoid code duplication. In case of error
7651       --  the message will be associated to Error_Node.
7652
7653       ------------------
7654       -- Check_Ifaces --
7655       ------------------
7656
7657       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
7658       begin
7659          --  Ada 2005 (AI-345): Protected interfaces can only inherit from
7660          --  limited, synchronized or protected interfaces.
7661
7662          if Protected_Present (Def) then
7663             if Limited_Present (Iface_Def)
7664               or else Synchronized_Present (Iface_Def)
7665               or else Protected_Present (Iface_Def)
7666             then
7667                null;
7668
7669             elsif Task_Present (Iface_Def) then
7670                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
7671                             & " from task interface", Error_Node);
7672
7673             else
7674                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
7675                             & " from non-limited interface", Error_Node);
7676             end if;
7677
7678          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
7679          --  limited and synchronized.
7680
7681          elsif Synchronized_Present (Def) then
7682             if Limited_Present (Iface_Def)
7683               or else Synchronized_Present (Iface_Def)
7684             then
7685                null;
7686
7687             elsif Protected_Present (Iface_Def) then
7688                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
7689                             & " from protected interface", Error_Node);
7690
7691             elsif Task_Present (Iface_Def) then
7692                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
7693                             & " from task interface", Error_Node);
7694
7695             else
7696                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
7697                             & " from non-limited interface", Error_Node);
7698             end if;
7699
7700          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
7701          --  synchronized or task interfaces.
7702
7703          elsif Task_Present (Def) then
7704             if Limited_Present (Iface_Def)
7705               or else Synchronized_Present (Iface_Def)
7706               or else Task_Present (Iface_Def)
7707             then
7708                null;
7709
7710             elsif Protected_Present (Iface_Def) then
7711                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
7712                             & " protected interface", Error_Node);
7713
7714             else
7715                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
7716                             & " non-limited interface", Error_Node);
7717             end if;
7718          end if;
7719       end Check_Ifaces;
7720
7721       --  Local variables
7722
7723       Iface       : Node_Id;
7724       Iface_Def   : Node_Id;
7725       Iface_Typ   : Entity_Id;
7726       Parent_Node : Node_Id;
7727
7728    --  Start of processing for Check_Abstract_Interfaces
7729
7730    begin
7731       --  Why is this still unsupported???
7732
7733       if Nkind (N) = N_Private_Extension_Declaration then
7734          return;
7735       end if;
7736
7737       --  Check the parent in case of derivation of interface type
7738
7739       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
7740         and then Is_Interface (Etype (Defining_Identifier (N)))
7741       then
7742          Parent_Node := Parent (Etype (Defining_Identifier (N)));
7743
7744          Check_Ifaces
7745            (Iface_Def  => Type_Definition (Parent_Node),
7746             Error_Node => Subtype_Indication (Type_Definition (N)));
7747       end if;
7748
7749       Iface := First (Interface_List (Def));
7750       while Present (Iface) loop
7751          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
7752
7753          Parent_Node := Parent (Base_Type (Iface_Typ));
7754          Iface_Def   := Type_Definition (Parent_Node);
7755
7756          if not Is_Interface (Iface_Typ) then
7757             Error_Msg_NE ("(Ada 2005) & must be an interface",
7758                           Iface, Iface_Typ);
7759
7760          else
7761             --  "The declaration of a specific descendant of an interface
7762             --   type freezes the interface type" RM 13.14
7763
7764             Freeze_Before (N, Iface_Typ);
7765             Check_Ifaces (Iface_Def, Error_Node => Iface);
7766          end if;
7767
7768          Next (Iface);
7769       end loop;
7770    end Check_Abstract_Interfaces;
7771
7772    -------------------------------
7773    -- Check_Abstract_Overriding --
7774    -------------------------------
7775
7776    procedure Check_Abstract_Overriding (T : Entity_Id) is
7777       Alias_Subp : Entity_Id;
7778       Elmt       : Elmt_Id;
7779       Op_List    : Elist_Id;
7780       Subp       : Entity_Id;
7781       Type_Def   : Node_Id;
7782
7783    begin
7784       Op_List := Primitive_Operations (T);
7785
7786       --  Loop to check primitive operations
7787
7788       Elmt := First_Elmt (Op_List);
7789       while Present (Elmt) loop
7790          Subp := Node (Elmt);
7791          Alias_Subp := Alias (Subp);
7792
7793          --  Inherited subprograms are identified by the fact that they do not
7794          --  come from source, and the associated source location is the
7795          --  location of the first subtype of the derived type.
7796
7797          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
7798          --  subprograms that "require overriding".
7799
7800          --  Special exception, do not complain about failure to override the
7801          --  stream routines _Input and _Output, as well as the primitive
7802          --  operations used in dispatching selects since we always provide
7803          --  automatic overridings for these subprograms.
7804
7805          --  Also ignore this rule for convention CIL since .NET libraries
7806          --  do bizarre things with interfaces???
7807
7808          --  The partial view of T may have been a private extension, for
7809          --  which inherited functions dispatching on result are abstract.
7810          --  If the full view is a null extension, there is no need for
7811          --  overriding in Ada2005, but wrappers need to be built for them
7812          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
7813
7814          --  Use elseif here and avoid above goto???
7815
7816          if Is_Null_Extension (T)
7817            and then Has_Controlling_Result (Subp)
7818            and then Ada_Version >= Ada_05
7819            and then Present (Alias (Subp))
7820            and then not Comes_From_Source (Subp)
7821            and then not Is_Abstract_Subprogram (Alias (Subp))
7822          then
7823             goto Next_Subp;
7824          end if;
7825
7826          if (Is_Abstract_Subprogram (Subp)
7827               or else Requires_Overriding (Subp)
7828               or else (Has_Controlling_Result (Subp)
7829                         and then Present (Alias_Subp)
7830                         and then not Comes_From_Source (Subp)
7831                         and then Sloc (Subp) = Sloc (First_Subtype (T))))
7832            and then not Is_TSS (Subp, TSS_Stream_Input)
7833            and then not Is_TSS (Subp, TSS_Stream_Output)
7834            and then not Is_Abstract_Type (T)
7835            and then Convention (T) /= Convention_CIL
7836            and then Chars (Subp) /= Name_uDisp_Asynchronous_Select
7837            and then Chars (Subp) /= Name_uDisp_Conditional_Select
7838            and then Chars (Subp) /= Name_uDisp_Get_Prim_Op_Kind
7839            and then Chars (Subp) /= Name_uDisp_Timed_Select
7840
7841             --  Ada 2005 (AI-251): Do not consider hidden entities associated
7842             --  with abstract interface types because the check will be done
7843             --  with the aliased entity (otherwise we generate a duplicated
7844             --  error message).
7845
7846            and then not Present (Abstract_Interface_Alias (Subp))
7847          then
7848             if Present (Alias_Subp) then
7849
7850                --  Only perform the check for a derived subprogram when the
7851                --  type has an explicit record extension. This avoids
7852                --  incorrectly flagging abstract subprograms for the case of a
7853                --  type without an extension derived from a formal type with a
7854                --  tagged actual (can occur within a private part).
7855
7856                --  Ada 2005 (AI-391): In the case of an inherited function with
7857                --  a controlling result of the type, the rule does not apply if
7858                --  the type is a null extension (unless the parent function
7859                --  itself is abstract, in which case the function must still be
7860                --  be overridden). The expander will generate an overriding
7861                --  wrapper function calling the parent subprogram (see
7862                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
7863
7864                Type_Def := Type_Definition (Parent (T));
7865                if Nkind (Type_Def) = N_Derived_Type_Definition
7866                  and then Present (Record_Extension_Part (Type_Def))
7867                  and then
7868                    (Ada_Version < Ada_05
7869                       or else not Is_Null_Extension (T)
7870                       or else Ekind (Subp) = E_Procedure
7871                       or else not Has_Controlling_Result (Subp)
7872                       or else Is_Abstract_Subprogram (Alias_Subp)
7873                       or else Requires_Overriding (Subp)
7874                       or else Is_Access_Type (Etype (Subp)))
7875                then
7876                   Error_Msg_NE
7877                     ("type must be declared abstract or & overridden",
7878                      T, Subp);
7879
7880                   --  Traverse the whole chain of aliased subprograms to
7881                   --  complete the error notification. This is especially
7882                   --  useful for traceability of the chain of entities when the
7883                   --  subprogram corresponds with an interface subprogram
7884                   --  (which might be defined in another package)
7885
7886                   if Present (Alias_Subp) then
7887                      declare
7888                         E : Entity_Id;
7889
7890                      begin
7891                         E := Subp;
7892                         while Present (Alias (E)) loop
7893                            Error_Msg_Sloc := Sloc (E);
7894                            Error_Msg_NE ("\& has been inherited #", T, Subp);
7895                            E := Alias (E);
7896                         end loop;
7897
7898                         Error_Msg_Sloc := Sloc (E);
7899                         Error_Msg_NE
7900                           ("\& has been inherited from subprogram #", T, Subp);
7901                      end;
7902                   end if;
7903
7904                --  Ada 2005 (AI-345): Protected or task type implementing
7905                --  abstract interfaces.
7906
7907                elsif Is_Concurrent_Record_Type (T)
7908                  and then Present (Abstract_Interfaces (T))
7909                then
7910                   --  The controlling formal of Subp must be of mode "out",
7911                   --  "in out" or an access-to-variable to be overridden.
7912
7913                   --  Error message below needs rewording (remember comma
7914                   --  in -gnatj mode) ???
7915
7916                   if Ekind (First_Formal (Subp)) = E_In_Parameter then
7917                      Error_Msg_NE
7918                        ("first formal of & must be of mode `OUT`, `IN OUT` " &
7919                         "or access-to-variable", T, Subp);
7920                      Error_Msg_N
7921                        ("\to be overridden by protected procedure or " &
7922                         "entry (RM 9.4(11.9/2))", T);
7923
7924                   --  Some other kind of overriding failure
7925
7926                   else
7927                      Error_Msg_NE
7928                        ("interface subprogram & must be overridden",
7929                         T, Subp);
7930                   end if;
7931                end if;
7932
7933             else
7934                Error_Msg_Node_2 := T;
7935                Error_Msg_N
7936                  ("abstract subprogram& not allowed for type&", Subp);
7937
7938                --  Also post unconditional warning on the type (unconditional
7939                --  so that if there are more than one of these cases, we get
7940                --  them all, and not just the first one).
7941
7942                Error_Msg_Node_2 := Subp;
7943                Error_Msg_N
7944                  ("nonabstract type& has abstract subprogram&!", T);
7945             end if;
7946          end if;
7947
7948          <<Next_Subp>>
7949             Next_Elmt (Elmt);
7950       end loop;
7951    end Check_Abstract_Overriding;
7952
7953    ------------------------------------------------
7954    -- Check_Access_Discriminant_Requires_Limited --
7955    ------------------------------------------------
7956
7957    procedure Check_Access_Discriminant_Requires_Limited
7958      (D   : Node_Id;
7959       Loc : Node_Id)
7960    is
7961    begin
7962       --  A discriminant_specification for an access discriminant shall appear
7963       --  only in the declaration for a task or protected type, or for a type
7964       --  with the reserved word 'limited' in its definition or in one of its
7965       --  ancestors. (RM 3.7(10))
7966
7967       if Nkind (Discriminant_Type (D)) = N_Access_Definition
7968         and then not Is_Concurrent_Type (Current_Scope)
7969         and then not Is_Concurrent_Record_Type (Current_Scope)
7970         and then not Is_Limited_Record (Current_Scope)
7971         and then Ekind (Current_Scope) /= E_Limited_Private_Type
7972       then
7973          Error_Msg_N
7974            ("access discriminants allowed only for limited types", Loc);
7975       end if;
7976    end Check_Access_Discriminant_Requires_Limited;
7977
7978    -----------------------------------
7979    -- Check_Aliased_Component_Types --
7980    -----------------------------------
7981
7982    procedure Check_Aliased_Component_Types (T : Entity_Id) is
7983       C : Entity_Id;
7984
7985    begin
7986       --  ??? Also need to check components of record extensions, but not
7987       --  components of protected types (which are always limited).
7988
7989       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
7990       --  types to be unconstrained. This is safe because it is illegal to
7991       --  create access subtypes to such types with explicit discriminant
7992       --  constraints.
7993
7994       if not Is_Limited_Type (T) then
7995          if Ekind (T) = E_Record_Type then
7996             C := First_Component (T);
7997             while Present (C) loop
7998                if Is_Aliased (C)
7999                  and then Has_Discriminants (Etype (C))
8000                  and then not Is_Constrained (Etype (C))
8001                  and then not In_Instance_Body
8002                  and then Ada_Version < Ada_05
8003                then
8004                   Error_Msg_N
8005                     ("aliased component must be constrained (RM 3.6(11))",
8006                       C);
8007                end if;
8008
8009                Next_Component (C);
8010             end loop;
8011
8012          elsif Ekind (T) = E_Array_Type then
8013             if Has_Aliased_Components (T)
8014               and then Has_Discriminants (Component_Type (T))
8015               and then not Is_Constrained (Component_Type (T))
8016               and then not In_Instance_Body
8017               and then Ada_Version < Ada_05
8018             then
8019                Error_Msg_N
8020                  ("aliased component type must be constrained (RM 3.6(11))",
8021                     T);
8022             end if;
8023          end if;
8024       end if;
8025    end Check_Aliased_Component_Types;
8026
8027    ----------------------
8028    -- Check_Completion --
8029    ----------------------
8030
8031    procedure Check_Completion (Body_Id : Node_Id := Empty) is
8032       E : Entity_Id;
8033
8034       procedure Post_Error;
8035       --  Post error message for lack of completion for entity E
8036
8037       ----------------
8038       -- Post_Error --
8039       ----------------
8040
8041       procedure Post_Error is
8042       begin
8043          if not Comes_From_Source (E) then
8044
8045             if Ekind (E) = E_Task_Type
8046               or else Ekind (E) = E_Protected_Type
8047             then
8048                --  It may be an anonymous protected type created for a
8049                --  single variable. Post error on variable, if present.
8050
8051                declare
8052                   Var : Entity_Id;
8053
8054                begin
8055                   Var := First_Entity (Current_Scope);
8056                   while Present (Var) loop
8057                      exit when Etype (Var) = E
8058                        and then Comes_From_Source (Var);
8059
8060                      Next_Entity (Var);
8061                   end loop;
8062
8063                   if Present (Var) then
8064                      E := Var;
8065                   end if;
8066                end;
8067             end if;
8068          end if;
8069
8070          --  If a generated entity has no completion, then either previous
8071          --  semantic errors have disabled the expansion phase, or else we had
8072          --  missing subunits, or else we are compiling without expansion,
8073          --  or else something is very wrong.
8074
8075          if not Comes_From_Source (E) then
8076             pragma Assert
8077               (Serious_Errors_Detected > 0
8078                 or else Configurable_Run_Time_Violations > 0
8079                 or else Subunits_Missing
8080                 or else not Expander_Active);
8081             return;
8082
8083          --  Here for source entity
8084
8085          else
8086             --  Here if no body to post the error message, so we post the error
8087             --  on the declaration that has no completion. This is not really
8088             --  the right place to post it, think about this later ???
8089
8090             if No (Body_Id) then
8091                if Is_Type (E) then
8092                   Error_Msg_NE
8093                     ("missing full declaration for }", Parent (E), E);
8094                else
8095                   Error_Msg_NE
8096                     ("missing body for &", Parent (E), E);
8097                end if;
8098
8099             --  Package body has no completion for a declaration that appears
8100             --  in the corresponding spec. Post error on the body, with a
8101             --  reference to the non-completed declaration.
8102
8103             else
8104                Error_Msg_Sloc := Sloc (E);
8105
8106                if Is_Type (E) then
8107                   Error_Msg_NE
8108                     ("missing full declaration for }!", Body_Id, E);
8109
8110                elsif Is_Overloadable (E)
8111                  and then Current_Entity_In_Scope (E) /= E
8112                then
8113                   --  It may be that the completion is mistyped and appears
8114                   --  as a  distinct overloading of the entity.
8115
8116                   declare
8117                      Candidate : constant Entity_Id :=
8118                                    Current_Entity_In_Scope (E);
8119                      Decl      : constant Node_Id :=
8120                                    Unit_Declaration_Node (Candidate);
8121
8122                   begin
8123                      if Is_Overloadable (Candidate)
8124                        and then Ekind (Candidate) = Ekind (E)
8125                        and then Nkind (Decl) = N_Subprogram_Body
8126                        and then Acts_As_Spec (Decl)
8127                      then
8128                         Check_Type_Conformant (Candidate, E);
8129
8130                      else
8131                         Error_Msg_NE ("missing body for & declared#!",
8132                            Body_Id, E);
8133                      end if;
8134                   end;
8135                else
8136                   Error_Msg_NE ("missing body for & declared#!",
8137                      Body_Id, E);
8138                end if;
8139             end if;
8140          end if;
8141       end Post_Error;
8142
8143    --  Start processing for Check_Completion
8144
8145    begin
8146       E := First_Entity (Current_Scope);
8147       while Present (E) loop
8148          if Is_Intrinsic_Subprogram (E) then
8149             null;
8150
8151          --  The following situation requires special handling: a child
8152          --  unit that appears in the context clause of the body of its
8153          --  parent:
8154
8155          --    procedure Parent.Child (...);
8156
8157          --    with Parent.Child;
8158          --    package body Parent is
8159
8160          --  Here Parent.Child appears as a local entity, but should not
8161          --  be flagged as requiring completion, because it is a
8162          --  compilation unit.
8163
8164          --  Ignore missing completion for a subprogram that does not come from
8165          --  source (including the _Call primitive operation of RAS types,
8166          --  which has to have the flag Comes_From_Source for other purposes):
8167          --  we assume that the expander will provide the missing completion.
8168
8169          elsif     Ekind (E) = E_Function
8170            or else Ekind (E) = E_Procedure
8171            or else Ekind (E) = E_Generic_Function
8172            or else Ekind (E) = E_Generic_Procedure
8173          then
8174             if not Has_Completion (E)
8175               and then not (Is_Subprogram (E)
8176                             and then Is_Abstract_Subprogram (E))
8177               and then not (Is_Subprogram (E)
8178                               and then
8179                             (not Comes_From_Source (E)
8180                               or else Chars (E) = Name_uCall))
8181               and then Nkind (Parent (Unit_Declaration_Node (E))) /=
8182                                                        N_Compilation_Unit
8183               and then Chars (E) /= Name_uSize
8184             then
8185                Post_Error;
8186             end if;
8187
8188          elsif Is_Entry (E) then
8189             if not Has_Completion (E) and then
8190               (Ekind (Scope (E)) = E_Protected_Object
8191                 or else Ekind (Scope (E)) = E_Protected_Type)
8192             then
8193                Post_Error;
8194             end if;
8195
8196          elsif Is_Package_Or_Generic_Package (E) then
8197             if Unit_Requires_Body (E) then
8198                if not Has_Completion (E)
8199                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
8200                                                        N_Compilation_Unit
8201                then
8202                   Post_Error;
8203                end if;
8204
8205             elsif not Is_Child_Unit (E) then
8206                May_Need_Implicit_Body (E);
8207             end if;
8208
8209          elsif Ekind (E) = E_Incomplete_Type
8210            and then No (Underlying_Type (E))
8211          then
8212             Post_Error;
8213
8214          elsif (Ekind (E) = E_Task_Type or else
8215                 Ekind (E) = E_Protected_Type)
8216            and then not Has_Completion (E)
8217          then
8218             Post_Error;
8219
8220          --  A single task declared in the current scope is a constant, verify
8221          --  that the body of its anonymous type is in the same scope. If the
8222          --  task is defined elsewhere, this may be a renaming declaration for
8223          --  which no completion is needed.
8224
8225          elsif Ekind (E) = E_Constant
8226            and then Ekind (Etype (E)) = E_Task_Type
8227            and then not Has_Completion (Etype (E))
8228            and then Scope (Etype (E)) = Current_Scope
8229          then
8230             Post_Error;
8231
8232          elsif Ekind (E) = E_Protected_Object
8233            and then not Has_Completion (Etype (E))
8234          then
8235             Post_Error;
8236
8237          elsif Ekind (E) = E_Record_Type then
8238             if Is_Tagged_Type (E) then
8239                Check_Abstract_Overriding (E);
8240                Check_Conventions (E);
8241             end if;
8242
8243             Check_Aliased_Component_Types (E);
8244
8245          elsif Ekind (E) = E_Array_Type then
8246             Check_Aliased_Component_Types (E);
8247
8248          end if;
8249
8250          Next_Entity (E);
8251       end loop;
8252    end Check_Completion;
8253
8254    ----------------------------
8255    -- Check_Delta_Expression --
8256    ----------------------------
8257
8258    procedure Check_Delta_Expression (E : Node_Id) is
8259    begin
8260       if not (Is_Real_Type (Etype (E))) then
8261          Wrong_Type (E, Any_Real);
8262
8263       elsif not Is_OK_Static_Expression (E) then
8264          Flag_Non_Static_Expr
8265            ("non-static expression used for delta value!", E);
8266
8267       elsif not UR_Is_Positive (Expr_Value_R (E)) then
8268          Error_Msg_N ("delta expression must be positive", E);
8269
8270       else
8271          return;
8272       end if;
8273
8274       --  If any of above errors occurred, then replace the incorrect
8275       --  expression by the real 0.1, which should prevent further errors.
8276
8277       Rewrite (E,
8278         Make_Real_Literal (Sloc (E), Ureal_Tenth));
8279       Analyze_And_Resolve (E, Standard_Float);
8280    end Check_Delta_Expression;
8281
8282    -----------------------------
8283    -- Check_Digits_Expression --
8284    -----------------------------
8285
8286    procedure Check_Digits_Expression (E : Node_Id) is
8287    begin
8288       if not (Is_Integer_Type (Etype (E))) then
8289          Wrong_Type (E, Any_Integer);
8290
8291       elsif not Is_OK_Static_Expression (E) then
8292          Flag_Non_Static_Expr
8293            ("non-static expression used for digits value!", E);
8294
8295       elsif Expr_Value (E) <= 0 then
8296          Error_Msg_N ("digits value must be greater than zero", E);
8297
8298       else
8299          return;
8300       end if;
8301
8302       --  If any of above errors occurred, then replace the incorrect
8303       --  expression by the integer 1, which should prevent further errors.
8304
8305       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
8306       Analyze_And_Resolve (E, Standard_Integer);
8307
8308    end Check_Digits_Expression;
8309
8310    --------------------------
8311    -- Check_Initialization --
8312    --------------------------
8313
8314    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
8315    begin
8316       if Is_Limited_Type (T)
8317         and then not In_Instance
8318         and then not In_Inlined_Body
8319       then
8320          if not OK_For_Limited_Init (Exp) then
8321
8322             --  In GNAT mode, this is just a warning, to allow it to be evilly
8323             --  turned off. Otherwise it is a real error.
8324
8325             if GNAT_Mode then
8326                Error_Msg_N
8327                  ("?cannot initialize entities of limited type!", Exp);
8328
8329             elsif Ada_Version < Ada_05 then
8330                Error_Msg_N
8331                  ("cannot initialize entities of limited type", Exp);
8332                Explain_Limited_Type (T, Exp);
8333
8334             else
8335                --  Specialize error message according to kind of illegal
8336                --  initial expression.
8337
8338                if Nkind (Exp) = N_Type_Conversion
8339                  and then Nkind (Expression (Exp)) = N_Function_Call
8340                then
8341                   Error_Msg_N
8342                     ("illegal context for call"
8343                       & " to function with limited result", Exp);
8344
8345                else
8346                   Error_Msg_N
8347                     ("initialization of limited object requires agggregate "
8348                       & "or function call",  Exp);
8349                end if;
8350             end if;
8351          end if;
8352       end if;
8353    end Check_Initialization;
8354
8355    ------------------------------------
8356    -- Check_Or_Process_Discriminants --
8357    ------------------------------------
8358
8359    --  If an incomplete or private type declaration was already given for the
8360    --  type, the discriminants may have already been processed if they were
8361    --  present on the incomplete declaration. In this case a full conformance
8362    --  check is performed otherwise just process them.
8363
8364    procedure Check_Or_Process_Discriminants
8365      (N    : Node_Id;
8366       T    : Entity_Id;
8367       Prev : Entity_Id := Empty)
8368    is
8369    begin
8370       if Has_Discriminants (T) then
8371
8372          --  Make the discriminants visible to component declarations
8373
8374          declare
8375             D    : Entity_Id;
8376             Prev : Entity_Id;
8377
8378          begin
8379             D := First_Discriminant (T);
8380             while Present (D) loop
8381                Prev := Current_Entity (D);
8382                Set_Current_Entity (D);
8383                Set_Is_Immediately_Visible (D);
8384                Set_Homonym (D, Prev);
8385
8386                --  Ada 2005 (AI-230): Access discriminant allowed in
8387                --  non-limited record types.
8388
8389                if Ada_Version < Ada_05 then
8390
8391                   --  This restriction gets applied to the full type here. It
8392                   --  has already been applied earlier to the partial view.
8393
8394                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
8395                end if;
8396
8397                Next_Discriminant (D);
8398             end loop;
8399          end;
8400
8401       elsif Present (Discriminant_Specifications (N)) then
8402          Process_Discriminants (N, Prev);
8403       end if;
8404    end Check_Or_Process_Discriminants;
8405
8406    ----------------------
8407    -- Check_Real_Bound --
8408    ----------------------
8409
8410    procedure Check_Real_Bound (Bound : Node_Id) is
8411    begin
8412       if not Is_Real_Type (Etype (Bound)) then
8413          Error_Msg_N
8414            ("bound in real type definition must be of real type", Bound);
8415
8416       elsif not Is_OK_Static_Expression (Bound) then
8417          Flag_Non_Static_Expr
8418            ("non-static expression used for real type bound!", Bound);
8419
8420       else
8421          return;
8422       end if;
8423
8424       Rewrite
8425         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
8426       Analyze (Bound);
8427       Resolve (Bound, Standard_Float);
8428    end Check_Real_Bound;
8429
8430    ------------------------------
8431    -- Complete_Private_Subtype --
8432    ------------------------------
8433
8434    procedure Complete_Private_Subtype
8435      (Priv        : Entity_Id;
8436       Full        : Entity_Id;
8437       Full_Base   : Entity_Id;
8438       Related_Nod : Node_Id)
8439    is
8440       Save_Next_Entity : Entity_Id;
8441       Save_Homonym     : Entity_Id;
8442
8443    begin
8444       --  Set semantic attributes for (implicit) private subtype completion.
8445       --  If the full type has no discriminants, then it is a copy of the full
8446       --  view of the base. Otherwise, it is a subtype of the base with a
8447       --  possible discriminant constraint. Save and restore the original
8448       --  Next_Entity field of full to ensure that the calls to Copy_Node
8449       --  do not corrupt the entity chain.
8450
8451       --  Note that the type of the full view is the same entity as the type of
8452       --  the partial view. In this fashion, the subtype has access to the
8453       --  correct view of the parent.
8454
8455       Save_Next_Entity := Next_Entity (Full);
8456       Save_Homonym     := Homonym (Priv);
8457
8458       case Ekind (Full_Base) is
8459          when E_Record_Type    |
8460               E_Record_Subtype |
8461               Class_Wide_Kind  |
8462               Private_Kind     |
8463               Task_Kind        |
8464               Protected_Kind   =>
8465             Copy_Node (Priv, Full);
8466
8467             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
8468             Set_First_Entity       (Full, First_Entity (Full_Base));
8469             Set_Last_Entity        (Full, Last_Entity (Full_Base));
8470
8471          when others =>
8472             Copy_Node (Full_Base, Full);
8473             Set_Chars          (Full, Chars (Priv));
8474             Conditional_Delay  (Full, Priv);
8475             Set_Sloc           (Full, Sloc (Priv));
8476       end case;
8477
8478       Set_Next_Entity (Full, Save_Next_Entity);
8479       Set_Homonym     (Full, Save_Homonym);
8480       Set_Associated_Node_For_Itype (Full, Related_Nod);
8481
8482       --  Set common attributes for all subtypes
8483
8484       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
8485
8486       --  The Etype of the full view is inconsistent. Gigi needs to see the
8487       --  structural full view,  which is what the current scheme gives:
8488       --  the Etype of the full view is the etype of the full base. However,
8489       --  if the full base is a derived type, the full view then looks like
8490       --  a subtype of the parent, not a subtype of the full base. If instead
8491       --  we write:
8492
8493       --       Set_Etype (Full, Full_Base);
8494
8495       --  then we get inconsistencies in the front-end (confusion between
8496       --  views). Several outstanding bugs are related to this ???
8497
8498       Set_Is_First_Subtype (Full, False);
8499       Set_Scope            (Full, Scope (Priv));
8500       Set_Size_Info        (Full, Full_Base);
8501       Set_RM_Size          (Full, RM_Size (Full_Base));
8502       Set_Is_Itype         (Full);
8503
8504       --  A subtype of a private-type-without-discriminants, whose full-view
8505       --  has discriminants with default expressions, is not constrained!
8506
8507       if not Has_Discriminants (Priv) then
8508          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
8509
8510          if Has_Discriminants (Full_Base) then
8511             Set_Discriminant_Constraint
8512               (Full, Discriminant_Constraint (Full_Base));
8513
8514             --  The partial view may have been indefinite, the full view
8515             --  might not be.
8516
8517             Set_Has_Unknown_Discriminants
8518               (Full, Has_Unknown_Discriminants (Full_Base));
8519          end if;
8520       end if;
8521
8522       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
8523       Set_Depends_On_Private (Full, Has_Private_Component (Full));
8524
8525       --  Freeze the private subtype entity if its parent is delayed, and not
8526       --  already frozen. We skip this processing if the type is an anonymous
8527       --  subtype of a record component, or is the corresponding record of a
8528       --  protected type, since ???
8529
8530       if not Is_Type (Scope (Full)) then
8531          Set_Has_Delayed_Freeze (Full,
8532            Has_Delayed_Freeze (Full_Base)
8533              and then (not Is_Frozen (Full_Base)));
8534       end if;
8535
8536       Set_Freeze_Node (Full, Empty);
8537       Set_Is_Frozen (Full, False);
8538       Set_Full_View (Priv, Full);
8539
8540       if Has_Discriminants (Full) then
8541          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
8542          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
8543
8544          if Has_Unknown_Discriminants (Full) then
8545             Set_Discriminant_Constraint (Full, No_Elist);
8546          end if;
8547       end if;
8548
8549       if Ekind (Full_Base) = E_Record_Type
8550         and then Has_Discriminants (Full_Base)
8551         and then Has_Discriminants (Priv) -- might not, if errors
8552         and then not Has_Unknown_Discriminants (Priv)
8553         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
8554       then
8555          Create_Constrained_Components
8556            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
8557
8558       --  If the full base is itself derived from private, build a congruent
8559       --  subtype of its underlying type, for use by the back end. For a
8560       --  constrained record component, the declaration cannot be placed on
8561       --  the component list, but it must nevertheless be built an analyzed, to
8562       --  supply enough information for Gigi to compute the size of component.
8563
8564       elsif Ekind (Full_Base) in Private_Kind
8565         and then Is_Derived_Type (Full_Base)
8566         and then Has_Discriminants (Full_Base)
8567         and then (Ekind (Current_Scope) /= E_Record_Subtype)
8568       then
8569          if not Is_Itype (Priv)
8570            and then
8571              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
8572          then
8573             Build_Underlying_Full_View
8574               (Parent (Priv), Full, Etype (Full_Base));
8575
8576          elsif Nkind (Related_Nod) = N_Component_Declaration then
8577             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
8578          end if;
8579
8580       elsif Is_Record_Type (Full_Base) then
8581
8582          --  Show Full is simply a renaming of Full_Base
8583
8584          Set_Cloned_Subtype (Full, Full_Base);
8585       end if;
8586
8587       --  It is unsafe to share to bounds of a scalar type, because the Itype
8588       --  is elaborated on demand, and if a bound is non-static then different
8589       --  orders of elaboration in different units will lead to different
8590       --  external symbols.
8591
8592       if Is_Scalar_Type (Full_Base) then
8593          Set_Scalar_Range (Full,
8594            Make_Range (Sloc (Related_Nod),
8595              Low_Bound  =>
8596                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
8597              High_Bound =>
8598                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
8599
8600          --  This completion inherits the bounds of the full parent, but if
8601          --  the parent is an unconstrained floating point type, so is the
8602          --  completion.
8603
8604          if Is_Floating_Point_Type (Full_Base) then
8605             Set_Includes_Infinities
8606              (Scalar_Range (Full), Has_Infinities (Full_Base));
8607          end if;
8608       end if;
8609
8610       --  ??? It seems that a lot of fields are missing that should be copied
8611       --  from Full_Base to Full. Here are some that are introduced in a
8612       --  non-disruptive way but a cleanup is necessary.
8613
8614       if Is_Tagged_Type (Full_Base) then
8615          Set_Is_Tagged_Type (Full);
8616          Set_Primitive_Operations (Full, Primitive_Operations (Full_Base));
8617          Set_Class_Wide_Type      (Full, Class_Wide_Type (Full_Base));
8618
8619       --  If this is a subtype of a protected or task type, constrain its
8620       --  corresponding record, unless this is a subtype without constraints,
8621       --  i.e. a simple renaming as with an actual subtype in an instance.
8622
8623       elsif Is_Concurrent_Type (Full_Base) then
8624          if Has_Discriminants (Full)
8625            and then Present (Corresponding_Record_Type (Full_Base))
8626            and then
8627              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
8628          then
8629             Set_Corresponding_Record_Type (Full,
8630               Constrain_Corresponding_Record
8631                 (Full, Corresponding_Record_Type (Full_Base),
8632                   Related_Nod, Full_Base));
8633
8634          else
8635             Set_Corresponding_Record_Type (Full,
8636               Corresponding_Record_Type (Full_Base));
8637          end if;
8638       end if;
8639    end Complete_Private_Subtype;
8640
8641    ----------------------------
8642    -- Constant_Redeclaration --
8643    ----------------------------
8644
8645    procedure Constant_Redeclaration
8646      (Id : Entity_Id;
8647       N  : Node_Id;
8648       T  : out Entity_Id)
8649    is
8650       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
8651       Obj_Def : constant Node_Id := Object_Definition (N);
8652       New_T   : Entity_Id;
8653
8654       procedure Check_Possible_Deferred_Completion
8655         (Prev_Id      : Entity_Id;
8656          Prev_Obj_Def : Node_Id;
8657          Curr_Obj_Def : Node_Id);
8658       --  Determine whether the two object definitions describe the partial
8659       --  and the full view of a constrained deferred constant. Generate
8660       --  a subtype for the full view and verify that it statically matches
8661       --  the subtype of the partial view.
8662
8663       procedure Check_Recursive_Declaration (Typ : Entity_Id);
8664       --  If deferred constant is an access type initialized with an allocator,
8665       --  check whether there is an illegal recursion in the definition,
8666       --  through a default value of some record subcomponent. This is normally
8667       --  detected when generating init procs, but requires this additional
8668       --  mechanism when expansion is disabled.
8669
8670       ----------------------------------------
8671       -- Check_Possible_Deferred_Completion --
8672       ----------------------------------------
8673
8674       procedure Check_Possible_Deferred_Completion
8675         (Prev_Id      : Entity_Id;
8676          Prev_Obj_Def : Node_Id;
8677          Curr_Obj_Def : Node_Id)
8678       is
8679       begin
8680          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
8681            and then Present (Constraint (Prev_Obj_Def))
8682            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
8683            and then Present (Constraint (Curr_Obj_Def))
8684          then
8685             declare
8686                Loc    : constant Source_Ptr := Sloc (N);
8687                Def_Id : constant Entity_Id :=
8688                           Make_Defining_Identifier (Loc,
8689                             New_Internal_Name ('S'));
8690                Decl   : constant Node_Id :=
8691                           Make_Subtype_Declaration (Loc,
8692                             Defining_Identifier =>
8693                               Def_Id,
8694                             Subtype_Indication =>
8695                               Relocate_Node (Curr_Obj_Def));
8696
8697             begin
8698                Insert_Before_And_Analyze (N, Decl);
8699                Set_Etype (Id, Def_Id);
8700
8701                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
8702                   Error_Msg_Sloc := Sloc (Prev_Id);
8703                   Error_Msg_N ("subtype does not statically match deferred " &
8704                                "declaration#", N);
8705                end if;
8706             end;
8707          end if;
8708       end Check_Possible_Deferred_Completion;
8709
8710       ---------------------------------
8711       -- Check_Recursive_Declaration --
8712       ---------------------------------
8713
8714       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
8715          Comp : Entity_Id;
8716
8717       begin
8718          if Is_Record_Type (Typ) then
8719             Comp := First_Component (Typ);
8720             while Present (Comp) loop
8721                if Comes_From_Source (Comp) then
8722                   if Present (Expression (Parent (Comp)))
8723                     and then Is_Entity_Name (Expression (Parent (Comp)))
8724                     and then Entity (Expression (Parent (Comp))) = Prev
8725                   then
8726                      Error_Msg_Sloc := Sloc (Parent (Comp));
8727                      Error_Msg_NE
8728                        ("illegal circularity with declaration for&#",
8729                          N, Comp);
8730                      return;
8731
8732                   elsif Is_Record_Type (Etype (Comp)) then
8733                      Check_Recursive_Declaration (Etype (Comp));
8734                   end if;
8735                end if;
8736
8737                Next_Component (Comp);
8738             end loop;
8739          end if;
8740       end Check_Recursive_Declaration;
8741
8742    --  Start of processing for Constant_Redeclaration
8743
8744    begin
8745       if Nkind (Parent (Prev)) = N_Object_Declaration then
8746          if Nkind (Object_Definition
8747                      (Parent (Prev))) = N_Subtype_Indication
8748          then
8749             --  Find type of new declaration. The constraints of the two
8750             --  views must match statically, but there is no point in
8751             --  creating an itype for the full view.
8752
8753             if Nkind (Obj_Def) = N_Subtype_Indication then
8754                Find_Type (Subtype_Mark (Obj_Def));
8755                New_T := Entity (Subtype_Mark (Obj_Def));
8756
8757             else
8758                Find_Type (Obj_Def);
8759                New_T := Entity (Obj_Def);
8760             end if;
8761
8762             T := Etype (Prev);
8763
8764          else
8765             --  The full view may impose a constraint, even if the partial
8766             --  view does not, so construct the subtype.
8767
8768             New_T := Find_Type_Of_Object (Obj_Def, N);
8769             T     := New_T;
8770          end if;
8771
8772       else
8773          --  Current declaration is illegal, diagnosed below in Enter_Name
8774
8775          T := Empty;
8776          New_T := Any_Type;
8777       end if;
8778
8779       --  If previous full declaration exists, or if a homograph is present,
8780       --  let Enter_Name handle it, either with an error, or with the removal
8781       --  of an overridden implicit subprogram.
8782
8783       if Ekind (Prev) /= E_Constant
8784         or else Present (Expression (Parent (Prev)))
8785         or else Present (Full_View (Prev))
8786       then
8787          Enter_Name (Id);
8788
8789       --  Verify that types of both declarations match, or else that both types
8790       --  are anonymous access types whose designated subtypes statically match
8791       --  (as allowed in Ada 2005 by AI-385).
8792
8793       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
8794         and then
8795           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
8796              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
8797              or else not Subtypes_Statically_Match
8798                            (Designated_Type (Etype (Prev)),
8799                             Designated_Type (Etype (New_T))))
8800       then
8801          Error_Msg_Sloc := Sloc (Prev);
8802          Error_Msg_N ("type does not match declaration#", N);
8803          Set_Full_View (Prev, Id);
8804          Set_Etype (Id, Any_Type);
8805
8806       --  If so, process the full constant declaration
8807
8808       else
8809          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
8810          --  the deferred declaration is constrained, then the subtype defined
8811          --  by the subtype_indication in the full declaration shall match it
8812          --  statically.
8813
8814          Check_Possible_Deferred_Completion
8815            (Prev_Id      => Prev,
8816             Prev_Obj_Def => Object_Definition (Parent (Prev)),
8817             Curr_Obj_Def => Obj_Def);
8818
8819          Set_Full_View (Prev, Id);
8820          Set_Is_Public (Id, Is_Public (Prev));
8821          Set_Is_Internal (Id);
8822          Append_Entity (Id, Current_Scope);
8823
8824          --  Check ALIASED present if present before (RM 7.4(7))
8825
8826          if Is_Aliased (Prev)
8827            and then not Aliased_Present (N)
8828          then
8829             Error_Msg_Sloc := Sloc (Prev);
8830             Error_Msg_N ("ALIASED required (see declaration#)", N);
8831          end if;
8832
8833          --  Allow incomplete declaration of tags (used to handle forward
8834          --  references to tags). The check on Ada_Tags avoids cicularities
8835          --  when rebuilding the compiler.
8836
8837          if RTU_Loaded (Ada_Tags)
8838            and then T = RTE (RE_Tag)
8839          then
8840             null;
8841
8842          --  Check that placement is in private part and that the incomplete
8843          --  declaration appeared in the visible part.
8844
8845          elsif Ekind (Current_Scope) = E_Package
8846            and then not In_Private_Part (Current_Scope)
8847          then
8848             Error_Msg_Sloc := Sloc (Prev);
8849             Error_Msg_N ("full constant for declaration#"
8850                          & " must be in private part", N);
8851
8852          elsif Ekind (Current_Scope) = E_Package
8853            and then List_Containing (Parent (Prev))
8854            /= Visible_Declarations
8855              (Specification (Unit_Declaration_Node (Current_Scope)))
8856          then
8857             Error_Msg_N
8858               ("deferred constant must be declared in visible part",
8859                  Parent (Prev));
8860          end if;
8861
8862          if Is_Access_Type (T)
8863            and then Nkind (Expression (N)) = N_Allocator
8864          then
8865             Check_Recursive_Declaration (Designated_Type (T));
8866          end if;
8867       end if;
8868    end Constant_Redeclaration;
8869
8870    ----------------------
8871    -- Constrain_Access --
8872    ----------------------
8873
8874    procedure Constrain_Access
8875      (Def_Id      : in out Entity_Id;
8876       S           : Node_Id;
8877       Related_Nod : Node_Id)
8878    is
8879       T             : constant Entity_Id := Entity (Subtype_Mark (S));
8880       Desig_Type    : constant Entity_Id := Designated_Type (T);
8881       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
8882       Constraint_OK : Boolean := True;
8883
8884       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
8885       --  Simple predicate to test for defaulted discriminants
8886       --  Shouldn't this be in sem_util???
8887
8888       ---------------------------------
8889       -- Has_Defaulted_Discriminants --
8890       ---------------------------------
8891
8892       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
8893       begin
8894          return Has_Discriminants (Typ)
8895           and then Present (First_Discriminant (Typ))
8896           and then Present
8897             (Discriminant_Default_Value (First_Discriminant (Typ)));
8898       end Has_Defaulted_Discriminants;
8899
8900    --  Start of processing for Constrain_Access
8901
8902    begin
8903       if Is_Array_Type (Desig_Type) then
8904          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
8905
8906       elsif (Is_Record_Type (Desig_Type)
8907               or else Is_Incomplete_Or_Private_Type (Desig_Type))
8908         and then not Is_Constrained (Desig_Type)
8909       then
8910          --  ??? The following code is a temporary kludge to ignore a
8911          --  discriminant constraint on access type if it is constraining
8912          --  the current record. Avoid creating the implicit subtype of the
8913          --  record we are currently compiling since right now, we cannot
8914          --  handle these. For now, just return the access type itself.
8915
8916          if Desig_Type = Current_Scope
8917            and then No (Def_Id)
8918          then
8919             Set_Ekind (Desig_Subtype, E_Record_Subtype);
8920             Def_Id := Entity (Subtype_Mark (S));
8921
8922             --  This call added to ensure that the constraint is analyzed
8923             --  (needed for a B test). Note that we still return early from
8924             --  this procedure to avoid recursive processing. ???
8925
8926             Constrain_Discriminated_Type
8927               (Desig_Subtype, S, Related_Nod, For_Access => True);
8928             return;
8929          end if;
8930
8931          if Ekind (T) = E_General_Access_Type
8932            and then Has_Private_Declaration (Desig_Type)
8933            and then In_Open_Scopes (Scope (Desig_Type))
8934          then
8935             --  Enforce rule that the constraint is illegal if there is
8936             --  an unconstrained view of the designated type. This means
8937             --  that the partial view (either a private type declaration or
8938             --  a derivation from a private type) has no discriminants.
8939             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
8940             --  by ACATS B371001).
8941
8942             --  Rule updated for Ada 2005: the private type is said to have
8943             --  a constrained partial view, given that objects of the type
8944             --  can be declared.
8945
8946             declare
8947                Pack  : constant Node_Id :=
8948                          Unit_Declaration_Node (Scope (Desig_Type));
8949                Decls : List_Id;
8950                Decl  : Node_Id;
8951
8952             begin
8953                if Nkind (Pack) = N_Package_Declaration then
8954                   Decls := Visible_Declarations (Specification (Pack));
8955                   Decl := First (Decls);
8956                   while Present (Decl) loop
8957                      if (Nkind (Decl) = N_Private_Type_Declaration
8958                           and then
8959                             Chars (Defining_Identifier (Decl)) =
8960                                                      Chars (Desig_Type))
8961
8962                        or else
8963                         (Nkind (Decl) = N_Full_Type_Declaration
8964                           and then
8965                             Chars (Defining_Identifier (Decl)) =
8966                                                      Chars (Desig_Type)
8967                           and then Is_Derived_Type (Desig_Type)
8968                           and then
8969                             Has_Private_Declaration (Etype (Desig_Type)))
8970                      then
8971                         if No (Discriminant_Specifications (Decl)) then
8972                            Error_Msg_N
8973                             ("cannot constrain general access type if " &
8974                                "designated type has constrained partial view",
8975                                 S);
8976                         end if;
8977
8978                         exit;
8979                      end if;
8980
8981                      Next (Decl);
8982                   end loop;
8983                end if;
8984             end;
8985          end if;
8986
8987          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
8988            For_Access => True);
8989
8990       elsif (Is_Task_Type (Desig_Type)
8991               or else Is_Protected_Type (Desig_Type))
8992         and then not Is_Constrained (Desig_Type)
8993       then
8994          Constrain_Concurrent
8995            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
8996
8997       else
8998          Error_Msg_N ("invalid constraint on access type", S);
8999          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
9000          Constraint_OK := False;
9001       end if;
9002
9003       if No (Def_Id) then
9004          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
9005       else
9006          Set_Ekind (Def_Id, E_Access_Subtype);
9007       end if;
9008
9009       if Constraint_OK then
9010          Set_Etype (Def_Id, Base_Type (T));
9011
9012          if Is_Private_Type (Desig_Type) then
9013             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
9014          end if;
9015       else
9016          Set_Etype (Def_Id, Any_Type);
9017       end if;
9018
9019       Set_Size_Info                (Def_Id, T);
9020       Set_Is_Constrained           (Def_Id, Constraint_OK);
9021       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
9022       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
9023       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
9024
9025       Conditional_Delay (Def_Id, T);
9026
9027       --  AI-363 : Subtypes of general access types whose designated types have
9028       --  default discriminants are disallowed. In instances, the rule has to
9029       --  be checked against the actual, of which T is the subtype. In a
9030       --  generic body, the rule is checked assuming that the actual type has
9031       --  defaulted discriminants.
9032
9033       if Ada_Version >= Ada_05 or else Warn_On_Ada_2005_Compatibility then
9034          if Ekind (Base_Type (T)) = E_General_Access_Type
9035            and then Has_Defaulted_Discriminants (Desig_Type)
9036          then
9037             if Ada_Version < Ada_05 then
9038                Error_Msg_N
9039                  ("access subtype of general access type would not " &
9040                   "be allowed in Ada 2005?", S);
9041             else
9042                Error_Msg_N
9043                  ("access subype of general access type not allowed", S);
9044             end if;
9045
9046             Error_Msg_N ("\discriminants have defaults", S);
9047
9048          elsif Is_Access_Type (T)
9049            and then Is_Generic_Type (Desig_Type)
9050            and then Has_Discriminants (Desig_Type)
9051            and then In_Package_Body (Current_Scope)
9052          then
9053             if Ada_Version < Ada_05 then
9054                Error_Msg_N
9055                  ("access subtype would not be allowed in generic body " &
9056                   "in Ada 2005?", S);
9057             else
9058                Error_Msg_N
9059                  ("access subtype not allowed in generic body", S);
9060             end if;
9061
9062             Error_Msg_N
9063               ("\designated type is a discriminated formal", S);
9064          end if;
9065       end if;
9066    end Constrain_Access;
9067
9068    ---------------------
9069    -- Constrain_Array --
9070    ---------------------
9071
9072    procedure Constrain_Array
9073      (Def_Id      : in out Entity_Id;
9074       SI          : Node_Id;
9075       Related_Nod : Node_Id;
9076       Related_Id  : Entity_Id;
9077       Suffix      : Character)
9078    is
9079       C                     : constant Node_Id := Constraint (SI);
9080       Number_Of_Constraints : Nat := 0;
9081       Index                 : Node_Id;
9082       S, T                  : Entity_Id;
9083       Constraint_OK         : Boolean := True;
9084
9085    begin
9086       T := Entity (Subtype_Mark (SI));
9087
9088       if Ekind (T) in Access_Kind then
9089          T := Designated_Type (T);
9090       end if;
9091
9092       --  If an index constraint follows a subtype mark in a subtype indication
9093       --  then the type or subtype denoted by the subtype mark must not already
9094       --  impose an index constraint. The subtype mark must denote either an
9095       --  unconstrained array type or an access type whose designated type
9096       --  is such an array type... (RM 3.6.1)
9097
9098       if Is_Constrained (T) then
9099          Error_Msg_N
9100            ("array type is already constrained", Subtype_Mark (SI));
9101          Constraint_OK := False;
9102
9103       else
9104          S := First (Constraints (C));
9105          while Present (S) loop
9106             Number_Of_Constraints := Number_Of_Constraints + 1;
9107             Next (S);
9108          end loop;
9109
9110          --  In either case, the index constraint must provide a discrete
9111          --  range for each index of the array type and the type of each
9112          --  discrete range must be the same as that of the corresponding
9113          --  index. (RM 3.6.1)
9114
9115          if Number_Of_Constraints /= Number_Dimensions (T) then
9116             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
9117             Constraint_OK := False;
9118
9119          else
9120             S := First (Constraints (C));
9121             Index := First_Index (T);
9122             Analyze (Index);
9123
9124             --  Apply constraints to each index type
9125
9126             for J in 1 .. Number_Of_Constraints loop
9127                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
9128                Next (Index);
9129                Next (S);
9130             end loop;
9131
9132          end if;
9133       end if;
9134
9135       if No (Def_Id) then
9136          Def_Id :=
9137            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
9138          Set_Parent (Def_Id, Related_Nod);
9139
9140       else
9141          Set_Ekind (Def_Id, E_Array_Subtype);
9142       end if;
9143
9144       Set_Size_Info      (Def_Id,                (T));
9145       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
9146       Set_Etype          (Def_Id, Base_Type      (T));
9147
9148       if Constraint_OK then
9149          Set_First_Index (Def_Id, First (Constraints (C)));
9150       else
9151          Set_First_Index (Def_Id, First_Index (T));
9152       end if;
9153
9154       Set_Is_Constrained     (Def_Id, True);
9155       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
9156       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
9157
9158       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
9159       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
9160
9161       --  A subtype does not inherit the packed_array_type of is parent. We
9162       --  need to initialize the attribute because if Def_Id is previously
9163       --  analyzed through a limited_with clause, it will have the attributes
9164       --  of an incomplete type, one of which is an Elist that overlaps the
9165       --  Packed_Array_Type field.
9166
9167       Set_Packed_Array_Type (Def_Id, Empty);
9168
9169       --  Build a freeze node if parent still needs one. Also make sure that
9170       --  the Depends_On_Private status is set because the subtype will need
9171       --  reprocessing at the time the base type does, and also we must set a
9172       --  conditional delay.
9173
9174       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
9175       Conditional_Delay (Def_Id, T);
9176    end Constrain_Array;
9177
9178    ------------------------------
9179    -- Constrain_Component_Type --
9180    ------------------------------
9181
9182    function Constrain_Component_Type
9183      (Comp            : Entity_Id;
9184       Constrained_Typ : Entity_Id;
9185       Related_Node    : Node_Id;
9186       Typ             : Entity_Id;
9187       Constraints     : Elist_Id) return Entity_Id
9188    is
9189       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
9190       Compon_Type : constant Entity_Id := Etype (Comp);
9191
9192       function Build_Constrained_Array_Type
9193         (Old_Type : Entity_Id) return Entity_Id;
9194       --  If Old_Type is an array type, one of whose indices is constrained
9195       --  by a discriminant, build an Itype whose constraint replaces the
9196       --  discriminant with its value in the constraint.
9197
9198       function Build_Constrained_Discriminated_Type
9199         (Old_Type : Entity_Id) return Entity_Id;
9200       --  Ditto for record components
9201
9202       function Build_Constrained_Access_Type
9203         (Old_Type : Entity_Id) return Entity_Id;
9204       --  Ditto for access types. Makes use of previous two functions, to
9205       --  constrain designated type.
9206
9207       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
9208       --  T is an array or discriminated type, C is a list of constraints
9209       --  that apply to T. This routine builds the constrained subtype.
9210
9211       function Is_Discriminant (Expr : Node_Id) return Boolean;
9212       --  Returns True if Expr is a discriminant
9213
9214       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
9215       --  Find the value of discriminant Discrim in Constraint
9216
9217       -----------------------------------
9218       -- Build_Constrained_Access_Type --
9219       -----------------------------------
9220
9221       function Build_Constrained_Access_Type
9222         (Old_Type : Entity_Id) return Entity_Id
9223       is
9224          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
9225          Itype         : Entity_Id;
9226          Desig_Subtype : Entity_Id;
9227          Scop          : Entity_Id;
9228
9229       begin
9230          --  if the original access type was not embedded in the enclosing
9231          --  type definition, there is no need to produce a new access
9232          --  subtype. In fact every access type with an explicit constraint
9233          --  generates an itype whose scope is the enclosing record.
9234
9235          if not Is_Type (Scope (Old_Type)) then
9236             return Old_Type;
9237
9238          elsif Is_Array_Type (Desig_Type) then
9239             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
9240
9241          elsif Has_Discriminants (Desig_Type) then
9242
9243             --  This may be an access type to an enclosing record type for
9244             --  which we are constructing the constrained components. Return
9245             --  the enclosing record subtype. This is not always correct,
9246             --  but avoids infinite recursion. ???
9247
9248             Desig_Subtype := Any_Type;
9249
9250             for J in reverse 0 .. Scope_Stack.Last loop
9251                Scop := Scope_Stack.Table (J).Entity;
9252
9253                if Is_Type (Scop)
9254                  and then Base_Type (Scop) = Base_Type (Desig_Type)
9255                then
9256                   Desig_Subtype := Scop;
9257                end if;
9258
9259                exit when not Is_Type (Scop);
9260             end loop;
9261
9262             if Desig_Subtype = Any_Type then
9263                Desig_Subtype :=
9264                  Build_Constrained_Discriminated_Type (Desig_Type);
9265             end if;
9266
9267          else
9268             return Old_Type;
9269          end if;
9270
9271          if Desig_Subtype /= Desig_Type then
9272
9273             --  The Related_Node better be here or else we won't be able
9274             --  to attach new itypes to a node in the tree.
9275
9276             pragma Assert (Present (Related_Node));
9277
9278             Itype := Create_Itype (E_Access_Subtype, Related_Node);
9279
9280             Set_Etype                    (Itype, Base_Type      (Old_Type));
9281             Set_Size_Info                (Itype,                (Old_Type));
9282             Set_Directly_Designated_Type (Itype, Desig_Subtype);
9283             Set_Depends_On_Private       (Itype, Has_Private_Component
9284                                                                 (Old_Type));
9285             Set_Is_Access_Constant       (Itype, Is_Access_Constant
9286                                                                 (Old_Type));
9287
9288             --  The new itype needs freezing when it depends on a not frozen
9289             --  type and the enclosing subtype needs freezing.
9290
9291             if Has_Delayed_Freeze (Constrained_Typ)
9292               and then not Is_Frozen (Constrained_Typ)
9293             then
9294                Conditional_Delay (Itype, Base_Type (Old_Type));
9295             end if;
9296
9297             return Itype;
9298
9299          else
9300             return Old_Type;
9301          end if;
9302       end Build_Constrained_Access_Type;
9303
9304       ----------------------------------
9305       -- Build_Constrained_Array_Type --
9306       ----------------------------------
9307
9308       function Build_Constrained_Array_Type
9309         (Old_Type : Entity_Id) return Entity_Id
9310       is
9311          Lo_Expr     : Node_Id;
9312          Hi_Expr     : Node_Id;
9313          Old_Index   : Node_Id;
9314          Range_Node  : Node_Id;
9315          Constr_List : List_Id;
9316
9317          Need_To_Create_Itype : Boolean := False;
9318
9319       begin
9320          Old_Index := First_Index (Old_Type);
9321          while Present (Old_Index) loop
9322             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
9323
9324             if Is_Discriminant (Lo_Expr)
9325               or else Is_Discriminant (Hi_Expr)
9326             then
9327                Need_To_Create_Itype := True;
9328             end if;
9329
9330             Next_Index (Old_Index);
9331          end loop;
9332
9333          if Need_To_Create_Itype then
9334             Constr_List := New_List;
9335
9336             Old_Index := First_Index (Old_Type);
9337             while Present (Old_Index) loop
9338                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
9339
9340                if Is_Discriminant (Lo_Expr) then
9341                   Lo_Expr := Get_Discr_Value (Lo_Expr);
9342                end if;
9343
9344                if Is_Discriminant (Hi_Expr) then
9345                   Hi_Expr := Get_Discr_Value (Hi_Expr);
9346                end if;
9347
9348                Range_Node :=
9349                  Make_Range
9350                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
9351
9352                Append (Range_Node, To => Constr_List);
9353
9354                Next_Index (Old_Index);
9355             end loop;
9356
9357             return Build_Subtype (Old_Type, Constr_List);
9358
9359          else
9360             return Old_Type;
9361          end if;
9362       end Build_Constrained_Array_Type;
9363
9364       ------------------------------------------
9365       -- Build_Constrained_Discriminated_Type --
9366       ------------------------------------------
9367
9368       function Build_Constrained_Discriminated_Type
9369         (Old_Type : Entity_Id) return Entity_Id
9370       is
9371          Expr           : Node_Id;
9372          Constr_List    : List_Id;
9373          Old_Constraint : Elmt_Id;
9374
9375          Need_To_Create_Itype : Boolean := False;
9376
9377       begin
9378          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
9379          while Present (Old_Constraint) loop
9380             Expr := Node (Old_Constraint);
9381
9382             if Is_Discriminant (Expr) then
9383                Need_To_Create_Itype := True;
9384             end if;
9385
9386             Next_Elmt (Old_Constraint);
9387          end loop;
9388
9389          if Need_To_Create_Itype then
9390             Constr_List := New_List;
9391
9392             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
9393             while Present (Old_Constraint) loop
9394                Expr := Node (Old_Constraint);
9395
9396                if Is_Discriminant (Expr) then
9397                   Expr := Get_Discr_Value (Expr);
9398                end if;
9399
9400                Append (New_Copy_Tree (Expr), To => Constr_List);
9401
9402                Next_Elmt (Old_Constraint);
9403             end loop;
9404
9405             return Build_Subtype (Old_Type, Constr_List);
9406
9407          else
9408             return Old_Type;
9409          end if;
9410       end Build_Constrained_Discriminated_Type;
9411
9412       -------------------
9413       -- Build_Subtype --
9414       -------------------
9415
9416       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
9417          Indic       : Node_Id;
9418          Subtyp_Decl : Node_Id;
9419          Def_Id      : Entity_Id;
9420          Btyp        : Entity_Id := Base_Type (T);
9421
9422       begin
9423          --  The Related_Node better be here or else we won't be able to
9424          --  attach new itypes to a node in the tree.
9425
9426          pragma Assert (Present (Related_Node));
9427
9428          --  If the view of the component's type is incomplete or private
9429          --  with unknown discriminants, then the constraint must be applied
9430          --  to the full type.
9431
9432          if Has_Unknown_Discriminants (Btyp)
9433            and then Present (Underlying_Type (Btyp))
9434          then
9435             Btyp := Underlying_Type (Btyp);
9436          end if;
9437
9438          Indic :=
9439            Make_Subtype_Indication (Loc,
9440              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
9441              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
9442
9443          Def_Id := Create_Itype (Ekind (T), Related_Node);
9444
9445          Subtyp_Decl :=
9446            Make_Subtype_Declaration (Loc,
9447              Defining_Identifier => Def_Id,
9448              Subtype_Indication  => Indic);
9449
9450          Set_Parent (Subtyp_Decl, Parent (Related_Node));
9451
9452          --  Itypes must be analyzed with checks off (see package Itypes)
9453
9454          Analyze (Subtyp_Decl, Suppress => All_Checks);
9455
9456          return Def_Id;
9457       end Build_Subtype;
9458
9459       ---------------------
9460       -- Get_Discr_Value --
9461       ---------------------
9462
9463       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
9464          D : Entity_Id;
9465          E : Elmt_Id;
9466          G : Elmt_Id;
9467
9468       begin
9469          --  The discriminant may be declared for the type, in which case we
9470          --  find it by iterating over the list of discriminants. If the
9471          --  discriminant is inherited from a parent type, it appears as the
9472          --  corresponding discriminant of the current type. This will be the
9473          --  case when constraining an inherited component whose constraint is
9474          --  given by a discriminant of the parent.
9475
9476          D := First_Discriminant (Typ);
9477          E := First_Elmt (Constraints);
9478
9479          while Present (D) loop
9480             if D = Entity (Discrim)
9481               or else D = CR_Discriminant (Entity (Discrim))
9482               or else Corresponding_Discriminant (D) = Entity (Discrim)
9483             then
9484                return Node (E);
9485             end if;
9486
9487             Next_Discriminant (D);
9488             Next_Elmt (E);
9489          end loop;
9490
9491          --  The corresponding_Discriminant mechanism is incomplete, because
9492          --  the correspondence between new and old discriminants is not one
9493          --  to one: one new discriminant can constrain several old ones. In
9494          --  that case, scan sequentially the stored_constraint, the list of
9495          --  discriminants of the parents, and the constraints.
9496
9497          if Is_Derived_Type (Typ)
9498            and then Present (Stored_Constraint (Typ))
9499            and then Scope (Entity (Discrim)) = Etype (Typ)
9500          then
9501             D := First_Discriminant (Etype (Typ));
9502             E := First_Elmt (Constraints);
9503             G := First_Elmt (Stored_Constraint (Typ));
9504             while Present (D) loop
9505                if D = Entity (Discrim) then
9506                   return Node (E);
9507                end if;
9508
9509                Next_Discriminant (D);
9510                Next_Elmt (E);
9511                Next_Elmt (G);
9512             end loop;
9513          end if;
9514
9515          --  Something is wrong if we did not find the value
9516
9517          raise Program_Error;
9518       end Get_Discr_Value;
9519
9520       ---------------------
9521       -- Is_Discriminant --
9522       ---------------------
9523
9524       function Is_Discriminant (Expr : Node_Id) return Boolean is
9525          Discrim_Scope : Entity_Id;
9526
9527       begin
9528          if Denotes_Discriminant (Expr) then
9529             Discrim_Scope := Scope (Entity (Expr));
9530
9531             --  Either we have a reference to one of Typ's discriminants,
9532
9533             pragma Assert (Discrim_Scope = Typ
9534
9535                --  or to the discriminants of the parent type, in the case
9536                --  of a derivation of a tagged type with variants.
9537
9538                or else Discrim_Scope = Etype (Typ)
9539                or else Full_View (Discrim_Scope) = Etype (Typ)
9540
9541                --  or same as above for the case where the discriminants
9542                --  were declared in Typ's private view.
9543
9544                or else (Is_Private_Type (Discrim_Scope)
9545                         and then Chars (Discrim_Scope) = Chars (Typ))
9546
9547                --  or else we are deriving from the full view and the
9548                --  discriminant is declared in the private entity.
9549
9550                or else (Is_Private_Type (Typ)
9551                         and then Chars (Discrim_Scope) = Chars (Typ))
9552
9553                --  Or we are constrained the corresponding record of a
9554                --  synchronized type that completes a private declaration.
9555
9556                or else (Is_Concurrent_Record_Type (Typ)
9557                          and then
9558                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
9559
9560                --  or we have a class-wide type, in which case make sure the
9561                --  discriminant found belongs to the root type.
9562
9563                or else (Is_Class_Wide_Type (Typ)
9564                         and then Etype (Typ) = Discrim_Scope));
9565
9566             return True;
9567          end if;
9568
9569          --  In all other cases we have something wrong
9570
9571          return False;
9572       end Is_Discriminant;
9573
9574    --  Start of processing for Constrain_Component_Type
9575
9576    begin
9577       if Nkind (Parent (Comp)) = N_Component_Declaration
9578         and then Comes_From_Source (Parent (Comp))
9579         and then Comes_From_Source
9580           (Subtype_Indication (Component_Definition (Parent (Comp))))
9581         and then
9582           Is_Entity_Name
9583             (Subtype_Indication (Component_Definition (Parent (Comp))))
9584       then
9585          return Compon_Type;
9586
9587       elsif Is_Array_Type (Compon_Type) then
9588          return Build_Constrained_Array_Type (Compon_Type);
9589
9590       elsif Has_Discriminants (Compon_Type) then
9591          return Build_Constrained_Discriminated_Type (Compon_Type);
9592
9593       elsif Is_Access_Type (Compon_Type) then
9594          return Build_Constrained_Access_Type (Compon_Type);
9595
9596       else
9597          return Compon_Type;
9598       end if;
9599    end Constrain_Component_Type;
9600
9601    --------------------------
9602    -- Constrain_Concurrent --
9603    --------------------------
9604
9605    --  For concurrent types, the associated record value type carries the same
9606    --  discriminants, so when we constrain a concurrent type, we must constrain
9607    --  the corresponding record type as well.
9608
9609    procedure Constrain_Concurrent
9610      (Def_Id      : in out Entity_Id;
9611       SI          : Node_Id;
9612       Related_Nod : Node_Id;
9613       Related_Id  : Entity_Id;
9614       Suffix      : Character)
9615    is
9616       T_Ent : Entity_Id := Entity (Subtype_Mark (SI));
9617       T_Val : Entity_Id;
9618
9619    begin
9620       if Ekind (T_Ent) in Access_Kind then
9621          T_Ent := Designated_Type (T_Ent);
9622       end if;
9623
9624       T_Val := Corresponding_Record_Type (T_Ent);
9625
9626       if Present (T_Val) then
9627
9628          if No (Def_Id) then
9629             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
9630          end if;
9631
9632          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
9633
9634          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
9635          Set_Corresponding_Record_Type (Def_Id,
9636            Constrain_Corresponding_Record
9637              (Def_Id, T_Val, Related_Nod, Related_Id));
9638
9639       else
9640          --  If there is no associated record, expansion is disabled and this
9641          --  is a generic context. Create a subtype in any case, so that
9642          --  semantic analysis can proceed.
9643
9644          if No (Def_Id) then
9645             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
9646          end if;
9647
9648          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
9649       end if;
9650    end Constrain_Concurrent;
9651
9652    ------------------------------------
9653    -- Constrain_Corresponding_Record --
9654    ------------------------------------
9655
9656    function Constrain_Corresponding_Record
9657      (Prot_Subt   : Entity_Id;
9658       Corr_Rec    : Entity_Id;
9659       Related_Nod : Node_Id;
9660       Related_Id  : Entity_Id) return Entity_Id
9661    is
9662       T_Sub : constant Entity_Id :=
9663                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
9664
9665    begin
9666       Set_Etype             (T_Sub, Corr_Rec);
9667       Init_Size_Align       (T_Sub);
9668       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
9669       Set_Is_Constrained    (T_Sub, True);
9670       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
9671       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
9672
9673       --  As elsewhere, we do not want to create a freeze node for this itype
9674       --  if it is created for a constrained component of an enclosing record
9675       --  because references to outer discriminants will appear out of scope.
9676
9677       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
9678          Conditional_Delay (T_Sub, Corr_Rec);
9679       else
9680          Set_Is_Frozen (T_Sub);
9681       end if;
9682
9683       if Has_Discriminants (Prot_Subt) then -- False only if errors.
9684          Set_Discriminant_Constraint
9685            (T_Sub, Discriminant_Constraint (Prot_Subt));
9686          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
9687          Create_Constrained_Components
9688            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
9689       end if;
9690
9691       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
9692
9693       return T_Sub;
9694    end Constrain_Corresponding_Record;
9695
9696    -----------------------
9697    -- Constrain_Decimal --
9698    -----------------------
9699
9700    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
9701       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
9702       C           : constant Node_Id    := Constraint (S);
9703       Loc         : constant Source_Ptr := Sloc (C);
9704       Range_Expr  : Node_Id;
9705       Digits_Expr : Node_Id;
9706       Digits_Val  : Uint;
9707       Bound_Val   : Ureal;
9708
9709    begin
9710       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
9711
9712       if Nkind (C) = N_Range_Constraint then
9713          Range_Expr := Range_Expression (C);
9714          Digits_Val := Digits_Value (T);
9715
9716       else
9717          pragma Assert (Nkind (C) = N_Digits_Constraint);
9718          Digits_Expr := Digits_Expression (C);
9719          Analyze_And_Resolve (Digits_Expr, Any_Integer);
9720
9721          Check_Digits_Expression (Digits_Expr);
9722          Digits_Val := Expr_Value (Digits_Expr);
9723
9724          if Digits_Val > Digits_Value (T) then
9725             Error_Msg_N
9726                ("digits expression is incompatible with subtype", C);
9727             Digits_Val := Digits_Value (T);
9728          end if;
9729
9730          if Present (Range_Constraint (C)) then
9731             Range_Expr := Range_Expression (Range_Constraint (C));
9732          else
9733             Range_Expr := Empty;
9734          end if;
9735       end if;
9736
9737       Set_Etype            (Def_Id, Base_Type        (T));
9738       Set_Size_Info        (Def_Id,                  (T));
9739       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
9740       Set_Delta_Value      (Def_Id, Delta_Value      (T));
9741       Set_Scale_Value      (Def_Id, Scale_Value      (T));
9742       Set_Small_Value      (Def_Id, Small_Value      (T));
9743       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
9744       Set_Digits_Value     (Def_Id, Digits_Val);
9745
9746       --  Manufacture range from given digits value if no range present
9747
9748       if No (Range_Expr) then
9749          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
9750          Range_Expr :=
9751            Make_Range (Loc,
9752              Low_Bound =>
9753                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
9754              High_Bound =>
9755                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
9756       end if;
9757
9758       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
9759       Set_Discrete_RM_Size (Def_Id);
9760
9761       --  Unconditionally delay the freeze, since we cannot set size
9762       --  information in all cases correctly until the freeze point.
9763
9764       Set_Has_Delayed_Freeze (Def_Id);
9765    end Constrain_Decimal;
9766
9767    ----------------------------------
9768    -- Constrain_Discriminated_Type --
9769    ----------------------------------
9770
9771    procedure Constrain_Discriminated_Type
9772      (Def_Id      : Entity_Id;
9773       S           : Node_Id;
9774       Related_Nod : Node_Id;
9775       For_Access  : Boolean := False)
9776    is
9777       E     : constant Entity_Id := Entity (Subtype_Mark (S));
9778       T     : Entity_Id;
9779       C     : Node_Id;
9780       Elist : Elist_Id := New_Elmt_List;
9781
9782       procedure Fixup_Bad_Constraint;
9783       --  This is called after finding a bad constraint, and after having
9784       --  posted an appropriate error message. The mission is to leave the
9785       --  entity T in as reasonable state as possible!
9786
9787       --------------------------
9788       -- Fixup_Bad_Constraint --
9789       --------------------------
9790
9791       procedure Fixup_Bad_Constraint is
9792       begin
9793          --  Set a reasonable Ekind for the entity. For an incomplete type,
9794          --  we can't do much, but for other types, we can set the proper
9795          --  corresponding subtype kind.
9796
9797          if Ekind (T) = E_Incomplete_Type then
9798             Set_Ekind (Def_Id, Ekind (T));
9799          else
9800             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
9801          end if;
9802
9803          Set_Etype (Def_Id, Any_Type);
9804          Set_Error_Posted (Def_Id);
9805       end Fixup_Bad_Constraint;
9806
9807    --  Start of processing for Constrain_Discriminated_Type
9808
9809    begin
9810       C := Constraint (S);
9811
9812       --  A discriminant constraint is only allowed in a subtype indication,
9813       --  after a subtype mark. This subtype mark must denote either a type
9814       --  with discriminants, or an access type whose designated type is a
9815       --  type with discriminants. A discriminant constraint specifies the
9816       --  values of these discriminants (RM 3.7.2(5)).
9817
9818       T := Base_Type (Entity (Subtype_Mark (S)));
9819
9820       if Ekind (T) in Access_Kind then
9821          T := Designated_Type (T);
9822       end if;
9823
9824       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
9825       --  Avoid generating an error for access-to-incomplete subtypes.
9826
9827       if Ada_Version >= Ada_05
9828         and then Ekind (T) = E_Incomplete_Type
9829         and then Nkind (Parent (S)) = N_Subtype_Declaration
9830         and then not Is_Itype (Def_Id)
9831       then
9832          --  A little sanity check, emit an error message if the type
9833          --  has discriminants to begin with. Type T may be a regular
9834          --  incomplete type or imported via a limited with clause.
9835
9836          if Has_Discriminants (T)
9837            or else
9838              (From_With_Type (T)
9839                 and then Present (Non_Limited_View (T))
9840                 and then Nkind (Parent (Non_Limited_View (T))) =
9841                            N_Full_Type_Declaration
9842                 and then Present (Discriminant_Specifications
9843                           (Parent (Non_Limited_View (T)))))
9844          then
9845             Error_Msg_N
9846               ("(Ada 2005) incomplete subtype may not be constrained", C);
9847          else
9848             Error_Msg_N
9849               ("invalid constraint: type has no discriminant", C);
9850          end if;
9851
9852          Fixup_Bad_Constraint;
9853          return;
9854
9855       --  Check that the type has visible discriminants. The type may be
9856       --  a private type with unknown discriminants whose full view has
9857       --  discriminants which are invisible.
9858
9859       elsif not Has_Discriminants (T)
9860         or else
9861           (Has_Unknown_Discriminants (T)
9862              and then Is_Private_Type (T))
9863       then
9864          Error_Msg_N ("invalid constraint: type has no discriminant", C);
9865          Fixup_Bad_Constraint;
9866          return;
9867
9868       elsif Is_Constrained (E)
9869         or else (Ekind (E) = E_Class_Wide_Subtype
9870                   and then Present (Discriminant_Constraint (E)))
9871       then
9872          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
9873          Fixup_Bad_Constraint;
9874          return;
9875       end if;
9876
9877       --  T may be an unconstrained subtype (e.g. a generic actual).
9878       --  Constraint applies to the base type.
9879
9880       T := Base_Type (T);
9881
9882       Elist := Build_Discriminant_Constraints (T, S);
9883
9884       --  If the list returned was empty we had an error in building the
9885       --  discriminant constraint. We have also already signalled an error
9886       --  in the incomplete type case
9887
9888       if Is_Empty_Elmt_List (Elist) then
9889          Fixup_Bad_Constraint;
9890          return;
9891       end if;
9892
9893       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
9894    end Constrain_Discriminated_Type;
9895
9896    ---------------------------
9897    -- Constrain_Enumeration --
9898    ---------------------------
9899
9900    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
9901       T : constant Entity_Id := Entity (Subtype_Mark (S));
9902       C : constant Node_Id   := Constraint (S);
9903
9904    begin
9905       Set_Ekind (Def_Id, E_Enumeration_Subtype);
9906
9907       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
9908
9909       Set_Etype             (Def_Id, Base_Type         (T));
9910       Set_Size_Info         (Def_Id,                   (T));
9911       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
9912       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
9913
9914       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
9915
9916       Set_Discrete_RM_Size (Def_Id);
9917    end Constrain_Enumeration;
9918
9919    ----------------------
9920    -- Constrain_Float --
9921    ----------------------
9922
9923    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
9924       T    : constant Entity_Id := Entity (Subtype_Mark (S));
9925       C    : Node_Id;
9926       D    : Node_Id;
9927       Rais : Node_Id;
9928
9929    begin
9930       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
9931
9932       Set_Etype          (Def_Id, Base_Type      (T));
9933       Set_Size_Info      (Def_Id,                (T));
9934       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
9935
9936       --  Process the constraint
9937
9938       C := Constraint (S);
9939
9940       --  Digits constraint present
9941
9942       if Nkind (C) = N_Digits_Constraint then
9943          Check_Restriction (No_Obsolescent_Features, C);
9944
9945          if Warn_On_Obsolescent_Feature then
9946             Error_Msg_N
9947               ("subtype digits constraint is an " &
9948                "obsolescent feature (RM J.3(8))?", C);
9949          end if;
9950
9951          D := Digits_Expression (C);
9952          Analyze_And_Resolve (D, Any_Integer);
9953          Check_Digits_Expression (D);
9954          Set_Digits_Value (Def_Id, Expr_Value (D));
9955
9956          --  Check that digits value is in range. Obviously we can do this
9957          --  at compile time, but it is strictly a runtime check, and of
9958          --  course there is an ACVC test that checks this!
9959
9960          if Digits_Value (Def_Id) > Digits_Value (T) then
9961             Error_Msg_Uint_1 := Digits_Value (T);
9962             Error_Msg_N ("?digits value is too large, maximum is ^", D);
9963             Rais :=
9964               Make_Raise_Constraint_Error (Sloc (D),
9965                 Reason => CE_Range_Check_Failed);
9966             Insert_Action (Declaration_Node (Def_Id), Rais);
9967          end if;
9968
9969          C := Range_Constraint (C);
9970
9971       --  No digits constraint present
9972
9973       else
9974          Set_Digits_Value (Def_Id, Digits_Value (T));
9975       end if;
9976
9977       --  Range constraint present
9978
9979       if Nkind (C) = N_Range_Constraint then
9980          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
9981
9982       --  No range constraint present
9983
9984       else
9985          pragma Assert (No (C));
9986          Set_Scalar_Range (Def_Id, Scalar_Range (T));
9987       end if;
9988
9989       Set_Is_Constrained (Def_Id);
9990    end Constrain_Float;
9991
9992    ---------------------
9993    -- Constrain_Index --
9994    ---------------------
9995
9996    procedure Constrain_Index
9997      (Index        : Node_Id;
9998       S            : Node_Id;
9999       Related_Nod  : Node_Id;
10000       Related_Id   : Entity_Id;
10001       Suffix       : Character;
10002       Suffix_Index : Nat)
10003    is
10004       Def_Id : Entity_Id;
10005       R      : Node_Id := Empty;
10006       T      : constant Entity_Id := Etype (Index);
10007
10008    begin
10009       if Nkind (S) = N_Range
10010         or else
10011           (Nkind (S) = N_Attribute_Reference
10012             and then Attribute_Name (S) = Name_Range)
10013       then
10014          --  A Range attribute will transformed into N_Range by Resolve
10015
10016          Analyze (S);
10017          Set_Etype (S, T);
10018          R := S;
10019
10020          Process_Range_Expr_In_Decl (R, T, Empty_List);
10021
10022          if not Error_Posted (S)
10023            and then
10024              (Nkind (S) /= N_Range
10025                or else not Covers (T, (Etype (Low_Bound (S))))
10026                or else not Covers (T, (Etype (High_Bound (S)))))
10027          then
10028             if Base_Type (T) /= Any_Type
10029               and then Etype (Low_Bound (S)) /= Any_Type
10030               and then Etype (High_Bound (S)) /= Any_Type
10031             then
10032                Error_Msg_N ("range expected", S);
10033             end if;
10034          end if;
10035
10036       elsif Nkind (S) = N_Subtype_Indication then
10037
10038          --  The parser has verified that this is a discrete indication
10039
10040          Resolve_Discrete_Subtype_Indication (S, T);
10041          R := Range_Expression (Constraint (S));
10042
10043       elsif Nkind (S) = N_Discriminant_Association then
10044
10045          --  Syntactically valid in subtype indication
10046
10047          Error_Msg_N ("invalid index constraint", S);
10048          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
10049          return;
10050
10051       --  Subtype_Mark case, no anonymous subtypes to construct
10052
10053       else
10054          Analyze (S);
10055
10056          if Is_Entity_Name (S) then
10057             if not Is_Type (Entity (S)) then
10058                Error_Msg_N ("expect subtype mark for index constraint", S);
10059
10060             elsif Base_Type (Entity (S)) /= Base_Type (T) then
10061                Wrong_Type (S, Base_Type (T));
10062             end if;
10063
10064             return;
10065
10066          else
10067             Error_Msg_N ("invalid index constraint", S);
10068             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
10069             return;
10070          end if;
10071       end if;
10072
10073       Def_Id :=
10074         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
10075
10076       Set_Etype (Def_Id, Base_Type (T));
10077
10078       if Is_Modular_Integer_Type (T) then
10079          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
10080
10081       elsif Is_Integer_Type (T) then
10082          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
10083
10084       else
10085          Set_Ekind (Def_Id, E_Enumeration_Subtype);
10086          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
10087       end if;
10088
10089       Set_Size_Info      (Def_Id,                (T));
10090       Set_RM_Size        (Def_Id, RM_Size        (T));
10091       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10092
10093       Set_Scalar_Range   (Def_Id, R);
10094
10095       Set_Etype (S, Def_Id);
10096       Set_Discrete_RM_Size (Def_Id);
10097    end Constrain_Index;
10098
10099    -----------------------
10100    -- Constrain_Integer --
10101    -----------------------
10102
10103    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
10104       T : constant Entity_Id := Entity (Subtype_Mark (S));
10105       C : constant Node_Id   := Constraint (S);
10106
10107    begin
10108       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
10109
10110       if Is_Modular_Integer_Type (T) then
10111          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
10112       else
10113          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
10114       end if;
10115
10116       Set_Etype            (Def_Id, Base_Type        (T));
10117       Set_Size_Info        (Def_Id,                  (T));
10118       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
10119       Set_Discrete_RM_Size (Def_Id);
10120    end Constrain_Integer;
10121
10122    ------------------------------
10123    -- Constrain_Ordinary_Fixed --
10124    ------------------------------
10125
10126    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
10127       T    : constant Entity_Id := Entity (Subtype_Mark (S));
10128       C    : Node_Id;
10129       D    : Node_Id;
10130       Rais : Node_Id;
10131
10132    begin
10133       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
10134       Set_Etype          (Def_Id, Base_Type        (T));
10135       Set_Size_Info      (Def_Id,                  (T));
10136       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
10137       Set_Small_Value    (Def_Id, Small_Value      (T));
10138
10139       --  Process the constraint
10140
10141       C := Constraint (S);
10142
10143       --  Delta constraint present
10144
10145       if Nkind (C) = N_Delta_Constraint then
10146          Check_Restriction (No_Obsolescent_Features, C);
10147
10148          if Warn_On_Obsolescent_Feature then
10149             Error_Msg_S
10150               ("subtype delta constraint is an " &
10151                "obsolescent feature (RM J.3(7))?");
10152          end if;
10153
10154          D := Delta_Expression (C);
10155          Analyze_And_Resolve (D, Any_Real);
10156          Check_Delta_Expression (D);
10157          Set_Delta_Value (Def_Id, Expr_Value_R (D));
10158
10159          --  Check that delta value is in range. Obviously we can do this
10160          --  at compile time, but it is strictly a runtime check, and of
10161          --  course there is an ACVC test that checks this!
10162
10163          if Delta_Value (Def_Id) < Delta_Value (T) then
10164             Error_Msg_N ("?delta value is too small", D);
10165             Rais :=
10166               Make_Raise_Constraint_Error (Sloc (D),
10167                 Reason => CE_Range_Check_Failed);
10168             Insert_Action (Declaration_Node (Def_Id), Rais);
10169          end if;
10170
10171          C := Range_Constraint (C);
10172
10173       --  No delta constraint present
10174
10175       else
10176          Set_Delta_Value (Def_Id, Delta_Value (T));
10177       end if;
10178
10179       --  Range constraint present
10180
10181       if Nkind (C) = N_Range_Constraint then
10182          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
10183
10184       --  No range constraint present
10185
10186       else
10187          pragma Assert (No (C));
10188          Set_Scalar_Range (Def_Id, Scalar_Range (T));
10189
10190       end if;
10191
10192       Set_Discrete_RM_Size (Def_Id);
10193
10194       --  Unconditionally delay the freeze, since we cannot set size
10195       --  information in all cases correctly until the freeze point.
10196
10197       Set_Has_Delayed_Freeze (Def_Id);
10198    end Constrain_Ordinary_Fixed;
10199
10200    -----------------------
10201    -- Contain_Interface --
10202    -----------------------
10203
10204    function Contain_Interface
10205      (Iface  : Entity_Id;
10206       Ifaces : Elist_Id) return Boolean
10207    is
10208       Iface_Elmt : Elmt_Id;
10209
10210    begin
10211       if Present (Ifaces) then
10212          Iface_Elmt := First_Elmt (Ifaces);
10213          while Present (Iface_Elmt) loop
10214             if Node (Iface_Elmt) = Iface then
10215                return True;
10216             end if;
10217
10218             Next_Elmt (Iface_Elmt);
10219          end loop;
10220       end if;
10221
10222       return False;
10223    end Contain_Interface;
10224
10225    ---------------------------
10226    -- Convert_Scalar_Bounds --
10227    ---------------------------
10228
10229    procedure Convert_Scalar_Bounds
10230      (N            : Node_Id;
10231       Parent_Type  : Entity_Id;
10232       Derived_Type : Entity_Id;
10233       Loc          : Source_Ptr)
10234    is
10235       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
10236
10237       Lo  : Node_Id;
10238       Hi  : Node_Id;
10239       Rng : Node_Id;
10240
10241    begin
10242       Lo := Build_Scalar_Bound
10243               (Type_Low_Bound (Derived_Type),
10244                Parent_Type, Implicit_Base);
10245
10246       Hi := Build_Scalar_Bound
10247               (Type_High_Bound (Derived_Type),
10248                Parent_Type, Implicit_Base);
10249
10250       Rng :=
10251         Make_Range (Loc,
10252           Low_Bound  => Lo,
10253           High_Bound => Hi);
10254
10255       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
10256
10257       Set_Parent (Rng, N);
10258       Set_Scalar_Range (Derived_Type, Rng);
10259
10260       --  Analyze the bounds
10261
10262       Analyze_And_Resolve (Lo, Implicit_Base);
10263       Analyze_And_Resolve (Hi, Implicit_Base);
10264
10265       --  Analyze the range itself, except that we do not analyze it if
10266       --  the bounds are real literals, and we have a fixed-point type.
10267       --  The reason for this is that we delay setting the bounds in this
10268       --  case till we know the final Small and Size values (see circuit
10269       --  in Freeze.Freeze_Fixed_Point_Type for further details).
10270
10271       if Is_Fixed_Point_Type (Parent_Type)
10272         and then Nkind (Lo) = N_Real_Literal
10273         and then Nkind (Hi) = N_Real_Literal
10274       then
10275          return;
10276
10277       --  Here we do the analysis of the range
10278
10279       --  Note: we do this manually, since if we do a normal Analyze and
10280       --  Resolve call, there are problems with the conversions used for
10281       --  the derived type range.
10282
10283       else
10284          Set_Etype    (Rng, Implicit_Base);
10285          Set_Analyzed (Rng, True);
10286       end if;
10287    end Convert_Scalar_Bounds;
10288
10289    -------------------
10290    -- Copy_And_Swap --
10291    -------------------
10292
10293    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
10294    begin
10295       --  Initialize new full declaration entity by copying the pertinent
10296       --  fields of the corresponding private declaration entity.
10297
10298       --  We temporarily set Ekind to a value appropriate for a type to
10299       --  avoid assert failures in Einfo from checking for setting type
10300       --  attributes on something that is not a type. Ekind (Priv) is an
10301       --  appropriate choice, since it allowed the attributes to be set
10302       --  in the first place. This Ekind value will be modified later.
10303
10304       Set_Ekind (Full, Ekind (Priv));
10305
10306       --  Also set Etype temporarily to Any_Type, again, in the absence
10307       --  of errors, it will be properly reset, and if there are errors,
10308       --  then we want a value of Any_Type to remain.
10309
10310       Set_Etype (Full, Any_Type);
10311
10312       --  Now start copying attributes
10313
10314       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
10315
10316       if Has_Discriminants (Full) then
10317          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
10318          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
10319       end if;
10320
10321       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
10322       Set_Homonym                    (Full, Homonym                 (Priv));
10323       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
10324       Set_Is_Public                  (Full, Is_Public               (Priv));
10325       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
10326       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
10327       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
10328       Set_Has_Pragma_Unreferenced_Objects
10329                                      (Full, Has_Pragma_Unreferenced_Objects
10330                                                                     (Priv));
10331
10332       Conditional_Delay              (Full,                          Priv);
10333
10334       if Is_Tagged_Type (Full) then
10335          Set_Primitive_Operations    (Full, Primitive_Operations    (Priv));
10336
10337          if Priv = Base_Type (Priv) then
10338             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
10339          end if;
10340       end if;
10341
10342       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
10343       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
10344       Set_Scope                      (Full, Scope                   (Priv));
10345       Set_Next_Entity                (Full, Next_Entity             (Priv));
10346       Set_First_Entity               (Full, First_Entity            (Priv));
10347       Set_Last_Entity                (Full, Last_Entity             (Priv));
10348
10349       --  If access types have been recorded for later handling, keep them in
10350       --  the full view so that they get handled when the full view freeze
10351       --  node is expanded.
10352
10353       if Present (Freeze_Node (Priv))
10354         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
10355       then
10356          Ensure_Freeze_Node (Full);
10357          Set_Access_Types_To_Process
10358            (Freeze_Node (Full),
10359             Access_Types_To_Process (Freeze_Node (Priv)));
10360       end if;
10361
10362       --  Swap the two entities. Now Privat is the full type entity and
10363       --  Full is the private one. They will be swapped back at the end
10364       --  of the private part. This swapping ensures that the entity that
10365       --  is visible in the private part is the full declaration.
10366
10367       Exchange_Entities (Priv, Full);
10368       Append_Entity (Full, Scope (Full));
10369    end Copy_And_Swap;
10370
10371    -------------------------------------
10372    -- Copy_Array_Base_Type_Attributes --
10373    -------------------------------------
10374
10375    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
10376    begin
10377       Set_Component_Alignment      (T1, Component_Alignment      (T2));
10378       Set_Component_Type           (T1, Component_Type           (T2));
10379       Set_Component_Size           (T1, Component_Size           (T2));
10380       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
10381       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
10382       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
10383       Set_Has_Task                 (T1, Has_Task                 (T2));
10384       Set_Is_Packed                (T1, Is_Packed                (T2));
10385       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
10386       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
10387       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
10388    end Copy_Array_Base_Type_Attributes;
10389
10390    -----------------------------------
10391    -- Copy_Array_Subtype_Attributes --
10392    -----------------------------------
10393
10394    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
10395    begin
10396       Set_Size_Info (T1, T2);
10397
10398       Set_First_Index          (T1, First_Index           (T2));
10399       Set_Is_Aliased           (T1, Is_Aliased            (T2));
10400       Set_Is_Atomic            (T1, Is_Atomic             (T2));
10401       Set_Is_Volatile          (T1, Is_Volatile           (T2));
10402       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
10403       Set_Is_Constrained       (T1, Is_Constrained        (T2));
10404       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
10405       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
10406       Set_Convention           (T1, Convention            (T2));
10407       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
10408       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
10409    end Copy_Array_Subtype_Attributes;
10410
10411    -----------------------------------
10412    -- Create_Constrained_Components --
10413    -----------------------------------
10414
10415    procedure Create_Constrained_Components
10416      (Subt        : Entity_Id;
10417       Decl_Node   : Node_Id;
10418       Typ         : Entity_Id;
10419       Constraints : Elist_Id)
10420    is
10421       Loc         : constant Source_Ptr := Sloc (Subt);
10422       Comp_List   : constant Elist_Id   := New_Elmt_List;
10423       Parent_Type : constant Entity_Id  := Etype (Typ);
10424       Assoc_List  : constant List_Id    := New_List;
10425       Discr_Val   : Elmt_Id;
10426       Errors      : Boolean;
10427       New_C       : Entity_Id;
10428       Old_C       : Entity_Id;
10429       Is_Static   : Boolean := True;
10430
10431       procedure Collect_Fixed_Components (Typ : Entity_Id);
10432       --  Collect parent type components that do not appear in a variant part
10433
10434       procedure Create_All_Components;
10435       --  Iterate over Comp_List to create the components of the subtype
10436
10437       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
10438       --  Creates a new component from Old_Compon, copying all the fields from
10439       --  it, including its Etype, inserts the new component in the Subt entity
10440       --  chain and returns the new component.
10441
10442       function Is_Variant_Record (T : Entity_Id) return Boolean;
10443       --  If true, and discriminants are static, collect only components from
10444       --  variants selected by discriminant values.
10445
10446       ------------------------------
10447       -- Collect_Fixed_Components --
10448       ------------------------------
10449
10450       procedure Collect_Fixed_Components (Typ : Entity_Id) is
10451       begin
10452       --  Build association list for discriminants, and find components of the
10453       --  variant part selected by the values of the discriminants.
10454
10455          Old_C := First_Discriminant (Typ);
10456          Discr_Val := First_Elmt (Constraints);
10457          while Present (Old_C) loop
10458             Append_To (Assoc_List,
10459               Make_Component_Association (Loc,
10460                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
10461                  Expression => New_Copy (Node (Discr_Val))));
10462
10463             Next_Elmt (Discr_Val);
10464             Next_Discriminant (Old_C);
10465          end loop;
10466
10467          --  The tag, and the possible parent and controller components
10468          --  are unconditionally in the subtype.
10469
10470          if Is_Tagged_Type (Typ)
10471            or else Has_Controlled_Component (Typ)
10472          then
10473             Old_C := First_Component (Typ);
10474             while Present (Old_C) loop
10475                if Chars ((Old_C)) = Name_uTag
10476                  or else Chars ((Old_C)) = Name_uParent
10477                  or else Chars ((Old_C)) = Name_uController
10478                then
10479                   Append_Elmt (Old_C, Comp_List);
10480                end if;
10481
10482                Next_Component (Old_C);
10483             end loop;
10484          end if;
10485       end Collect_Fixed_Components;
10486
10487       ---------------------------
10488       -- Create_All_Components --
10489       ---------------------------
10490
10491       procedure Create_All_Components is
10492          Comp : Elmt_Id;
10493
10494       begin
10495          Comp := First_Elmt (Comp_List);
10496          while Present (Comp) loop
10497             Old_C := Node (Comp);
10498             New_C := Create_Component (Old_C);
10499
10500             Set_Etype
10501               (New_C,
10502                Constrain_Component_Type
10503                  (Old_C, Subt, Decl_Node, Typ, Constraints));
10504             Set_Is_Public (New_C, Is_Public (Subt));
10505
10506             Next_Elmt (Comp);
10507          end loop;
10508       end Create_All_Components;
10509
10510       ----------------------
10511       -- Create_Component --
10512       ----------------------
10513
10514       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
10515          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
10516
10517       begin
10518          if Ekind (Old_Compon) = E_Discriminant
10519            and then Is_Completely_Hidden (Old_Compon)
10520          then
10521             --  This is a shadow discriminant created for a discriminant of
10522             --  the parent type that is one of several renamed by the same
10523             --  new discriminant. Give the shadow discriminant an internal
10524             --  name that cannot conflict with that of visible components.
10525
10526             Set_Chars (New_Compon, New_Internal_Name ('C'));
10527          end if;
10528
10529          --  Set the parent so we have a proper link for freezing etc. This is
10530          --  not a real parent pointer, since of course our parent does not own
10531          --  up to us and reference us, we are an illegitimate child of the
10532          --  original parent!
10533
10534          Set_Parent (New_Compon, Parent (Old_Compon));
10535
10536          --  If the old component's Esize was already determined and is a
10537          --  static value, then the new component simply inherits it. Otherwise
10538          --  the old component's size may require run-time determination, but
10539          --  the new component's size still might be statically determinable
10540          --  (if, for example it has a static constraint). In that case we want
10541          --  Layout_Type to recompute the component's size, so we reset its
10542          --  size and positional fields.
10543
10544          if Frontend_Layout_On_Target
10545            and then not Known_Static_Esize (Old_Compon)
10546          then
10547             Set_Esize (New_Compon, Uint_0);
10548             Init_Normalized_First_Bit    (New_Compon);
10549             Init_Normalized_Position     (New_Compon);
10550             Init_Normalized_Position_Max (New_Compon);
10551          end if;
10552
10553          --  We do not want this node marked as Comes_From_Source, since
10554          --  otherwise it would get first class status and a separate cross-
10555          --  reference line would be generated. Illegitimate children do not
10556          --  rate such recognition.
10557
10558          Set_Comes_From_Source (New_Compon, False);
10559
10560          --  But it is a real entity, and a birth certificate must be properly
10561          --  registered by entering it into the entity list.
10562
10563          Enter_Name (New_Compon);
10564
10565          return New_Compon;
10566       end Create_Component;
10567
10568       -----------------------
10569       -- Is_Variant_Record --
10570       -----------------------
10571
10572       function Is_Variant_Record (T : Entity_Id) return Boolean is
10573       begin
10574          return Nkind (Parent (T)) = N_Full_Type_Declaration
10575            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
10576            and then Present (Component_List (Type_Definition (Parent (T))))
10577            and then
10578              Present
10579                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
10580       end Is_Variant_Record;
10581
10582    --  Start of processing for Create_Constrained_Components
10583
10584    begin
10585       pragma Assert (Subt /= Base_Type (Subt));
10586       pragma Assert (Typ = Base_Type (Typ));
10587
10588       Set_First_Entity (Subt, Empty);
10589       Set_Last_Entity  (Subt, Empty);
10590
10591       --  Check whether constraint is fully static, in which case we can
10592       --  optimize the list of components.
10593
10594       Discr_Val := First_Elmt (Constraints);
10595       while Present (Discr_Val) loop
10596          if not Is_OK_Static_Expression (Node (Discr_Val)) then
10597             Is_Static := False;
10598             exit;
10599          end if;
10600
10601          Next_Elmt (Discr_Val);
10602       end loop;
10603
10604       Set_Has_Static_Discriminants (Subt, Is_Static);
10605
10606       Push_Scope (Subt);
10607
10608       --  Inherit the discriminants of the parent type
10609
10610       Add_Discriminants : declare
10611          Num_Disc : Int;
10612          Num_Gird : Int;
10613
10614       begin
10615          Num_Disc := 0;
10616          Old_C := First_Discriminant (Typ);
10617
10618          while Present (Old_C) loop
10619             Num_Disc := Num_Disc + 1;
10620             New_C := Create_Component (Old_C);
10621             Set_Is_Public (New_C, Is_Public (Subt));
10622             Next_Discriminant (Old_C);
10623          end loop;
10624
10625          --  For an untagged derived subtype, the number of discriminants may
10626          --  be smaller than the number of inherited discriminants, because
10627          --  several of them may be renamed by a single new discriminant.
10628          --  In this case, add the hidden discriminants back into the subtype,
10629          --  because otherwise the size of the subtype is computed incorrectly
10630          --  in GCC 4.1.
10631
10632          Num_Gird := 0;
10633
10634          if Is_Derived_Type (Typ)
10635            and then not Is_Tagged_Type (Typ)
10636          then
10637             Old_C := First_Stored_Discriminant (Typ);
10638
10639             while Present (Old_C) loop
10640                Num_Gird := Num_Gird + 1;
10641                Next_Stored_Discriminant (Old_C);
10642             end loop;
10643          end if;
10644
10645          if Num_Gird > Num_Disc then
10646
10647             --  Find out multiple uses of new discriminants, and add hidden
10648             --  components for the extra renamed discriminants. We recognize
10649             --  multiple uses through the Corresponding_Discriminant of a
10650             --  new discriminant: if it constrains several old discriminants,
10651             --  this field points to the last one in the parent type. The
10652             --  stored discriminants of the derived type have the same name
10653             --  as those of the parent.
10654
10655             declare
10656                Constr    : Elmt_Id;
10657                New_Discr : Entity_Id;
10658                Old_Discr : Entity_Id;
10659
10660             begin
10661                Constr    := First_Elmt (Stored_Constraint (Typ));
10662                Old_Discr := First_Stored_Discriminant (Typ);
10663                while Present (Constr) loop
10664                   if Is_Entity_Name (Node (Constr))
10665                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
10666                   then
10667                      New_Discr := Entity (Node (Constr));
10668
10669                      if Chars (Corresponding_Discriminant (New_Discr)) /=
10670                         Chars (Old_Discr)
10671                      then
10672                         --  The new discriminant has been used to rename a
10673                         --  subsequent old discriminant. Introduce a shadow
10674                         --  component for the current old discriminant.
10675
10676                         New_C := Create_Component (Old_Discr);
10677                         Set_Original_Record_Component  (New_C, Old_Discr);
10678                      end if;
10679                   end if;
10680
10681                   Next_Elmt (Constr);
10682                   Next_Stored_Discriminant (Old_Discr);
10683                end loop;
10684             end;
10685          end if;
10686       end Add_Discriminants;
10687
10688       if Is_Static
10689         and then Is_Variant_Record (Typ)
10690       then
10691          Collect_Fixed_Components (Typ);
10692
10693          Gather_Components (
10694            Typ,
10695            Component_List (Type_Definition (Parent (Typ))),
10696            Governed_By   => Assoc_List,
10697            Into          => Comp_List,
10698            Report_Errors => Errors);
10699          pragma Assert (not Errors);
10700
10701          Create_All_Components;
10702
10703       --  If the subtype declaration is created for a tagged type derivation
10704       --  with constraints, we retrieve the record definition of the parent
10705       --  type to select the components of the proper variant.
10706
10707       elsif Is_Static
10708         and then Is_Tagged_Type (Typ)
10709         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
10710         and then
10711           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
10712         and then Is_Variant_Record (Parent_Type)
10713       then
10714          Collect_Fixed_Components (Typ);
10715
10716          Gather_Components (
10717            Typ,
10718            Component_List (Type_Definition (Parent (Parent_Type))),
10719            Governed_By   => Assoc_List,
10720            Into          => Comp_List,
10721            Report_Errors => Errors);
10722          pragma Assert (not Errors);
10723
10724          --  If the tagged derivation has a type extension, collect all the
10725          --  new components therein.
10726
10727          if Present
10728               (Record_Extension_Part (Type_Definition (Parent (Typ))))
10729          then
10730             Old_C := First_Component (Typ);
10731             while Present (Old_C) loop
10732                if Original_Record_Component (Old_C) = Old_C
10733                 and then Chars (Old_C) /= Name_uTag
10734                 and then Chars (Old_C) /= Name_uParent
10735                 and then Chars (Old_C) /= Name_uController
10736                then
10737                   Append_Elmt (Old_C, Comp_List);
10738                end if;
10739
10740                Next_Component (Old_C);
10741             end loop;
10742          end if;
10743
10744          Create_All_Components;
10745
10746       else
10747          --  If discriminants are not static, or if this is a multi-level type
10748          --  extension, we have to include all components of the parent type.
10749
10750          Old_C := First_Component (Typ);
10751          while Present (Old_C) loop
10752             New_C := Create_Component (Old_C);
10753
10754             Set_Etype
10755               (New_C,
10756                Constrain_Component_Type
10757                  (Old_C, Subt, Decl_Node, Typ, Constraints));
10758             Set_Is_Public (New_C, Is_Public (Subt));
10759
10760             Next_Component (Old_C);
10761          end loop;
10762       end if;
10763
10764       End_Scope;
10765    end Create_Constrained_Components;
10766
10767    ------------------------------------------
10768    -- Decimal_Fixed_Point_Type_Declaration --
10769    ------------------------------------------
10770
10771    procedure Decimal_Fixed_Point_Type_Declaration
10772      (T   : Entity_Id;
10773       Def : Node_Id)
10774    is
10775       Loc           : constant Source_Ptr := Sloc (Def);
10776       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
10777       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
10778       Implicit_Base : Entity_Id;
10779       Digs_Val      : Uint;
10780       Delta_Val     : Ureal;
10781       Scale_Val     : Uint;
10782       Bound_Val     : Ureal;
10783
10784    --  Start of processing for Decimal_Fixed_Point_Type_Declaration
10785
10786    begin
10787       Check_Restriction (No_Fixed_Point, Def);
10788
10789       --  Create implicit base type
10790
10791       Implicit_Base :=
10792         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
10793       Set_Etype (Implicit_Base, Implicit_Base);
10794
10795       --  Analyze and process delta expression
10796
10797       Analyze_And_Resolve (Delta_Expr, Universal_Real);
10798
10799       Check_Delta_Expression (Delta_Expr);
10800       Delta_Val := Expr_Value_R (Delta_Expr);
10801
10802       --  Check delta is power of 10, and determine scale value from it
10803
10804       declare
10805          Val : Ureal;
10806
10807       begin
10808          Scale_Val := Uint_0;
10809          Val := Delta_Val;
10810
10811          if Val < Ureal_1 then
10812             while Val < Ureal_1 loop
10813                Val := Val * Ureal_10;
10814                Scale_Val := Scale_Val + 1;
10815             end loop;
10816
10817             if Scale_Val > 18 then
10818                Error_Msg_N ("scale exceeds maximum value of 18", Def);
10819                Scale_Val := UI_From_Int (+18);
10820             end if;
10821
10822          else
10823             while Val > Ureal_1 loop
10824                Val := Val / Ureal_10;
10825                Scale_Val := Scale_Val - 1;
10826             end loop;
10827
10828             if Scale_Val < -18 then
10829                Error_Msg_N ("scale is less than minimum value of -18", Def);
10830                Scale_Val := UI_From_Int (-18);
10831             end if;
10832          end if;
10833
10834          if Val /= Ureal_1 then
10835             Error_Msg_N ("delta expression must be a power of 10", Def);
10836             Delta_Val := Ureal_10 ** (-Scale_Val);
10837          end if;
10838       end;
10839
10840       --  Set delta, scale and small (small = delta for decimal type)
10841
10842       Set_Delta_Value (Implicit_Base, Delta_Val);
10843       Set_Scale_Value (Implicit_Base, Scale_Val);
10844       Set_Small_Value (Implicit_Base, Delta_Val);
10845
10846       --  Analyze and process digits expression
10847
10848       Analyze_And_Resolve (Digs_Expr, Any_Integer);
10849       Check_Digits_Expression (Digs_Expr);
10850       Digs_Val := Expr_Value (Digs_Expr);
10851
10852       if Digs_Val > 18 then
10853          Digs_Val := UI_From_Int (+18);
10854          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
10855       end if;
10856
10857       Set_Digits_Value (Implicit_Base, Digs_Val);
10858       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
10859
10860       --  Set range of base type from digits value for now. This will be
10861       --  expanded to represent the true underlying base range by Freeze.
10862
10863       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
10864
10865       --  Set size to zero for now, size will be set at freeze time. We have
10866       --  to do this for ordinary fixed-point, because the size depends on
10867       --  the specified small, and we might as well do the same for decimal
10868       --  fixed-point.
10869
10870       Init_Size_Align (Implicit_Base);
10871
10872       --  If there are bounds given in the declaration use them as the
10873       --  bounds of the first named subtype.
10874
10875       if Present (Real_Range_Specification (Def)) then
10876          declare
10877             RRS      : constant Node_Id := Real_Range_Specification (Def);
10878             Low      : constant Node_Id := Low_Bound (RRS);
10879             High     : constant Node_Id := High_Bound (RRS);
10880             Low_Val  : Ureal;
10881             High_Val : Ureal;
10882
10883          begin
10884             Analyze_And_Resolve (Low, Any_Real);
10885             Analyze_And_Resolve (High, Any_Real);
10886             Check_Real_Bound (Low);
10887             Check_Real_Bound (High);
10888             Low_Val := Expr_Value_R (Low);
10889             High_Val := Expr_Value_R (High);
10890
10891             if Low_Val < (-Bound_Val) then
10892                Error_Msg_N
10893                  ("range low bound too small for digits value", Low);
10894                Low_Val := -Bound_Val;
10895             end if;
10896
10897             if High_Val > Bound_Val then
10898                Error_Msg_N
10899                  ("range high bound too large for digits value", High);
10900                High_Val := Bound_Val;
10901             end if;
10902
10903             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
10904          end;
10905
10906       --  If no explicit range, use range that corresponds to given
10907       --  digits value. This will end up as the final range for the
10908       --  first subtype.
10909
10910       else
10911          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
10912       end if;
10913
10914       --  Complete entity for first subtype
10915
10916       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
10917       Set_Etype          (T, Implicit_Base);
10918       Set_Size_Info      (T, Implicit_Base);
10919       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
10920       Set_Digits_Value   (T, Digs_Val);
10921       Set_Delta_Value    (T, Delta_Val);
10922       Set_Small_Value    (T, Delta_Val);
10923       Set_Scale_Value    (T, Scale_Val);
10924       Set_Is_Constrained (T);
10925    end Decimal_Fixed_Point_Type_Declaration;
10926
10927    ----------------------------------
10928    -- Derive_Interface_Subprograms --
10929    ----------------------------------
10930
10931    procedure Derive_Interface_Subprograms
10932      (Parent_Type : Entity_Id;
10933       Tagged_Type : Entity_Id;
10934       Ifaces_List : Elist_Id)
10935    is
10936       function Collect_Interface_Primitives
10937         (Tagged_Type : Entity_Id) return Elist_Id;
10938       --  Ada 2005 (AI-251): Collect the primitives of all the implemented
10939       --  interfaces.
10940
10941       function In_List (L : Elist_Id; Subp : Entity_Id) return Boolean;
10942       --  Determine if Subp already in the list L
10943
10944       procedure Remove_Homonym (E : Entity_Id);
10945       --  Removes E from the homonym chain
10946
10947       ----------------------------------
10948       -- Collect_Interface_Primitives --
10949       ----------------------------------
10950
10951       function Collect_Interface_Primitives
10952          (Tagged_Type : Entity_Id) return Elist_Id
10953       is
10954          Op_List     : constant Elist_Id := New_Elmt_List;
10955          Elmt        : Elmt_Id;
10956          Ifaces_List : Elist_Id;
10957          Iface_Elmt  : Elmt_Id;
10958          Prim        : Entity_Id;
10959
10960       begin
10961          pragma Assert (Is_Tagged_Type (Tagged_Type)
10962            and then Has_Abstract_Interfaces (Tagged_Type));
10963
10964          Collect_Abstract_Interfaces (Tagged_Type, Ifaces_List);
10965
10966          Iface_Elmt := First_Elmt (Ifaces_List);
10967          while Present (Iface_Elmt) loop
10968             Elmt := First_Elmt (Primitive_Operations (Node (Iface_Elmt)));
10969
10970             while Present (Elmt) loop
10971                Prim := Node (Elmt);
10972
10973                if not Is_Predefined_Dispatching_Operation (Prim) then
10974                   Append_Elmt (Prim, Op_List);
10975                end if;
10976
10977                Next_Elmt (Elmt);
10978             end loop;
10979
10980             Next_Elmt (Iface_Elmt);
10981          end loop;
10982
10983          return Op_List;
10984       end Collect_Interface_Primitives;
10985
10986       -------------
10987       -- In_List --
10988       -------------
10989
10990       function In_List (L : Elist_Id; Subp : Entity_Id) return Boolean is
10991          Elmt : Elmt_Id;
10992       begin
10993          Elmt := First_Elmt (L);
10994          while Present (Elmt) loop
10995             if Node (Elmt) = Subp then
10996                return True;
10997             end if;
10998
10999             Next_Elmt (Elmt);
11000          end loop;
11001
11002          return False;
11003       end In_List;
11004
11005       --------------------
11006       -- Remove_Homonym --
11007       --------------------
11008
11009       procedure Remove_Homonym (E : Entity_Id) is
11010          Prev  : Entity_Id := Empty;
11011          H     : Entity_Id;
11012
11013       begin
11014          if E = Current_Entity (E) then
11015             Set_Current_Entity (Homonym (E));
11016          else
11017             H := Current_Entity (E);
11018             while Present (H) and then H /= E loop
11019                Prev := H;
11020                H    := Homonym (H);
11021             end loop;
11022
11023             Set_Homonym (Prev, Homonym (E));
11024          end if;
11025       end Remove_Homonym;
11026
11027       --  Local Variables
11028
11029       E           : Entity_Id;
11030       Elmt        : Elmt_Id;
11031       Iface       : Entity_Id;
11032       Iface_Subp  : Entity_Id;
11033       New_Subp    : Entity_Id := Empty;
11034       Op_List     : Elist_Id;
11035       Parent_Base : Entity_Id;
11036       Subp        : Entity_Id;
11037
11038    --  Start of processing for Derive_Interface_Subprograms
11039
11040    begin
11041       if Ada_Version < Ada_05
11042         or else not Is_Record_Type (Tagged_Type)
11043         or else not Is_Tagged_Type (Tagged_Type)
11044         or else not Has_Abstract_Interfaces (Tagged_Type)
11045       then
11046          return;
11047       end if;
11048
11049       --  Add to the list of interface subprograms all the primitives inherited
11050       --  from abstract interfaces that are not immediate ancestors and also
11051       --  add their derivation to the list of interface primitives.
11052
11053       Op_List := Collect_Interface_Primitives (Tagged_Type);
11054
11055       Elmt := First_Elmt (Op_List);
11056       while Present (Elmt) loop
11057          Subp  := Node (Elmt);
11058          Iface := Find_Dispatching_Type (Subp);
11059
11060          if Is_Concurrent_Record_Type (Tagged_Type) then
11061             if not Present (Abstract_Interface_Alias (Subp)) then
11062                Derive_Subprogram (New_Subp, Subp, Tagged_Type, Iface);
11063                Append_Elmt (New_Subp, Ifaces_List);
11064             end if;
11065
11066          elsif not Is_Parent (Iface, Tagged_Type) then
11067             Derive_Subprogram (New_Subp, Subp, Tagged_Type, Iface);
11068             Append_Elmt (New_Subp, Ifaces_List);
11069          end if;
11070
11071          Next_Elmt (Elmt);
11072       end loop;
11073
11074       --  Complete the derivation of the interface subprograms. Assignate to
11075       --  each entity associated with abstract interfaces their aliased entity
11076       --  and complete their decoration as hidden interface entities that will
11077       --  be used later to build the secondary dispatch tables.
11078
11079       if not Is_Empty_Elmt_List (Ifaces_List) then
11080          if Ekind (Parent_Type) = E_Record_Type_With_Private
11081            and then Has_Discriminants (Parent_Type)
11082            and then Present (Full_View (Parent_Type))
11083          then
11084             Parent_Base := Full_View (Parent_Type);
11085          else
11086             Parent_Base := Parent_Type;
11087          end if;
11088
11089          Elmt := First_Elmt (Ifaces_List);
11090          while Present (Elmt) loop
11091             Iface_Subp := Node (Elmt);
11092
11093             --  Look for the first overriding entity in the homonym chain.
11094             --  In this way if we are in the private part of a package spec
11095             --  we get the last overriding subprogram.
11096
11097             E  := Current_Entity_In_Scope (Iface_Subp);
11098             while Present (E) loop
11099                if Is_Dispatching_Operation (E)
11100                  and then Scope (E) = Scope (Iface_Subp)
11101                  and then Type_Conformant (E, Iface_Subp)
11102                  and then not In_List (Ifaces_List, E)
11103                then
11104                   exit;
11105                end if;
11106
11107                E := Homonym (E);
11108             end loop;
11109
11110             --  Create an overriding entity if not found in the homonym chain
11111
11112             if not Present (E) then
11113                Derive_Subprogram
11114                  (E, Alias (Iface_Subp), Tagged_Type, Parent_Base);
11115
11116             elsif not In_List (Primitive_Operations (Tagged_Type), E) then
11117
11118                --  Inherit the operation from the private view
11119
11120                Append_Elmt (E, Primitive_Operations (Tagged_Type));
11121             end if;
11122
11123             --  Complete the decoration of the hidden interface entity
11124
11125             Set_Is_Hidden                (Iface_Subp);
11126             Set_Abstract_Interface_Alias (Iface_Subp, Alias (Iface_Subp));
11127             Set_Alias                    (Iface_Subp, E);
11128             Set_Is_Abstract_Subprogram   (Iface_Subp,
11129                                           Is_Abstract_Subprogram (E));
11130             Remove_Homonym               (Iface_Subp);
11131
11132             --  Hidden entities associated with interfaces must have set the
11133             --  Has_Delay_Freeze attribute to ensure that the corresponding
11134             --  entry of the secondary dispatch table is filled when such
11135             --  entity is frozen.
11136
11137             Set_Has_Delayed_Freeze (Iface_Subp);
11138
11139             Next_Elmt (Elmt);
11140          end loop;
11141       end if;
11142    end Derive_Interface_Subprograms;
11143
11144    -----------------------
11145    -- Derive_Subprogram --
11146    -----------------------
11147
11148    procedure Derive_Subprogram
11149      (New_Subp     : in out Entity_Id;
11150       Parent_Subp  : Entity_Id;
11151       Derived_Type : Entity_Id;
11152       Parent_Type  : Entity_Id;
11153       Actual_Subp  : Entity_Id := Empty)
11154    is
11155       Formal       : Entity_Id;
11156       New_Formal   : Entity_Id;
11157       Visible_Subp : Entity_Id := Parent_Subp;
11158
11159       function Is_Private_Overriding return Boolean;
11160       --  If Subp is a private overriding of a visible operation, the in-
11161       --  herited operation derives from the overridden op (even though
11162       --  its body is the overriding one) and the inherited operation is
11163       --  visible now. See sem_disp to see the details of the handling of
11164       --  the overridden subprogram, which is removed from the list of
11165       --  primitive operations of the type. The overridden subprogram is
11166       --  saved locally in Visible_Subp, and used to diagnose abstract
11167       --  operations that need overriding in the derived type.
11168
11169       procedure Replace_Type (Id, New_Id : Entity_Id);
11170       --  When the type is an anonymous access type, create a new access type
11171       --  designating the derived type.
11172
11173       procedure Set_Derived_Name;
11174       --  This procedure sets the appropriate Chars name for New_Subp. This
11175       --  is normally just a copy of the parent name. An exception arises for
11176       --  type support subprograms, where the name is changed to reflect the
11177       --  name of the derived type, e.g. if type foo is derived from type bar,
11178       --  then a procedure barDA is derived with a name fooDA.
11179
11180       ---------------------------
11181       -- Is_Private_Overriding --
11182       ---------------------------
11183
11184       function Is_Private_Overriding return Boolean is
11185          Prev : Entity_Id;
11186
11187       begin
11188          --  If the parent is not a dispatching operation there is no
11189          --  need to investigate overridings
11190
11191          if not Is_Dispatching_Operation (Parent_Subp) then
11192             return False;
11193          end if;
11194
11195          --  The visible operation that is overridden is a homonym of the
11196          --  parent subprogram. We scan the homonym chain to find the one
11197          --  whose alias is the subprogram we are deriving.
11198
11199          Prev := Current_Entity (Parent_Subp);
11200          while Present (Prev) loop
11201             if Ekind (Prev) = Ekind (Parent_Subp)
11202               and then Alias (Prev) = Parent_Subp
11203               and then Scope (Parent_Subp) = Scope (Prev)
11204               and then not Is_Hidden (Prev)
11205             then
11206                Visible_Subp := Prev;
11207                return True;
11208             end if;
11209
11210             Prev := Homonym (Prev);
11211          end loop;
11212
11213          return False;
11214       end Is_Private_Overriding;
11215
11216       ------------------
11217       -- Replace_Type --
11218       ------------------
11219
11220       procedure Replace_Type (Id, New_Id : Entity_Id) is
11221          Acc_Type : Entity_Id;
11222          Par      : constant Node_Id := Parent (Derived_Type);
11223
11224       begin
11225          --  When the type is an anonymous access type, create a new access
11226          --  type designating the derived type. This itype must be elaborated
11227          --  at the point of the derivation, not on subsequent calls that may
11228          --  be out of the proper scope for Gigi, so we insert a reference to
11229          --  it after the derivation.
11230
11231          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
11232             declare
11233                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
11234
11235             begin
11236                if Ekind (Desig_Typ) = E_Record_Type_With_Private
11237                  and then Present (Full_View (Desig_Typ))
11238                  and then not Is_Private_Type (Parent_Type)
11239                then
11240                   Desig_Typ := Full_View (Desig_Typ);
11241                end if;
11242
11243                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
11244
11245                   --  Ada 2005 (AI-251): Handle also derivations of abstract
11246                   --  interface primitives.
11247
11248                  or else (Is_Interface (Desig_Typ)
11249                           and then not Is_Class_Wide_Type (Desig_Typ))
11250                then
11251                   Acc_Type := New_Copy (Etype (Id));
11252                   Set_Etype (Acc_Type, Acc_Type);
11253                   Set_Scope (Acc_Type, New_Subp);
11254
11255                   --  Compute size of anonymous access type
11256
11257                   if Is_Array_Type (Desig_Typ)
11258                     and then not Is_Constrained (Desig_Typ)
11259                   then
11260                      Init_Size (Acc_Type, 2 * System_Address_Size);
11261                   else
11262                      Init_Size (Acc_Type, System_Address_Size);
11263                   end if;
11264
11265                   Init_Alignment (Acc_Type);
11266                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
11267
11268                   Set_Etype (New_Id, Acc_Type);
11269                   Set_Scope (New_Id, New_Subp);
11270
11271                   --  Create a reference to it
11272                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
11273
11274                else
11275                   Set_Etype (New_Id, Etype (Id));
11276                end if;
11277             end;
11278
11279          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
11280            or else
11281              (Ekind (Etype (Id)) = E_Record_Type_With_Private
11282                and then Present (Full_View (Etype (Id)))
11283                and then
11284                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
11285          then
11286             --  Constraint checks on formals are generated during expansion,
11287             --  based on the signature of the original subprogram. The bounds
11288             --  of the derived type are not relevant, and thus we can use
11289             --  the base type for the formals. However, the return type may be
11290             --  used in a context that requires that the proper static bounds
11291             --  be used (a case statement, for example)  and for those cases
11292             --  we must use the derived type (first subtype), not its base.
11293
11294             --  If the derived_type_definition has no constraints, we know that
11295             --  the derived type has the same constraints as the first subtype
11296             --  of the parent, and we can also use it rather than its base,
11297             --  which can lead to more efficient code.
11298
11299             if Etype (Id) = Parent_Type then
11300                if Is_Scalar_Type (Parent_Type)
11301                  and then
11302                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
11303                then
11304                   Set_Etype (New_Id, Derived_Type);
11305
11306                elsif Nkind (Par) = N_Full_Type_Declaration
11307                  and then
11308                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
11309                  and then
11310                    Is_Entity_Name
11311                      (Subtype_Indication (Type_Definition (Par)))
11312                then
11313                   Set_Etype (New_Id, Derived_Type);
11314
11315                else
11316                   Set_Etype (New_Id, Base_Type (Derived_Type));
11317                end if;
11318
11319             else
11320                Set_Etype (New_Id, Base_Type (Derived_Type));
11321             end if;
11322
11323          --  Ada 2005 (AI-251): Handle derivations of abstract interface
11324          --  primitives.
11325
11326          elsif Is_Interface (Etype (Id))
11327            and then not Is_Class_Wide_Type (Etype (Id))
11328          then
11329             Set_Etype (New_Id, Derived_Type);
11330
11331          else
11332             Set_Etype (New_Id, Etype (Id));
11333          end if;
11334       end Replace_Type;
11335
11336       ----------------------
11337       -- Set_Derived_Name --
11338       ----------------------
11339
11340       procedure Set_Derived_Name is
11341          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
11342       begin
11343          if Nm = TSS_Null then
11344             Set_Chars (New_Subp, Chars (Parent_Subp));
11345          else
11346             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
11347          end if;
11348       end Set_Derived_Name;
11349
11350    --  Start of processing for Derive_Subprogram
11351
11352    begin
11353       New_Subp :=
11354          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
11355       Set_Ekind (New_Subp, Ekind (Parent_Subp));
11356
11357       --  Check whether the inherited subprogram is a private operation that
11358       --  should be inherited but not yet made visible. Such subprograms can
11359       --  become visible at a later point (e.g., the private part of a public
11360       --  child unit) via Declare_Inherited_Private_Subprograms. If the
11361       --  following predicate is true, then this is not such a private
11362       --  operation and the subprogram simply inherits the name of the parent
11363       --  subprogram. Note the special check for the names of controlled
11364       --  operations, which are currently exempted from being inherited with
11365       --  a hidden name because they must be findable for generation of
11366       --  implicit run-time calls.
11367
11368       if not Is_Hidden (Parent_Subp)
11369         or else Is_Internal (Parent_Subp)
11370         or else Is_Private_Overriding
11371         or else Is_Internal_Name (Chars (Parent_Subp))
11372         or else Chars (Parent_Subp) = Name_Initialize
11373         or else Chars (Parent_Subp) = Name_Adjust
11374         or else Chars (Parent_Subp) = Name_Finalize
11375       then
11376          Set_Derived_Name;
11377
11378       --  If parent is hidden, this can be a regular derivation if the
11379       --  parent is immediately visible in a non-instantiating context,
11380       --  or if we are in the private part of an instance. This test
11381       --  should still be refined ???
11382
11383       --  The test for In_Instance_Not_Visible avoids inheriting the derived
11384       --  operation as a non-visible operation in cases where the parent
11385       --  subprogram might not be visible now, but was visible within the
11386       --  original generic, so it would be wrong to make the inherited
11387       --  subprogram non-visible now. (Not clear if this test is fully
11388       --  correct; are there any cases where we should declare the inherited
11389       --  operation as not visible to avoid it being overridden, e.g., when
11390       --  the parent type is a generic actual with private primitives ???)
11391
11392       --  (they should be treated the same as other private inherited
11393       --  subprograms, but it's not clear how to do this cleanly). ???
11394
11395       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
11396               and then Is_Immediately_Visible (Parent_Subp)
11397               and then not In_Instance)
11398         or else In_Instance_Not_Visible
11399       then
11400          Set_Derived_Name;
11401
11402       --  Ada 2005 (AI-251): Hidden entity associated with abstract interface
11403       --  primitive
11404
11405       elsif Present (Abstract_Interface_Alias (Parent_Subp)) then
11406          Set_Derived_Name;
11407
11408       --  The type is inheriting a private operation, so enter
11409       --  it with a special name so it can't be overridden.
11410
11411       else
11412          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
11413       end if;
11414
11415       Set_Parent (New_Subp, Parent (Derived_Type));
11416       Replace_Type (Parent_Subp, New_Subp);
11417       Conditional_Delay (New_Subp, Parent_Subp);
11418
11419       Formal := First_Formal (Parent_Subp);
11420       while Present (Formal) loop
11421          New_Formal := New_Copy (Formal);
11422
11423          --  Normally we do not go copying parents, but in the case of
11424          --  formals, we need to link up to the declaration (which is the
11425          --  parameter specification), and it is fine to link up to the
11426          --  original formal's parameter specification in this case.
11427
11428          Set_Parent (New_Formal, Parent (Formal));
11429
11430          Append_Entity (New_Formal, New_Subp);
11431
11432          Replace_Type (Formal, New_Formal);
11433          Next_Formal (Formal);
11434       end loop;
11435
11436       --  If this derivation corresponds to a tagged generic actual, then
11437       --  primitive operations rename those of the actual. Otherwise the
11438       --  primitive operations rename those of the parent type, If the
11439       --  parent renames an intrinsic operator, so does the new subprogram.
11440       --  We except concatenation, which is always properly typed, and does
11441       --  not get expanded as other intrinsic operations.
11442
11443       if No (Actual_Subp) then
11444          if Is_Intrinsic_Subprogram (Parent_Subp) then
11445             Set_Is_Intrinsic_Subprogram (New_Subp);
11446
11447             if Present (Alias (Parent_Subp))
11448               and then Chars (Parent_Subp) /= Name_Op_Concat
11449             then
11450                Set_Alias (New_Subp, Alias (Parent_Subp));
11451             else
11452                Set_Alias (New_Subp, Parent_Subp);
11453             end if;
11454
11455          else
11456             Set_Alias (New_Subp, Parent_Subp);
11457          end if;
11458
11459       else
11460          Set_Alias (New_Subp, Actual_Subp);
11461       end if;
11462
11463       --  Derived subprograms of a tagged type must inherit the convention
11464       --  of the parent subprogram (a requirement of AI-117). Derived
11465       --  subprograms of untagged types simply get convention Ada by default.
11466
11467       if Is_Tagged_Type (Derived_Type) then
11468          Set_Convention (New_Subp, Convention (Parent_Subp));
11469       end if;
11470
11471       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
11472       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
11473
11474       if Ekind (Parent_Subp) = E_Procedure then
11475          Set_Is_Valued_Procedure
11476            (New_Subp, Is_Valued_Procedure (Parent_Subp));
11477       end if;
11478
11479       --  No_Return must be inherited properly. If this is overridden in the
11480       --  case of a dispatching operation, then a check is made in Sem_Disp
11481       --  that the overriding operation is also No_Return (no such check is
11482       --  required for the case of non-dispatching operation.
11483
11484       Set_No_Return (New_Subp, No_Return (Parent_Subp));
11485
11486       --  A derived function with a controlling result is abstract. If the
11487       --  Derived_Type is a nonabstract formal generic derived type, then
11488       --  inherited operations are not abstract: the required check is done at
11489       --  instantiation time. If the derivation is for a generic actual, the
11490       --  function is not abstract unless the actual is.
11491
11492       if Is_Generic_Type (Derived_Type)
11493         and then not Is_Abstract_Type (Derived_Type)
11494       then
11495          null;
11496
11497       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
11498       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
11499
11500       elsif Ada_Version >= Ada_05
11501         and then (Is_Abstract_Subprogram (Alias (New_Subp))
11502                    or else (Is_Tagged_Type (Derived_Type)
11503                             and then Etype (New_Subp) = Derived_Type
11504                             and then not Is_Null_Extension (Derived_Type))
11505                    or else (Is_Tagged_Type (Derived_Type)
11506                             and then Ekind (Etype (New_Subp)) =
11507                                                        E_Anonymous_Access_Type
11508                             and then Designated_Type (Etype (New_Subp)) =
11509                                                        Derived_Type
11510                             and then not Is_Null_Extension (Derived_Type)))
11511         and then No (Actual_Subp)
11512       then
11513          if not Is_Tagged_Type (Derived_Type)
11514            or else Is_Abstract_Type (Derived_Type)
11515            or else Is_Abstract_Subprogram (Alias (New_Subp))
11516          then
11517             Set_Is_Abstract_Subprogram (New_Subp);
11518          else
11519             Set_Requires_Overriding (New_Subp);
11520          end if;
11521
11522       elsif Ada_Version < Ada_05
11523         and then (Is_Abstract_Subprogram (Alias (New_Subp))
11524                    or else (Is_Tagged_Type (Derived_Type)
11525                              and then Etype (New_Subp) = Derived_Type
11526                              and then No (Actual_Subp)))
11527       then
11528          Set_Is_Abstract_Subprogram (New_Subp);
11529
11530       --  Finally, if the parent type is abstract we must verify that all
11531       --  inherited operations are either non-abstract or overridden, or
11532       --  that the derived type itself is abstract (this check is performed
11533       --  at the end of a package declaration, in Check_Abstract_Overriding).
11534       --  A private overriding in the parent type will not be visible in the
11535       --  derivation if we are not in an inner package or in a child unit of
11536       --  the parent type, in which case the abstractness of the inherited
11537       --  operation is carried to the new subprogram.
11538
11539       elsif Is_Abstract_Type (Parent_Type)
11540         and then not In_Open_Scopes (Scope (Parent_Type))
11541         and then Is_Private_Overriding
11542         and then Is_Abstract_Subprogram (Visible_Subp)
11543       then
11544          if No (Actual_Subp) then
11545             Set_Alias (New_Subp, Visible_Subp);
11546             Set_Is_Abstract_Subprogram
11547               (New_Subp, True);
11548          else
11549             --  If this is a derivation for an instance of a formal derived
11550             --  type, abstractness comes from the primitive operation of the
11551             --  actual, not from the operation inherited from the ancestor.
11552
11553             Set_Is_Abstract_Subprogram
11554               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
11555          end if;
11556       end if;
11557
11558       New_Overloaded_Entity (New_Subp, Derived_Type);
11559
11560       --  Check for case of a derived subprogram for the instantiation of a
11561       --  formal derived tagged type, if so mark the subprogram as dispatching
11562       --  and inherit the dispatching attributes of the parent subprogram. The
11563       --  derived subprogram is effectively renaming of the actual subprogram,
11564       --  so it needs to have the same attributes as the actual.
11565
11566       if Present (Actual_Subp)
11567         and then Is_Dispatching_Operation (Parent_Subp)
11568       then
11569          Set_Is_Dispatching_Operation (New_Subp);
11570
11571          if Present (DTC_Entity (Parent_Subp)) then
11572             Set_DTC_Entity (New_Subp, DTC_Entity (Parent_Subp));
11573             Set_DT_Position (New_Subp, DT_Position (Parent_Subp));
11574          end if;
11575       end if;
11576
11577       --  Indicate that a derived subprogram does not require a body and that
11578       --  it does not require processing of default expressions.
11579
11580       Set_Has_Completion (New_Subp);
11581       Set_Default_Expressions_Processed (New_Subp);
11582
11583       if Ekind (New_Subp) = E_Function then
11584          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
11585       end if;
11586    end Derive_Subprogram;
11587
11588    ------------------------
11589    -- Derive_Subprograms --
11590    ------------------------
11591
11592    procedure Derive_Subprograms
11593      (Parent_Type           : Entity_Id;
11594       Derived_Type          : Entity_Id;
11595       Generic_Actual        : Entity_Id := Empty)
11596    is
11597       Op_List      : constant Elist_Id :=
11598                        Collect_Primitive_Operations (Parent_Type);
11599       Ifaces_List  : constant Elist_Id := New_Elmt_List;
11600       Act_List     : Elist_Id;
11601       Act_Elmt     : Elmt_Id;
11602       Elmt         : Elmt_Id;
11603       New_Subp     : Entity_Id := Empty;
11604       Parent_Base  : Entity_Id;
11605       Subp         : Entity_Id;
11606
11607    begin
11608       if Ekind (Parent_Type) = E_Record_Type_With_Private
11609         and then Has_Discriminants (Parent_Type)
11610         and then Present (Full_View (Parent_Type))
11611       then
11612          Parent_Base := Full_View (Parent_Type);
11613       else
11614          Parent_Base := Parent_Type;
11615       end if;
11616
11617       --  Derive primitives inherited from the parent
11618
11619       if Present (Generic_Actual) then
11620          Act_List := Collect_Primitive_Operations (Generic_Actual);
11621          Act_Elmt := First_Elmt (Act_List);
11622       else
11623          Act_Elmt := No_Elmt;
11624       end if;
11625
11626       --  Literals are derived earlier in the process of building the derived
11627       --  type, and are skipped here.
11628
11629       Elmt := First_Elmt (Op_List);
11630       while Present (Elmt) loop
11631          Subp := Node (Elmt);
11632
11633          if Ekind (Subp) /= E_Enumeration_Literal then
11634
11635             if Ada_Version >= Ada_05
11636               and then Present (Abstract_Interface_Alias (Subp))
11637             then
11638                null;
11639
11640             elsif No (Generic_Actual) then
11641                Derive_Subprogram (New_Subp, Subp, Derived_Type, Parent_Base);
11642
11643                --  Ada 2005 (AI-251): Add the derivation of an abstract
11644                --  interface primitive to the list of entities to which
11645                --  we have to associate an aliased entity.
11646
11647                if Ada_Version >= Ada_05
11648                  and then Is_Dispatching_Operation (Subp)
11649                  and then Present (Find_Dispatching_Type (Subp))
11650                  and then Is_Interface (Find_Dispatching_Type (Subp))
11651                  and then not Is_Predefined_Dispatching_Operation (Subp)
11652                then
11653                   Append_Elmt (New_Subp, Ifaces_List);
11654                end if;
11655
11656             else
11657                --  If the generic parent type is present, the derived type
11658                --  is an instance of a formal derived type, and within the
11659                --  instance its operations are those of the actual. We derive
11660                --  from the formal type but make the inherited operations
11661                --  aliases of the corresponding operations of the actual.
11662
11663                if Is_Interface (Parent_Type)
11664                  and then Root_Type (Derived_Type) /= Parent_Type
11665                then
11666                   --  Find the corresponding operation in the generic actual.
11667                   --  Given that the actual is not a direct descendant of the
11668                   --  parent, as in Ada 95, the primitives are not necessarily
11669                   --  in the same order, so we have to traverse the list of
11670                   --  primitive operations of the actual to find the one that
11671                   --  implements the interface operation.
11672
11673                   --  Note that if the parent type is the direct ancestor of
11674                   --  the derived type, then even if it is an interface the
11675                   --  operations are inherited from the primary dispatch table
11676                   --  and are in the proper order.
11677
11678                   Act_Elmt := First_Elmt (Act_List);
11679                   while Present (Act_Elmt) loop
11680                      exit when
11681                        Abstract_Interface_Alias (Node (Act_Elmt)) = Subp;
11682                      Next_Elmt (Act_Elmt);
11683                   end loop;
11684                end if;
11685
11686                --  If the formal is not an interface, the actual is a direct
11687                --  descendant and the common  primitive operations appear in
11688                --  the same order.
11689
11690                Derive_Subprogram
11691                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
11692
11693                if Present (Act_Elmt) then
11694                   Next_Elmt (Act_Elmt);
11695                end if;
11696             end if;
11697          end if;
11698
11699          Next_Elmt (Elmt);
11700       end loop;
11701
11702       --  Inherit additional operations from progenitor interfaces.
11703       --  However, if the derived type is a generic actual, there
11704       --  are not new primitive operations for the type, because
11705       --  it has those of the actual, so nothing needs to be done.
11706       --  The renamings generated above are not primitive operations,
11707       --  and their purpose is simply to make the proper operations
11708       --  visible within an instantiation.
11709
11710       if Ada_Version >= Ada_05
11711         and then Is_Tagged_Type (Derived_Type)
11712         and then No (Generic_Actual)
11713       then
11714          Derive_Interface_Subprograms (Parent_Type, Derived_Type, Ifaces_List);
11715       end if;
11716    end Derive_Subprograms;
11717
11718    --------------------------------
11719    -- Derived_Standard_Character --
11720    --------------------------------
11721
11722    procedure Derived_Standard_Character
11723      (N            : Node_Id;
11724       Parent_Type  : Entity_Id;
11725       Derived_Type : Entity_Id)
11726    is
11727       Loc           : constant Source_Ptr := Sloc (N);
11728       Def           : constant Node_Id    := Type_Definition (N);
11729       Indic         : constant Node_Id    := Subtype_Indication (Def);
11730       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
11731       Implicit_Base : constant Entity_Id  :=
11732                         Create_Itype
11733                           (E_Enumeration_Type, N, Derived_Type, 'B');
11734
11735       Lo : Node_Id;
11736       Hi : Node_Id;
11737
11738    begin
11739       Discard_Node (Process_Subtype (Indic, N));
11740
11741       Set_Etype     (Implicit_Base, Parent_Base);
11742       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
11743       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
11744
11745       Set_Is_Character_Type  (Implicit_Base, True);
11746       Set_Has_Delayed_Freeze (Implicit_Base);
11747
11748       --  The bounds of the implicit base are the bounds of the parent base.
11749       --  Note that their type is the parent base.
11750
11751       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
11752       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
11753
11754       Set_Scalar_Range (Implicit_Base,
11755         Make_Range (Loc,
11756           Low_Bound  => Lo,
11757           High_Bound => Hi));
11758
11759       Conditional_Delay (Derived_Type, Parent_Type);
11760
11761       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
11762       Set_Etype (Derived_Type, Implicit_Base);
11763       Set_Size_Info         (Derived_Type, Parent_Type);
11764
11765       if Unknown_RM_Size (Derived_Type) then
11766          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
11767       end if;
11768
11769       Set_Is_Character_Type (Derived_Type, True);
11770
11771       if Nkind (Indic) /= N_Subtype_Indication then
11772
11773          --  If no explicit constraint, the bounds are those
11774          --  of the parent type.
11775
11776          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
11777          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
11778          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
11779       end if;
11780
11781       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
11782
11783       --  Because the implicit base is used in the conversion of the bounds,
11784       --  we have to freeze it now. This is similar to what is done for
11785       --  numeric types, and it equally suspicious, but otherwise a non-
11786       --  static bound will have a reference to an unfrozen type, which is
11787       --  rejected by Gigi (???). This requires specific care for definition
11788       --  of stream attributes. For details, see comments at the end of
11789       --  Build_Derived_Numeric_Type.
11790
11791       Freeze_Before (N, Implicit_Base);
11792    end Derived_Standard_Character;
11793
11794    ------------------------------
11795    -- Derived_Type_Declaration --
11796    ------------------------------
11797
11798    procedure Derived_Type_Declaration
11799      (T             : Entity_Id;
11800       N             : Node_Id;
11801       Is_Completion : Boolean)
11802    is
11803       Parent_Type  : Entity_Id;
11804
11805       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
11806       --  Check whether the parent type is a generic formal, or derives
11807       --  directly or indirectly from one.
11808
11809       ------------------------
11810       -- Comes_From_Generic --
11811       ------------------------
11812
11813       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
11814       begin
11815          if Is_Generic_Type (Typ) then
11816             return True;
11817
11818          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
11819             return True;
11820
11821          elsif Is_Private_Type (Typ)
11822            and then Present (Full_View (Typ))
11823            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
11824          then
11825             return True;
11826
11827          elsif Is_Generic_Actual_Type (Typ) then
11828             return True;
11829
11830          else
11831             return False;
11832          end if;
11833       end Comes_From_Generic;
11834
11835       --  Local variables
11836
11837       Def          : constant Node_Id := Type_Definition (N);
11838       Iface_Def    : Node_Id;
11839       Indic        : constant Node_Id := Subtype_Indication (Def);
11840       Extension    : constant Node_Id := Record_Extension_Part (Def);
11841       Parent_Node  : Node_Id;
11842       Parent_Scope : Entity_Id;
11843       Taggd        : Boolean;
11844
11845    --  Start of processing for Derived_Type_Declaration
11846
11847    begin
11848       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
11849
11850       --  Ada 2005 (AI-251): In case of interface derivation check that the
11851       --  parent is also an interface.
11852
11853       if Interface_Present (Def) then
11854          if not Is_Interface (Parent_Type) then
11855             Error_Msg_NE
11856               ("(Ada 2005) & must be an interface", Indic, Parent_Type);
11857
11858          else
11859             Parent_Node := Parent (Base_Type (Parent_Type));
11860             Iface_Def   := Type_Definition (Parent_Node);
11861
11862             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
11863             --  other limited interfaces.
11864
11865             if Limited_Present (Def) then
11866                if Limited_Present (Iface_Def) then
11867                   null;
11868
11869                elsif Protected_Present (Iface_Def) then
11870                   Error_Msg_N
11871                     ("(Ada 2005) limited interface cannot "
11872                      & "inherit from protected interface", Indic);
11873
11874                elsif Synchronized_Present (Iface_Def) then
11875                   Error_Msg_N
11876                     ("(Ada 2005) limited interface cannot "
11877                      & "inherit from synchronized interface", Indic);
11878
11879                elsif Task_Present (Iface_Def) then
11880                   Error_Msg_N
11881                     ("(Ada 2005) limited interface cannot "
11882                      & "inherit from task interface", Indic);
11883
11884                else
11885                   Error_Msg_N
11886                     ("(Ada 2005) limited interface cannot "
11887                      & "inherit from non-limited interface", Indic);
11888                end if;
11889
11890             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
11891             --  from non-limited or limited interfaces.
11892
11893             elsif not Protected_Present (Def)
11894               and then not Synchronized_Present (Def)
11895               and then not Task_Present (Def)
11896             then
11897                if Limited_Present (Iface_Def) then
11898                   null;
11899
11900                elsif Protected_Present (Iface_Def) then
11901                   Error_Msg_N
11902                     ("(Ada 2005) non-limited interface cannot "
11903                      & "inherit from protected interface", Indic);
11904
11905                elsif Synchronized_Present (Iface_Def) then
11906                   Error_Msg_N
11907                     ("(Ada 2005) non-limited interface cannot "
11908                      & "inherit from synchronized interface", Indic);
11909
11910                elsif Task_Present (Iface_Def) then
11911                   Error_Msg_N
11912                     ("(Ada 2005) non-limited interface cannot "
11913                      & "inherit from task interface", Indic);
11914
11915                else
11916                   null;
11917                end if;
11918             end if;
11919          end if;
11920       end if;
11921
11922       if Is_Tagged_Type (Parent_Type)
11923         and then Is_Concurrent_Type (Parent_Type)
11924         and then not Is_Interface (Parent_Type)
11925       then
11926          Error_Msg_N
11927            ("parent type of a record extension cannot be "
11928             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
11929          Set_Etype (T, Any_Type);
11930          return;
11931       end if;
11932
11933       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
11934       --  interfaces
11935
11936       if Is_Tagged_Type (Parent_Type)
11937         and then Is_Non_Empty_List (Interface_List (Def))
11938       then
11939          declare
11940             Intf : Node_Id;
11941             T    : Entity_Id;
11942
11943          begin
11944             Intf := First (Interface_List (Def));
11945             while Present (Intf) loop
11946                T := Find_Type_Of_Subtype_Indic (Intf);
11947
11948                if not Is_Interface (T) then
11949                   Error_Msg_NE ("(Ada 2005) & must be an interface", Intf, T);
11950
11951                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
11952                --  a limited type from having a nonlimited progenitor.
11953
11954                elsif (Limited_Present (Def)
11955                        or else (not Is_Interface (Parent_Type)
11956                                  and then Is_Limited_Type (Parent_Type)))
11957                  and then not Is_Limited_Interface (T)
11958                then
11959                   Error_Msg_NE
11960                    ("progenitor interface& of limited type must be limited",
11961                      N, T);
11962                end if;
11963
11964                Next (Intf);
11965             end loop;
11966          end;
11967       end if;
11968
11969       if Parent_Type = Any_Type
11970         or else Etype (Parent_Type) = Any_Type
11971         or else (Is_Class_Wide_Type (Parent_Type)
11972                    and then Etype (Parent_Type) = T)
11973       then
11974          --  If Parent_Type is undefined or illegal, make new type into a
11975          --  subtype of Any_Type, and set a few attributes to prevent cascaded
11976          --  errors. If this is a self-definition, emit error now.
11977
11978          if T = Parent_Type
11979            or else T = Etype (Parent_Type)
11980          then
11981             Error_Msg_N ("type cannot be used in its own definition", Indic);
11982          end if;
11983
11984          Set_Ekind        (T, Ekind (Parent_Type));
11985          Set_Etype        (T, Any_Type);
11986          Set_Scalar_Range (T, Scalar_Range (Any_Type));
11987
11988          if Is_Tagged_Type (T) then
11989             Set_Primitive_Operations (T, New_Elmt_List);
11990          end if;
11991
11992          return;
11993       end if;
11994
11995       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
11996       --  an interface is special because the list of interfaces in the full
11997       --  view can be given in any order. For example:
11998
11999       --     type A is interface;
12000       --     type B is interface and A;
12001       --     type D is new B with private;
12002       --   private
12003       --     type D is new A and B with null record; -- 1 --
12004
12005       --  In this case we perform the following transformation of -1-:
12006
12007       --     type D is new B and A with null record;
12008
12009       --  If the parent of the full-view covers the parent of the partial-view
12010       --  we have two possible cases:
12011
12012       --     1) They have the same parent
12013       --     2) The parent of the full-view implements some further interfaces
12014
12015       --  In both cases we do not need to perform the transformation. In the
12016       --  first case the source program is correct and the transformation is
12017       --  not needed; in the second case the source program does not fulfill
12018       --  the no-hidden interfaces rule (AI-396) and the error will be reported
12019       --  later.
12020
12021       --  This transformation not only simplifies the rest of the analysis of
12022       --  this type declaration but also simplifies the correct generation of
12023       --  the object layout to the expander.
12024
12025       if In_Private_Part (Current_Scope)
12026         and then Is_Interface (Parent_Type)
12027       then
12028          declare
12029             Iface               : Node_Id;
12030             Partial_View        : Entity_Id;
12031             Partial_View_Parent : Entity_Id;
12032             New_Iface           : Node_Id;
12033
12034          begin
12035             --  Look for the associated private type declaration
12036
12037             Partial_View := First_Entity (Current_Scope);
12038             loop
12039                exit when No (Partial_View)
12040                  or else (Has_Private_Declaration (Partial_View)
12041                            and then Full_View (Partial_View) = T);
12042
12043                Next_Entity (Partial_View);
12044             end loop;
12045
12046             --  If the partial view was not found then the source code has
12047             --  errors and the transformation is not needed.
12048
12049             if Present (Partial_View) then
12050                Partial_View_Parent := Etype (Partial_View);
12051
12052                --  If the parent of the full-view covers the parent of the
12053                --  partial-view we have nothing else to do.
12054
12055                if Interface_Present_In_Ancestor
12056                     (Parent_Type, Partial_View_Parent)
12057                then
12058                   null;
12059
12060                --  Traverse the list of interfaces of the full-view to look
12061                --  for the parent of the partial-view and perform the tree
12062                --  transformation.
12063
12064                else
12065                   Iface := First (Interface_List (Def));
12066                   while Present (Iface) loop
12067                      if Etype (Iface) = Etype (Partial_View) then
12068                         Rewrite (Subtype_Indication (Def),
12069                           New_Copy (Subtype_Indication
12070                                      (Parent (Partial_View))));
12071
12072                         New_Iface := Make_Identifier (Sloc (N),
12073                                        Chars (Parent_Type));
12074                         Append (New_Iface, Interface_List (Def));
12075
12076                         --  Analyze the transformed code
12077
12078                         Derived_Type_Declaration (T, N, Is_Completion);
12079                         return;
12080                      end if;
12081
12082                      Next (Iface);
12083                   end loop;
12084                end if;
12085             end if;
12086          end;
12087       end if;
12088
12089       --  Only composite types other than array types are allowed to have
12090       --  discriminants.
12091
12092       if Present (Discriminant_Specifications (N))
12093         and then (Is_Elementary_Type (Parent_Type)
12094                   or else Is_Array_Type (Parent_Type))
12095         and then not Error_Posted (N)
12096       then
12097          Error_Msg_N
12098            ("elementary or array type cannot have discriminants",
12099             Defining_Identifier (First (Discriminant_Specifications (N))));
12100          Set_Has_Discriminants (T, False);
12101       end if;
12102
12103       --  In Ada 83, a derived type defined in a package specification cannot
12104       --  be used for further derivation until the end of its visible part.
12105       --  Note that derivation in the private part of the package is allowed.
12106
12107       if Ada_Version = Ada_83
12108         and then Is_Derived_Type (Parent_Type)
12109         and then In_Visible_Part (Scope (Parent_Type))
12110       then
12111          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
12112             Error_Msg_N
12113               ("(Ada 83): premature use of type for derivation", Indic);
12114          end if;
12115       end if;
12116
12117       --  Check for early use of incomplete or private type
12118
12119       if Ekind (Parent_Type) = E_Void
12120         or else Ekind (Parent_Type) = E_Incomplete_Type
12121       then
12122          Error_Msg_N ("premature derivation of incomplete type", Indic);
12123          return;
12124
12125       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
12126               and then not Comes_From_Generic (Parent_Type))
12127         or else Has_Private_Component (Parent_Type)
12128       then
12129          --  The ancestor type of a formal type can be incomplete, in which
12130          --  case only the operations of the partial view are available in
12131          --  the generic. Subsequent checks may be required when the full
12132          --  view is analyzed, to verify that derivation from a tagged type
12133          --  has an extension.
12134
12135          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
12136             null;
12137
12138          elsif No (Underlying_Type (Parent_Type))
12139            or else Has_Private_Component (Parent_Type)
12140          then
12141             Error_Msg_N
12142               ("premature derivation of derived or private type", Indic);
12143
12144             --  Flag the type itself as being in error, this prevents some
12145             --  nasty problems with subsequent uses of the malformed type.
12146
12147             Set_Error_Posted (T);
12148
12149          --  Check that within the immediate scope of an untagged partial
12150          --  view it's illegal to derive from the partial view if the
12151          --  full view is tagged. (7.3(7))
12152
12153          --  We verify that the Parent_Type is a partial view by checking
12154          --  that it is not a Full_Type_Declaration (i.e. a private type or
12155          --  private extension declaration), to distinguish a partial view
12156          --  from  a derivation from a private type which also appears as
12157          --  E_Private_Type.
12158
12159          elsif Present (Full_View (Parent_Type))
12160            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
12161            and then not Is_Tagged_Type (Parent_Type)
12162            and then Is_Tagged_Type (Full_View (Parent_Type))
12163          then
12164             Parent_Scope := Scope (T);
12165             while Present (Parent_Scope)
12166               and then Parent_Scope /= Standard_Standard
12167             loop
12168                if Parent_Scope = Scope (Parent_Type) then
12169                   Error_Msg_N
12170                     ("premature derivation from type with tagged full view",
12171                      Indic);
12172                end if;
12173
12174                Parent_Scope := Scope (Parent_Scope);
12175             end loop;
12176          end if;
12177       end if;
12178
12179       --  Check that form of derivation is appropriate
12180
12181       Taggd := Is_Tagged_Type (Parent_Type);
12182
12183       --  Perhaps the parent type should be changed to the class-wide type's
12184       --  specific type in this case to prevent cascading errors ???
12185
12186       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
12187          Error_Msg_N ("parent type must not be a class-wide type", Indic);
12188          return;
12189       end if;
12190
12191       if Present (Extension) and then not Taggd then
12192          Error_Msg_N
12193            ("type derived from untagged type cannot have extension", Indic);
12194
12195       elsif No (Extension) and then Taggd then
12196
12197          --  If this declaration is within a private part (or body) of a
12198          --  generic instantiation then the derivation is allowed (the parent
12199          --  type can only appear tagged in this case if it's a generic actual
12200          --  type, since it would otherwise have been rejected in the analysis
12201          --  of the generic template).
12202
12203          if not Is_Generic_Actual_Type (Parent_Type)
12204            or else In_Visible_Part (Scope (Parent_Type))
12205          then
12206             Error_Msg_N
12207               ("type derived from tagged type must have extension", Indic);
12208          end if;
12209       end if;
12210
12211       --  AI-443: Synchronized formal derived types require a private
12212       --  extension. There is no point in checking the ancestor type or
12213       --  the progenitors since the construct is wrong to begin with.
12214
12215       if Ada_Version >= Ada_05
12216         and then Is_Generic_Type (T)
12217         and then Present (Original_Node (N))
12218       then
12219          declare
12220             Decl : constant Node_Id := Original_Node (N);
12221
12222          begin
12223             if Nkind (Decl) = N_Formal_Type_Declaration
12224               and then Nkind (Formal_Type_Definition (Decl)) =
12225                          N_Formal_Derived_Type_Definition
12226               and then Synchronized_Present (Formal_Type_Definition (Decl))
12227               and then No (Extension)
12228
12229                --  Avoid emitting a duplicate error message
12230
12231               and then not Error_Posted (Indic)
12232             then
12233                Error_Msg_N
12234                  ("synchronized derived type must have extension", N);
12235             end if;
12236          end;
12237       end if;
12238
12239       Build_Derived_Type (N, Parent_Type, T, Is_Completion);
12240
12241       --  AI-419: The parent type of an explicitly limited derived type must
12242       --  be a limited type or a limited interface.
12243
12244       if Limited_Present (Def) then
12245          Set_Is_Limited_Record (T);
12246
12247          if Is_Interface (T) then
12248             Set_Is_Limited_Interface (T);
12249          end if;
12250
12251          if not Is_Limited_Type (Parent_Type)
12252            and then
12253              (not Is_Interface (Parent_Type)
12254                or else not Is_Limited_Interface (Parent_Type))
12255          then
12256             Error_Msg_NE ("parent type& of limited type must be limited",
12257               N, Parent_Type);
12258          end if;
12259       end if;
12260    end Derived_Type_Declaration;
12261
12262    ----------------------------------
12263    -- Enumeration_Type_Declaration --
12264    ----------------------------------
12265
12266    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
12267       Ev     : Uint;
12268       L      : Node_Id;
12269       R_Node : Node_Id;
12270       B_Node : Node_Id;
12271
12272    begin
12273       --  Create identifier node representing lower bound
12274
12275       B_Node := New_Node (N_Identifier, Sloc (Def));
12276       L := First (Literals (Def));
12277       Set_Chars (B_Node, Chars (L));
12278       Set_Entity (B_Node,  L);
12279       Set_Etype (B_Node, T);
12280       Set_Is_Static_Expression (B_Node, True);
12281
12282       R_Node := New_Node (N_Range, Sloc (Def));
12283       Set_Low_Bound  (R_Node, B_Node);
12284
12285       Set_Ekind (T, E_Enumeration_Type);
12286       Set_First_Literal (T, L);
12287       Set_Etype (T, T);
12288       Set_Is_Constrained (T);
12289
12290       Ev := Uint_0;
12291
12292       --  Loop through literals of enumeration type setting pos and rep values
12293       --  except that if the Ekind is already set, then it means that the
12294       --  literal was already constructed (case of a derived type declaration
12295       --  and we should not disturb the Pos and Rep values.
12296
12297       while Present (L) loop
12298          if Ekind (L) /= E_Enumeration_Literal then
12299             Set_Ekind (L, E_Enumeration_Literal);
12300             Set_Enumeration_Pos (L, Ev);
12301             Set_Enumeration_Rep (L, Ev);
12302             Set_Is_Known_Valid  (L, True);
12303          end if;
12304
12305          Set_Etype (L, T);
12306          New_Overloaded_Entity (L);
12307          Generate_Definition (L);
12308          Set_Convention (L, Convention_Intrinsic);
12309
12310          if Nkind (L) = N_Defining_Character_Literal then
12311             Set_Is_Character_Type (T, True);
12312          end if;
12313
12314          Ev := Ev + 1;
12315          Next (L);
12316       end loop;
12317
12318       --  Now create a node representing upper bound
12319
12320       B_Node := New_Node (N_Identifier, Sloc (Def));
12321       Set_Chars (B_Node, Chars (Last (Literals (Def))));
12322       Set_Entity (B_Node,  Last (Literals (Def)));
12323       Set_Etype (B_Node, T);
12324       Set_Is_Static_Expression (B_Node, True);
12325
12326       Set_High_Bound (R_Node, B_Node);
12327
12328       --  Initialize various fields of the type. Some of this information
12329       --  may be overwritten later through rep.clauses.
12330
12331       Set_Scalar_Range    (T, R_Node);
12332       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
12333       Set_Enum_Esize      (T);
12334       Set_Enum_Pos_To_Rep (T, Empty);
12335
12336       --  Set Discard_Names if configuration pragma set, or if there is
12337       --  a parameterless pragma in the current declarative region
12338
12339       if Global_Discard_Names
12340         or else Discard_Names (Scope (T))
12341       then
12342          Set_Discard_Names (T);
12343       end if;
12344
12345       --  Process end label if there is one
12346
12347       if Present (Def) then
12348          Process_End_Label (Def, 'e', T);
12349       end if;
12350    end Enumeration_Type_Declaration;
12351
12352    ---------------------------------
12353    -- Expand_To_Stored_Constraint --
12354    ---------------------------------
12355
12356    function Expand_To_Stored_Constraint
12357      (Typ        : Entity_Id;
12358       Constraint : Elist_Id) return Elist_Id
12359    is
12360       Explicitly_Discriminated_Type : Entity_Id;
12361       Expansion    : Elist_Id;
12362       Discriminant : Entity_Id;
12363
12364       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
12365       --  Find the nearest type that actually specifies discriminants
12366
12367       ---------------------------------
12368       -- Type_With_Explicit_Discrims --
12369       ---------------------------------
12370
12371       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
12372          Typ : constant E := Base_Type (Id);
12373
12374       begin
12375          if Ekind (Typ) in Incomplete_Or_Private_Kind then
12376             if Present (Full_View (Typ)) then
12377                return Type_With_Explicit_Discrims (Full_View (Typ));
12378             end if;
12379
12380          else
12381             if Has_Discriminants (Typ) then
12382                return Typ;
12383             end if;
12384          end if;
12385
12386          if Etype (Typ) = Typ then
12387             return Empty;
12388          elsif Has_Discriminants (Typ) then
12389             return Typ;
12390          else
12391             return Type_With_Explicit_Discrims (Etype (Typ));
12392          end if;
12393
12394       end Type_With_Explicit_Discrims;
12395
12396    --  Start of processing for Expand_To_Stored_Constraint
12397
12398    begin
12399       if No (Constraint)
12400         or else Is_Empty_Elmt_List (Constraint)
12401       then
12402          return No_Elist;
12403       end if;
12404
12405       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
12406
12407       if No (Explicitly_Discriminated_Type) then
12408          return No_Elist;
12409       end if;
12410
12411       Expansion := New_Elmt_List;
12412
12413       Discriminant :=
12414          First_Stored_Discriminant (Explicitly_Discriminated_Type);
12415       while Present (Discriminant) loop
12416          Append_Elmt (
12417            Get_Discriminant_Value (
12418              Discriminant, Explicitly_Discriminated_Type, Constraint),
12419            Expansion);
12420          Next_Stored_Discriminant (Discriminant);
12421       end loop;
12422
12423       return Expansion;
12424    end Expand_To_Stored_Constraint;
12425
12426    ---------------------------
12427    -- Find_Hidden_Interface --
12428    ---------------------------
12429
12430    function Find_Hidden_Interface
12431      (Src  : Elist_Id;
12432       Dest : Elist_Id) return Entity_Id
12433    is
12434       Iface      : Entity_Id;
12435       Iface_Elmt : Elmt_Id;
12436
12437    begin
12438       if Present (Src) and then Present (Dest) then
12439          Iface_Elmt := First_Elmt (Src);
12440          while Present (Iface_Elmt) loop
12441             Iface := Node (Iface_Elmt);
12442
12443             if Is_Interface (Iface)
12444               and then not Contain_Interface (Iface, Dest)
12445             then
12446                return Iface;
12447             end if;
12448
12449             Next_Elmt (Iface_Elmt);
12450          end loop;
12451       end if;
12452
12453       return Empty;
12454    end Find_Hidden_Interface;
12455
12456    --------------------
12457    -- Find_Type_Name --
12458    --------------------
12459
12460    function Find_Type_Name (N : Node_Id) return Entity_Id is
12461       Id       : constant Entity_Id := Defining_Identifier (N);
12462       Prev     : Entity_Id;
12463       New_Id   : Entity_Id;
12464       Prev_Par : Node_Id;
12465
12466    begin
12467       --  Find incomplete declaration, if one was given
12468
12469       Prev := Current_Entity_In_Scope (Id);
12470
12471       if Present (Prev) then
12472
12473          --  Previous declaration exists. Error if not incomplete/private case
12474          --  except if previous declaration is implicit, etc. Enter_Name will
12475          --  emit error if appropriate.
12476
12477          Prev_Par := Parent (Prev);
12478
12479          if not Is_Incomplete_Or_Private_Type (Prev) then
12480             Enter_Name (Id);
12481             New_Id := Id;
12482
12483          elsif Nkind (N) /= N_Full_Type_Declaration
12484            and then Nkind (N) /= N_Task_Type_Declaration
12485            and then Nkind (N) /= N_Protected_Type_Declaration
12486          then
12487             --  Completion must be a full type declarations (RM 7.3(4))
12488
12489             Error_Msg_Sloc := Sloc (Prev);
12490             Error_Msg_NE ("invalid completion of }", Id, Prev);
12491
12492             --  Set scope of Id to avoid cascaded errors. Entity is never
12493             --  examined again, except when saving globals in generics.
12494
12495             Set_Scope (Id, Current_Scope);
12496             New_Id := Id;
12497
12498          --  Case of full declaration of incomplete type
12499
12500          elsif Ekind (Prev) = E_Incomplete_Type then
12501
12502             --  Indicate that the incomplete declaration has a matching full
12503             --  declaration. The defining occurrence of the incomplete
12504             --  declaration remains the visible one, and the procedure
12505             --  Get_Full_View dereferences it whenever the type is used.
12506
12507             if Present (Full_View (Prev)) then
12508                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
12509             end if;
12510
12511             Set_Full_View (Prev,  Id);
12512             Append_Entity (Id, Current_Scope);
12513             Set_Is_Public (Id, Is_Public (Prev));
12514             Set_Is_Internal (Id);
12515             New_Id := Prev;
12516
12517          --  Case of full declaration of private type
12518
12519          else
12520             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
12521                if Etype (Prev) /= Prev then
12522
12523                   --  Prev is a private subtype or a derived type, and needs
12524                   --  no completion.
12525
12526                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
12527                   New_Id := Id;
12528
12529                elsif Ekind (Prev) = E_Private_Type
12530                  and then
12531                    (Nkind (N) = N_Task_Type_Declaration
12532                      or else Nkind (N) = N_Protected_Type_Declaration)
12533                then
12534                   Error_Msg_N
12535                    ("completion of nonlimited type cannot be limited", N);
12536
12537                elsif Ekind (Prev) = E_Record_Type_With_Private
12538                  and then
12539                    (Nkind (N) = N_Task_Type_Declaration
12540                      or else Nkind (N) = N_Protected_Type_Declaration)
12541                then
12542                   if not Is_Limited_Record (Prev) then
12543                      Error_Msg_N
12544                         ("completion of nonlimited type cannot be limited", N);
12545
12546                   elsif No (Interface_List (N)) then
12547                      Error_Msg_N
12548                         ("completion of tagged private type must be tagged",
12549                            N);
12550                   end if;
12551                end if;
12552
12553             --  Ada 2005 (AI-251): Private extension declaration of a task
12554             --  type or a protected type. This case arises when covering
12555             --  interface types.
12556
12557             elsif Nkind (N) = N_Task_Type_Declaration
12558               or else Nkind (N) = N_Protected_Type_Declaration
12559             then
12560                null;
12561
12562             elsif Nkind (N) /= N_Full_Type_Declaration
12563               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
12564             then
12565                Error_Msg_N
12566                  ("full view of private extension must be an extension", N);
12567
12568             elsif not (Abstract_Present (Parent (Prev)))
12569               and then Abstract_Present (Type_Definition (N))
12570             then
12571                Error_Msg_N
12572                  ("full view of non-abstract extension cannot be abstract", N);
12573             end if;
12574
12575             if not In_Private_Part (Current_Scope) then
12576                Error_Msg_N
12577                  ("declaration of full view must appear in private part", N);
12578             end if;
12579
12580             Copy_And_Swap (Prev, Id);
12581             Set_Has_Private_Declaration (Prev);
12582             Set_Has_Private_Declaration (Id);
12583
12584             --  If no error, propagate freeze_node from private to full view.
12585             --  It may have been generated for an early operational item.
12586
12587             if Present (Freeze_Node (Id))
12588               and then Serious_Errors_Detected = 0
12589               and then No (Full_View (Id))
12590             then
12591                Set_Freeze_Node (Prev, Freeze_Node (Id));
12592                Set_Freeze_Node (Id, Empty);
12593                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
12594             end if;
12595
12596             Set_Full_View (Id, Prev);
12597             New_Id := Prev;
12598          end if;
12599
12600          --  Verify that full declaration conforms to incomplete one
12601
12602          if Is_Incomplete_Or_Private_Type (Prev)
12603            and then Present (Discriminant_Specifications (Prev_Par))
12604          then
12605             if Present (Discriminant_Specifications (N)) then
12606                if Ekind (Prev) = E_Incomplete_Type then
12607                   Check_Discriminant_Conformance (N, Prev, Prev);
12608                else
12609                   Check_Discriminant_Conformance (N, Prev, Id);
12610                end if;
12611
12612             else
12613                Error_Msg_N
12614                  ("missing discriminants in full type declaration", N);
12615
12616                --  To avoid cascaded errors on subsequent use, share the
12617                --  discriminants of the partial view.
12618
12619                Set_Discriminant_Specifications (N,
12620                  Discriminant_Specifications (Prev_Par));
12621             end if;
12622          end if;
12623
12624          --  A prior untagged private type can have an associated class-wide
12625          --  type due to use of the class attribute, and in this case also the
12626          --  full type is required to be tagged.
12627
12628          if Is_Type (Prev)
12629            and then (Is_Tagged_Type (Prev)
12630                       or else Present (Class_Wide_Type (Prev)))
12631            and then (Nkind (N) /= N_Task_Type_Declaration
12632                       and then Nkind (N) /= N_Protected_Type_Declaration)
12633          then
12634             --  The full declaration is either a tagged record or an
12635             --  extension otherwise this is an error
12636
12637             if Nkind (Type_Definition (N)) = N_Record_Definition then
12638                if not Tagged_Present (Type_Definition (N)) then
12639                   Error_Msg_NE
12640                     ("full declaration of } must be tagged", Prev, Id);
12641                   Set_Is_Tagged_Type (Id);
12642                   Set_Primitive_Operations (Id, New_Elmt_List);
12643                end if;
12644
12645             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
12646                if No (Record_Extension_Part (Type_Definition (N))) then
12647                   Error_Msg_NE (
12648                     "full declaration of } must be a record extension",
12649                     Prev, Id);
12650                   Set_Is_Tagged_Type (Id);
12651                   Set_Primitive_Operations (Id, New_Elmt_List);
12652                end if;
12653
12654             else
12655                Error_Msg_NE
12656                  ("full declaration of } must be a tagged type", Prev, Id);
12657
12658             end if;
12659          end if;
12660
12661          return New_Id;
12662
12663       else
12664          --  New type declaration
12665
12666          Enter_Name (Id);
12667          return Id;
12668       end if;
12669    end Find_Type_Name;
12670
12671    -------------------------
12672    -- Find_Type_Of_Object --
12673    -------------------------
12674
12675    function Find_Type_Of_Object
12676      (Obj_Def     : Node_Id;
12677       Related_Nod : Node_Id) return Entity_Id
12678    is
12679       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
12680       P        : Node_Id := Parent (Obj_Def);
12681       T        : Entity_Id;
12682       Nam      : Name_Id;
12683
12684    begin
12685       --  If the parent is a component_definition node we climb to the
12686       --  component_declaration node
12687
12688       if Nkind (P) = N_Component_Definition then
12689          P := Parent (P);
12690       end if;
12691
12692       --  Case of an anonymous array subtype
12693
12694       if Def_Kind = N_Constrained_Array_Definition
12695         or else Def_Kind = N_Unconstrained_Array_Definition
12696       then
12697          T := Empty;
12698          Array_Type_Declaration (T, Obj_Def);
12699
12700       --  Create an explicit subtype whenever possible
12701
12702       elsif Nkind (P) /= N_Component_Declaration
12703         and then Def_Kind = N_Subtype_Indication
12704       then
12705          --  Base name of subtype on object name, which will be unique in
12706          --  the current scope.
12707
12708          --  If this is a duplicate declaration, return base type, to avoid
12709          --  generating duplicate anonymous types.
12710
12711          if Error_Posted (P) then
12712             Analyze (Subtype_Mark (Obj_Def));
12713             return Entity (Subtype_Mark (Obj_Def));
12714          end if;
12715
12716          Nam :=
12717             New_External_Name
12718              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
12719
12720          T := Make_Defining_Identifier (Sloc (P), Nam);
12721
12722          Insert_Action (Obj_Def,
12723            Make_Subtype_Declaration (Sloc (P),
12724              Defining_Identifier => T,
12725              Subtype_Indication  => Relocate_Node (Obj_Def)));
12726
12727          --  This subtype may need freezing, and this will not be done
12728          --  automatically if the object declaration is not in declarative
12729          --  part. Since this is an object declaration, the type cannot always
12730          --  be frozen here. Deferred constants do not freeze their type
12731          --  (which often enough will be private).
12732
12733          if Nkind (P) = N_Object_Declaration
12734            and then Constant_Present (P)
12735            and then No (Expression (P))
12736          then
12737             null;
12738          else
12739             Insert_Actions (Obj_Def, Freeze_Entity (T, Sloc (P)));
12740          end if;
12741
12742       --  Ada 2005 AI-406: the object definition in an object declaration
12743       --  can be an access definition.
12744
12745       elsif Def_Kind = N_Access_Definition then
12746          T := Access_Definition (Related_Nod, Obj_Def);
12747          Set_Is_Local_Anonymous_Access (T);
12748
12749       --  Otherwise, the object definition is just a subtype_mark
12750
12751       else
12752          T := Process_Subtype (Obj_Def, Related_Nod);
12753       end if;
12754
12755       return T;
12756    end Find_Type_Of_Object;
12757
12758    --------------------------------
12759    -- Find_Type_Of_Subtype_Indic --
12760    --------------------------------
12761
12762    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
12763       Typ : Entity_Id;
12764
12765    begin
12766       --  Case of subtype mark with a constraint
12767
12768       if Nkind (S) = N_Subtype_Indication then
12769          Find_Type (Subtype_Mark (S));
12770          Typ := Entity (Subtype_Mark (S));
12771
12772          if not
12773            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
12774          then
12775             Error_Msg_N
12776               ("incorrect constraint for this kind of type", Constraint (S));
12777             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
12778          end if;
12779
12780       --  Otherwise we have a subtype mark without a constraint
12781
12782       elsif Error_Posted (S) then
12783          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
12784          return Any_Type;
12785
12786       else
12787          Find_Type (S);
12788          Typ := Entity (S);
12789       end if;
12790
12791       if Typ = Standard_Wide_Character
12792         or else Typ = Standard_Wide_Wide_Character
12793         or else Typ = Standard_Wide_String
12794         or else Typ = Standard_Wide_Wide_String
12795       then
12796          Check_Restriction (No_Wide_Characters, S);
12797       end if;
12798
12799       return Typ;
12800    end Find_Type_Of_Subtype_Indic;
12801
12802    -------------------------------------
12803    -- Floating_Point_Type_Declaration --
12804    -------------------------------------
12805
12806    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
12807       Digs          : constant Node_Id := Digits_Expression (Def);
12808       Digs_Val      : Uint;
12809       Base_Typ      : Entity_Id;
12810       Implicit_Base : Entity_Id;
12811       Bound         : Node_Id;
12812
12813       function Can_Derive_From (E : Entity_Id) return Boolean;
12814       --  Find if given digits value allows derivation from specified type
12815
12816       ---------------------
12817       -- Can_Derive_From --
12818       ---------------------
12819
12820       function Can_Derive_From (E : Entity_Id) return Boolean is
12821          Spec : constant Entity_Id := Real_Range_Specification (Def);
12822
12823       begin
12824          if Digs_Val > Digits_Value (E) then
12825             return False;
12826          end if;
12827
12828          if Present (Spec) then
12829             if Expr_Value_R (Type_Low_Bound (E)) >
12830                Expr_Value_R (Low_Bound (Spec))
12831             then
12832                return False;
12833             end if;
12834
12835             if Expr_Value_R (Type_High_Bound (E)) <
12836                Expr_Value_R (High_Bound (Spec))
12837             then
12838                return False;
12839             end if;
12840          end if;
12841
12842          return True;
12843       end Can_Derive_From;
12844
12845    --  Start of processing for Floating_Point_Type_Declaration
12846
12847    begin
12848       Check_Restriction (No_Floating_Point, Def);
12849
12850       --  Create an implicit base type
12851
12852       Implicit_Base :=
12853         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
12854
12855       --  Analyze and verify digits value
12856
12857       Analyze_And_Resolve (Digs, Any_Integer);
12858       Check_Digits_Expression (Digs);
12859       Digs_Val := Expr_Value (Digs);
12860
12861       --  Process possible range spec and find correct type to derive from
12862
12863       Process_Real_Range_Specification (Def);
12864
12865       if Can_Derive_From (Standard_Short_Float) then
12866          Base_Typ := Standard_Short_Float;
12867       elsif Can_Derive_From (Standard_Float) then
12868          Base_Typ := Standard_Float;
12869       elsif Can_Derive_From (Standard_Long_Float) then
12870          Base_Typ := Standard_Long_Float;
12871       elsif Can_Derive_From (Standard_Long_Long_Float) then
12872          Base_Typ := Standard_Long_Long_Float;
12873
12874       --  If we can't derive from any existing type, use long_long_float
12875       --  and give appropriate message explaining the problem.
12876
12877       else
12878          Base_Typ := Standard_Long_Long_Float;
12879
12880          if Digs_Val >= Digits_Value (Standard_Long_Long_Float) then
12881             Error_Msg_Uint_1 := Digits_Value (Standard_Long_Long_Float);
12882             Error_Msg_N ("digits value out of range, maximum is ^", Digs);
12883
12884          else
12885             Error_Msg_N
12886               ("range too large for any predefined type",
12887                Real_Range_Specification (Def));
12888          end if;
12889       end if;
12890
12891       --  If there are bounds given in the declaration use them as the bounds
12892       --  of the type, otherwise use the bounds of the predefined base type
12893       --  that was chosen based on the Digits value.
12894
12895       if Present (Real_Range_Specification (Def)) then
12896          Set_Scalar_Range (T, Real_Range_Specification (Def));
12897          Set_Is_Constrained (T);
12898
12899          --  The bounds of this range must be converted to machine numbers
12900          --  in accordance with RM 4.9(38).
12901
12902          Bound := Type_Low_Bound (T);
12903
12904          if Nkind (Bound) = N_Real_Literal then
12905             Set_Realval
12906               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
12907             Set_Is_Machine_Number (Bound);
12908          end if;
12909
12910          Bound := Type_High_Bound (T);
12911
12912          if Nkind (Bound) = N_Real_Literal then
12913             Set_Realval
12914               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
12915             Set_Is_Machine_Number (Bound);
12916          end if;
12917
12918       else
12919          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
12920       end if;
12921
12922       --  Complete definition of implicit base and declared first subtype
12923
12924       Set_Etype          (Implicit_Base, Base_Typ);
12925
12926       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
12927       Set_Size_Info      (Implicit_Base,                (Base_Typ));
12928       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
12929       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
12930       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
12931       Set_Vax_Float      (Implicit_Base, Vax_Float      (Base_Typ));
12932
12933       Set_Ekind          (T, E_Floating_Point_Subtype);
12934       Set_Etype          (T, Implicit_Base);
12935
12936       Set_Size_Info      (T,                (Implicit_Base));
12937       Set_RM_Size        (T, RM_Size        (Implicit_Base));
12938       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
12939       Set_Digits_Value   (T, Digs_Val);
12940    end Floating_Point_Type_Declaration;
12941
12942    ----------------------------
12943    -- Get_Discriminant_Value --
12944    ----------------------------
12945
12946    --  This is the situation:
12947
12948    --  There is a non-derived type
12949
12950    --       type T0 (Dx, Dy, Dz...)
12951
12952    --  There are zero or more levels of derivation, with each derivation
12953    --  either purely inheriting the discriminants, or defining its own.
12954
12955    --       type Ti      is new Ti-1
12956    --  or
12957    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
12958    --  or
12959    --       subtype Ti is ...
12960
12961    --  The subtype issue is avoided by the use of Original_Record_Component,
12962    --  and the fact that derived subtypes also derive the constraints.
12963
12964    --  This chain leads back from
12965
12966    --       Typ_For_Constraint
12967
12968    --  Typ_For_Constraint has discriminants, and the value for each
12969    --  discriminant is given by its corresponding Elmt of Constraints.
12970
12971    --  Discriminant is some discriminant in this hierarchy
12972
12973    --  We need to return its value
12974
12975    --  We do this by recursively searching each level, and looking for
12976    --  Discriminant. Once we get to the bottom, we start backing up
12977    --  returning the value for it which may in turn be a discriminant
12978    --  further up, so on the backup we continue the substitution.
12979
12980    function Get_Discriminant_Value
12981      (Discriminant       : Entity_Id;
12982       Typ_For_Constraint : Entity_Id;
12983       Constraint         : Elist_Id) return Node_Id
12984    is
12985       function Search_Derivation_Levels
12986         (Ti                    : Entity_Id;
12987          Discrim_Values        : Elist_Id;
12988          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
12989       --  This is the routine that performs the recursive search of levels
12990       --  as described above.
12991
12992       ------------------------------
12993       -- Search_Derivation_Levels --
12994       ------------------------------
12995
12996       function Search_Derivation_Levels
12997         (Ti                    : Entity_Id;
12998          Discrim_Values        : Elist_Id;
12999          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
13000       is
13001          Assoc          : Elmt_Id;
13002          Disc           : Entity_Id;
13003          Result         : Node_Or_Entity_Id;
13004          Result_Entity  : Node_Id;
13005
13006       begin
13007          --  If inappropriate type, return Error, this happens only in
13008          --  cascaded error situations, and we want to avoid a blow up.
13009
13010          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
13011             return Error;
13012          end if;
13013
13014          --  Look deeper if possible. Use Stored_Constraints only for
13015          --  untagged types. For tagged types use the given constraint.
13016          --  This asymmetry needs explanation???
13017
13018          if not Stored_Discrim_Values
13019            and then Present (Stored_Constraint (Ti))
13020            and then not Is_Tagged_Type (Ti)
13021          then
13022             Result :=
13023               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
13024          else
13025             declare
13026                Td : constant Entity_Id := Etype (Ti);
13027
13028             begin
13029                if Td = Ti then
13030                   Result := Discriminant;
13031
13032                else
13033                   if Present (Stored_Constraint (Ti)) then
13034                      Result :=
13035                         Search_Derivation_Levels
13036                           (Td, Stored_Constraint (Ti), True);
13037                   else
13038                      Result :=
13039                         Search_Derivation_Levels
13040                           (Td, Discrim_Values, Stored_Discrim_Values);
13041                   end if;
13042                end if;
13043             end;
13044          end if;
13045
13046          --  Extra underlying places to search, if not found above. For
13047          --  concurrent types, the relevant discriminant appears in the
13048          --  corresponding record. For a type derived from a private type
13049          --  without discriminant, the full view inherits the discriminants
13050          --  of the full view of the parent.
13051
13052          if Result = Discriminant then
13053             if Is_Concurrent_Type (Ti)
13054               and then Present (Corresponding_Record_Type (Ti))
13055             then
13056                Result :=
13057                  Search_Derivation_Levels (
13058                    Corresponding_Record_Type (Ti),
13059                    Discrim_Values,
13060                    Stored_Discrim_Values);
13061
13062             elsif Is_Private_Type (Ti)
13063               and then not Has_Discriminants (Ti)
13064               and then Present (Full_View (Ti))
13065               and then Etype (Full_View (Ti)) /= Ti
13066             then
13067                Result :=
13068                  Search_Derivation_Levels (
13069                    Full_View (Ti),
13070                    Discrim_Values,
13071                    Stored_Discrim_Values);
13072             end if;
13073          end if;
13074
13075          --  If Result is not a (reference to a) discriminant, return it,
13076          --  otherwise set Result_Entity to the discriminant.
13077
13078          if Nkind (Result) = N_Defining_Identifier then
13079             pragma Assert (Result = Discriminant);
13080             Result_Entity := Result;
13081
13082          else
13083             if not Denotes_Discriminant (Result) then
13084                return Result;
13085             end if;
13086
13087             Result_Entity := Entity (Result);
13088          end if;
13089
13090          --  See if this level of derivation actually has discriminants
13091          --  because tagged derivations can add them, hence the lower
13092          --  levels need not have any.
13093
13094          if not Has_Discriminants (Ti) then
13095             return Result;
13096          end if;
13097
13098          --  Scan Ti's discriminants for Result_Entity,
13099          --  and return its corresponding value, if any.
13100
13101          Result_Entity := Original_Record_Component (Result_Entity);
13102
13103          Assoc := First_Elmt (Discrim_Values);
13104
13105          if Stored_Discrim_Values then
13106             Disc := First_Stored_Discriminant (Ti);
13107          else
13108             Disc := First_Discriminant (Ti);
13109          end if;
13110
13111          while Present (Disc) loop
13112             pragma Assert (Present (Assoc));
13113
13114             if Original_Record_Component (Disc) = Result_Entity then
13115                return Node (Assoc);
13116             end if;
13117
13118             Next_Elmt (Assoc);
13119
13120             if Stored_Discrim_Values then
13121                Next_Stored_Discriminant (Disc);
13122             else
13123                Next_Discriminant (Disc);
13124             end if;
13125          end loop;
13126
13127          --  Could not find it
13128          --
13129          return Result;
13130       end Search_Derivation_Levels;
13131
13132       Result : Node_Or_Entity_Id;
13133
13134    --  Start of processing for Get_Discriminant_Value
13135
13136    begin
13137       --  ??? This routine is a gigantic mess and will be deleted. For the
13138       --  time being just test for the trivial case before calling recurse.
13139
13140       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
13141          declare
13142             D : Entity_Id;
13143             E : Elmt_Id;
13144
13145          begin
13146             D := First_Discriminant (Typ_For_Constraint);
13147             E := First_Elmt (Constraint);
13148             while Present (D) loop
13149                if Chars (D) = Chars (Discriminant) then
13150                   return Node (E);
13151                end if;
13152
13153                Next_Discriminant (D);
13154                Next_Elmt (E);
13155             end loop;
13156          end;
13157       end if;
13158
13159       Result := Search_Derivation_Levels
13160         (Typ_For_Constraint, Constraint, False);
13161
13162       --  ??? hack to disappear when this routine is gone
13163
13164       if  Nkind (Result) = N_Defining_Identifier then
13165          declare
13166             D : Entity_Id;
13167             E : Elmt_Id;
13168
13169          begin
13170             D := First_Discriminant (Typ_For_Constraint);
13171             E := First_Elmt (Constraint);
13172             while Present (D) loop
13173                if Corresponding_Discriminant (D) = Discriminant then
13174                   return Node (E);
13175                end if;
13176
13177                Next_Discriminant (D);
13178                Next_Elmt (E);
13179             end loop;
13180          end;
13181       end if;
13182
13183       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
13184       return Result;
13185    end Get_Discriminant_Value;
13186
13187    --------------------------
13188    -- Has_Range_Constraint --
13189    --------------------------
13190
13191    function Has_Range_Constraint (N : Node_Id) return Boolean is
13192       C : constant Node_Id := Constraint (N);
13193
13194    begin
13195       if Nkind (C) = N_Range_Constraint then
13196          return True;
13197
13198       elsif Nkind (C) = N_Digits_Constraint then
13199          return
13200             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
13201               or else
13202             Present (Range_Constraint (C));
13203
13204       elsif Nkind (C) = N_Delta_Constraint then
13205          return Present (Range_Constraint (C));
13206
13207       else
13208          return False;
13209       end if;
13210    end Has_Range_Constraint;
13211
13212    ------------------------
13213    -- Inherit_Components --
13214    ------------------------
13215
13216    function Inherit_Components
13217      (N             : Node_Id;
13218       Parent_Base   : Entity_Id;
13219       Derived_Base  : Entity_Id;
13220       Is_Tagged     : Boolean;
13221       Inherit_Discr : Boolean;
13222       Discs         : Elist_Id) return Elist_Id
13223    is
13224       Assoc_List : constant Elist_Id := New_Elmt_List;
13225
13226       procedure Inherit_Component
13227         (Old_C          : Entity_Id;
13228          Plain_Discrim  : Boolean := False;
13229          Stored_Discrim : Boolean := False);
13230       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
13231       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
13232       --  True, Old_C is a stored discriminant. If they are both false then
13233       --  Old_C is a regular component.
13234
13235       -----------------------
13236       -- Inherit_Component --
13237       -----------------------
13238
13239       procedure Inherit_Component
13240         (Old_C          : Entity_Id;
13241          Plain_Discrim  : Boolean := False;
13242          Stored_Discrim : Boolean := False)
13243       is
13244          New_C : constant Entity_Id := New_Copy (Old_C);
13245
13246          Discrim      : Entity_Id;
13247          Corr_Discrim : Entity_Id;
13248
13249       begin
13250          pragma Assert (not Is_Tagged or else not Stored_Discrim);
13251
13252          Set_Parent (New_C, Parent (Old_C));
13253
13254          --  Regular discriminants and components must be inserted in the scope
13255          --  of the Derived_Base. Do it here.
13256
13257          if not Stored_Discrim then
13258             Enter_Name (New_C);
13259          end if;
13260
13261          --  For tagged types the Original_Record_Component must point to
13262          --  whatever this field was pointing to in the parent type. This has
13263          --  already been achieved by the call to New_Copy above.
13264
13265          if not Is_Tagged then
13266             Set_Original_Record_Component (New_C, New_C);
13267          end if;
13268
13269          --  If we have inherited a component then see if its Etype contains
13270          --  references to Parent_Base discriminants. In this case, replace
13271          --  these references with the constraints given in Discs. We do not
13272          --  do this for the partial view of private types because this is
13273          --  not needed (only the components of the full view will be used
13274          --  for code generation) and cause problem. We also avoid this
13275          --  transformation in some error situations.
13276
13277          if Ekind (New_C) = E_Component then
13278             if (Is_Private_Type (Derived_Base)
13279                  and then not Is_Generic_Type (Derived_Base))
13280               or else (Is_Empty_Elmt_List (Discs)
13281                         and then  not Expander_Active)
13282             then
13283                Set_Etype (New_C, Etype (Old_C));
13284
13285             else
13286                --  The current component introduces a circularity of the
13287                --  following kind:
13288
13289                --     limited with Pack_2;
13290                --     package Pack_1 is
13291                --        type T_1 is tagged record
13292                --           Comp : access Pack_2.T_2;
13293                --           ...
13294                --        end record;
13295                --     end Pack_1;
13296
13297                --     with Pack_1;
13298                --     package Pack_2 is
13299                --        type T_2 is new Pack_1.T_1 with ...;
13300                --     end Pack_2;
13301
13302                Set_Etype
13303                  (New_C,
13304                   Constrain_Component_Type
13305                   (Old_C, Derived_Base, N, Parent_Base, Discs));
13306             end if;
13307          end if;
13308
13309          --  In derived tagged types it is illegal to reference a non
13310          --  discriminant component in the parent type. To catch this, mark
13311          --  these components with an Ekind of E_Void. This will be reset in
13312          --  Record_Type_Definition after processing the record extension of
13313          --  the derived type.
13314
13315          --  If the declaration is a private extension, there is no further
13316          --  record extension to process, and the components retain their
13317          --  current kind, because they are visible at this point.
13318
13319          if Is_Tagged and then Ekind (New_C) = E_Component
13320            and then Nkind (N) /= N_Private_Extension_Declaration
13321          then
13322             Set_Ekind (New_C, E_Void);
13323          end if;
13324
13325          if Plain_Discrim then
13326             Set_Corresponding_Discriminant (New_C, Old_C);
13327             Build_Discriminal (New_C);
13328
13329          --  If we are explicitly inheriting a stored discriminant it will be
13330          --  completely hidden.
13331
13332          elsif Stored_Discrim then
13333             Set_Corresponding_Discriminant (New_C, Empty);
13334             Set_Discriminal (New_C, Empty);
13335             Set_Is_Completely_Hidden (New_C);
13336
13337             --  Set the Original_Record_Component of each discriminant in the
13338             --  derived base to point to the corresponding stored that we just
13339             --  created.
13340
13341             Discrim := First_Discriminant (Derived_Base);
13342             while Present (Discrim) loop
13343                Corr_Discrim := Corresponding_Discriminant (Discrim);
13344
13345                --  Corr_Discrim could be missing in an error situation
13346
13347                if Present (Corr_Discrim)
13348                  and then Original_Record_Component (Corr_Discrim) = Old_C
13349                then
13350                   Set_Original_Record_Component (Discrim, New_C);
13351                end if;
13352
13353                Next_Discriminant (Discrim);
13354             end loop;
13355
13356             Append_Entity (New_C, Derived_Base);
13357          end if;
13358
13359          if not Is_Tagged then
13360             Append_Elmt (Old_C, Assoc_List);
13361             Append_Elmt (New_C, Assoc_List);
13362          end if;
13363       end Inherit_Component;
13364
13365       --  Variables local to Inherit_Component
13366
13367       Loc : constant Source_Ptr := Sloc (N);
13368
13369       Parent_Discrim : Entity_Id;
13370       Stored_Discrim : Entity_Id;
13371       D              : Entity_Id;
13372       Component      : Entity_Id;
13373
13374    --  Start of processing for Inherit_Components
13375
13376    begin
13377       if not Is_Tagged then
13378          Append_Elmt (Parent_Base,  Assoc_List);
13379          Append_Elmt (Derived_Base, Assoc_List);
13380       end if;
13381
13382       --  Inherit parent discriminants if needed
13383
13384       if Inherit_Discr then
13385          Parent_Discrim := First_Discriminant (Parent_Base);
13386          while Present (Parent_Discrim) loop
13387             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
13388             Next_Discriminant (Parent_Discrim);
13389          end loop;
13390       end if;
13391
13392       --  Create explicit stored discrims for untagged types when necessary
13393
13394       if not Has_Unknown_Discriminants (Derived_Base)
13395         and then Has_Discriminants (Parent_Base)
13396         and then not Is_Tagged
13397         and then
13398           (not Inherit_Discr
13399              or else First_Discriminant (Parent_Base) /=
13400                      First_Stored_Discriminant (Parent_Base))
13401       then
13402          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
13403          while Present (Stored_Discrim) loop
13404             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
13405             Next_Stored_Discriminant (Stored_Discrim);
13406          end loop;
13407       end if;
13408
13409       --  See if we can apply the second transformation for derived types, as
13410       --  explained in point 6. in the comments above Build_Derived_Record_Type
13411       --  This is achieved by appending Derived_Base discriminants into Discs,
13412       --  which has the side effect of returning a non empty Discs list to the
13413       --  caller of Inherit_Components, which is what we want. This must be
13414       --  done for private derived types if there are explicit stored
13415       --  discriminants, to ensure that we can retrieve the values of the
13416       --  constraints provided in the ancestors.
13417
13418       if Inherit_Discr
13419         and then Is_Empty_Elmt_List (Discs)
13420         and then Present (First_Discriminant (Derived_Base))
13421         and then
13422           (not Is_Private_Type (Derived_Base)
13423              or else Is_Completely_Hidden
13424                (First_Stored_Discriminant (Derived_Base))
13425              or else Is_Generic_Type (Derived_Base))
13426       then
13427          D := First_Discriminant (Derived_Base);
13428          while Present (D) loop
13429             Append_Elmt (New_Reference_To (D, Loc), Discs);
13430             Next_Discriminant (D);
13431          end loop;
13432       end if;
13433
13434       --  Finally, inherit non-discriminant components unless they are not
13435       --  visible because defined or inherited from the full view of the
13436       --  parent. Don't inherit the _parent field of the parent type.
13437
13438       Component := First_Entity (Parent_Base);
13439       while Present (Component) loop
13440
13441          --  Ada 2005 (AI-251): Do not inherit components associated with
13442          --  secondary tags of the parent.
13443
13444          if Ekind (Component) = E_Component
13445            and then Present (Related_Interface (Component))
13446          then
13447             null;
13448
13449          elsif Ekind (Component) /= E_Component
13450            or else Chars (Component) = Name_uParent
13451          then
13452             null;
13453
13454          --  If the derived type is within the parent type's declarative
13455          --  region, then the components can still be inherited even though
13456          --  they aren't visible at this point. This can occur for cases
13457          --  such as within public child units where the components must
13458          --  become visible upon entering the child unit's private part.
13459
13460          elsif not Is_Visible_Component (Component)
13461            and then not In_Open_Scopes (Scope (Parent_Base))
13462          then
13463             null;
13464
13465          elsif Ekind (Derived_Base) = E_Private_Type
13466            or else Ekind (Derived_Base) = E_Limited_Private_Type
13467          then
13468             null;
13469
13470          else
13471             Inherit_Component (Component);
13472          end if;
13473
13474          Next_Entity (Component);
13475       end loop;
13476
13477       --  For tagged derived types, inherited discriminants cannot be used in
13478       --  component declarations of the record extension part. To achieve this
13479       --  we mark the inherited discriminants as not visible.
13480
13481       if Is_Tagged and then Inherit_Discr then
13482          D := First_Discriminant (Derived_Base);
13483          while Present (D) loop
13484             Set_Is_Immediately_Visible (D, False);
13485             Next_Discriminant (D);
13486          end loop;
13487       end if;
13488
13489       return Assoc_List;
13490    end Inherit_Components;
13491
13492    -----------------------
13493    -- Is_Null_Extension --
13494    -----------------------
13495
13496    function Is_Null_Extension (T : Entity_Id) return Boolean is
13497       Type_Decl : constant Node_Id := Parent (T);
13498       Comp_List : Node_Id;
13499       Comp      : Node_Id;
13500
13501    begin
13502       if Nkind (Type_Decl) /= N_Full_Type_Declaration
13503         or else not Is_Tagged_Type (T)
13504         or else Nkind (Type_Definition (Type_Decl)) /=
13505                                               N_Derived_Type_Definition
13506         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
13507       then
13508          return False;
13509       end if;
13510
13511       Comp_List :=
13512         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
13513
13514       if Present (Discriminant_Specifications (Type_Decl)) then
13515          return False;
13516
13517       elsif Present (Comp_List)
13518         and then Is_Non_Empty_List (Component_Items (Comp_List))
13519       then
13520          Comp := First (Component_Items (Comp_List));
13521
13522          --  Only user-defined components are relevant. The component list
13523          --  may also contain a parent component and internal components
13524          --  corresponding to secondary tags, but these do not determine
13525          --  whether this is a null extension.
13526
13527          while Present (Comp) loop
13528             if Comes_From_Source (Comp) then
13529                return False;
13530             end if;
13531
13532             Next (Comp);
13533          end loop;
13534
13535          return True;
13536       else
13537          return True;
13538       end if;
13539    end Is_Null_Extension;
13540
13541    ------------------------------
13542    -- Is_Valid_Constraint_Kind --
13543    ------------------------------
13544
13545    function Is_Valid_Constraint_Kind
13546      (T_Kind          : Type_Kind;
13547       Constraint_Kind : Node_Kind) return Boolean
13548    is
13549    begin
13550       case T_Kind is
13551          when Enumeration_Kind |
13552               Integer_Kind =>
13553             return Constraint_Kind = N_Range_Constraint;
13554
13555          when Decimal_Fixed_Point_Kind =>
13556             return
13557               Constraint_Kind = N_Digits_Constraint
13558                 or else
13559               Constraint_Kind = N_Range_Constraint;
13560
13561          when Ordinary_Fixed_Point_Kind =>
13562             return
13563               Constraint_Kind = N_Delta_Constraint
13564                 or else
13565               Constraint_Kind = N_Range_Constraint;
13566
13567          when Float_Kind =>
13568             return
13569               Constraint_Kind = N_Digits_Constraint
13570                 or else
13571               Constraint_Kind = N_Range_Constraint;
13572
13573          when Access_Kind       |
13574               Array_Kind        |
13575               E_Record_Type     |
13576               E_Record_Subtype  |
13577               Class_Wide_Kind   |
13578               E_Incomplete_Type |
13579               Private_Kind      |
13580               Concurrent_Kind  =>
13581             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
13582
13583          when others =>
13584             return True; -- Error will be detected later
13585       end case;
13586    end Is_Valid_Constraint_Kind;
13587
13588    --------------------------
13589    -- Is_Visible_Component --
13590    --------------------------
13591
13592    function Is_Visible_Component (C : Entity_Id) return Boolean is
13593       Original_Comp  : Entity_Id := Empty;
13594       Original_Scope : Entity_Id;
13595       Type_Scope     : Entity_Id;
13596
13597       function Is_Local_Type (Typ : Entity_Id) return Boolean;
13598       --  Check whether parent type of inherited component is declared locally,
13599       --  possibly within a nested package or instance. The current scope is
13600       --  the derived record itself.
13601
13602       -------------------
13603       -- Is_Local_Type --
13604       -------------------
13605
13606       function Is_Local_Type (Typ : Entity_Id) return Boolean is
13607          Scop : Entity_Id;
13608
13609       begin
13610          Scop := Scope (Typ);
13611          while Present (Scop)
13612            and then Scop /= Standard_Standard
13613          loop
13614             if Scop = Scope (Current_Scope) then
13615                return True;
13616             end if;
13617
13618             Scop := Scope (Scop);
13619          end loop;
13620
13621          return False;
13622       end Is_Local_Type;
13623
13624    --  Start of processing for Is_Visible_Component
13625
13626    begin
13627       if Ekind (C) = E_Component
13628         or else Ekind (C) = E_Discriminant
13629       then
13630          Original_Comp := Original_Record_Component (C);
13631       end if;
13632
13633       if No (Original_Comp) then
13634
13635          --  Premature usage, or previous error
13636
13637          return False;
13638
13639       else
13640          Original_Scope := Scope (Original_Comp);
13641          Type_Scope     := Scope (Base_Type (Scope (C)));
13642       end if;
13643
13644       --  This test only concerns tagged types
13645
13646       if not Is_Tagged_Type (Original_Scope) then
13647          return True;
13648
13649       --  If it is _Parent or _Tag, there is no visibility issue
13650
13651       elsif not Comes_From_Source (Original_Comp) then
13652          return True;
13653
13654       --  If we are in the body of an instantiation, the component is visible
13655       --  even when the parent type (possibly defined in an enclosing unit or
13656       --  in a parent unit) might not.
13657
13658       elsif In_Instance_Body then
13659          return True;
13660
13661       --  Discriminants are always visible
13662
13663       elsif Ekind (Original_Comp) = E_Discriminant
13664         and then not Has_Unknown_Discriminants (Original_Scope)
13665       then
13666          return True;
13667
13668       --  If the component has been declared in an ancestor which is currently
13669       --  a private type, then it is not visible. The same applies if the
13670       --  component's containing type is not in an open scope and the original
13671       --  component's enclosing type is a visible full view of a private type
13672       --  (which can occur in cases where an attempt is being made to reference
13673       --  a component in a sibling package that is inherited from a visible
13674       --  component of a type in an ancestor package; the component in the
13675       --  sibling package should not be visible even though the component it
13676       --  inherited from is visible). This does not apply however in the case
13677       --  where the scope of the type is a private child unit, or when the
13678       --  parent comes from a local package in which the ancestor is currently
13679       --  visible. The latter suppression of visibility is needed for cases
13680       --  that are tested in B730006.
13681
13682       elsif Is_Private_Type (Original_Scope)
13683         or else
13684           (not Is_Private_Descendant (Type_Scope)
13685             and then not In_Open_Scopes (Type_Scope)
13686             and then Has_Private_Declaration (Original_Scope))
13687       then
13688          --  If the type derives from an entity in a formal package, there
13689          --  are no additional visible components.
13690
13691          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
13692             N_Formal_Package_Declaration
13693          then
13694             return False;
13695
13696          --  if we are not in the private part of the current package, there
13697          --  are no additional visible components.
13698
13699          elsif Ekind (Scope (Current_Scope)) = E_Package
13700            and then not In_Private_Part (Scope (Current_Scope))
13701          then
13702             return False;
13703          else
13704             return
13705               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
13706                 and then In_Open_Scopes (Scope (Original_Scope))
13707                 and then Is_Local_Type (Type_Scope);
13708          end if;
13709
13710       --  There is another weird way in which a component may be invisible
13711       --  when the private and the full view are not derived from the same
13712       --  ancestor. Here is an example :
13713
13714       --       type A1 is tagged      record F1 : integer; end record;
13715       --       type A2 is new A1 with record F2 : integer; end record;
13716       --       type T is new A1 with private;
13717       --     private
13718       --       type T is new A2 with null record;
13719
13720       --  In this case, the full view of T inherits F1 and F2 but the private
13721       --  view inherits only F1
13722
13723       else
13724          declare
13725             Ancestor : Entity_Id := Scope (C);
13726
13727          begin
13728             loop
13729                if Ancestor = Original_Scope then
13730                   return True;
13731                elsif Ancestor = Etype (Ancestor) then
13732                   return False;
13733                end if;
13734
13735                Ancestor := Etype (Ancestor);
13736             end loop;
13737
13738             return True;
13739          end;
13740       end if;
13741    end Is_Visible_Component;
13742
13743    --------------------------
13744    -- Make_Class_Wide_Type --
13745    --------------------------
13746
13747    procedure Make_Class_Wide_Type (T : Entity_Id) is
13748       CW_Type : Entity_Id;
13749       CW_Name : Name_Id;
13750       Next_E  : Entity_Id;
13751
13752    begin
13753       --  The class wide type can have been defined by the partial view, in
13754       --  which case everything is already done.
13755
13756       if Present (Class_Wide_Type (T)) then
13757          return;
13758       end if;
13759
13760       CW_Type :=
13761         New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
13762
13763       --  Inherit root type characteristics
13764
13765       CW_Name := Chars (CW_Type);
13766       Next_E  := Next_Entity (CW_Type);
13767       Copy_Node (T, CW_Type);
13768       Set_Comes_From_Source (CW_Type, False);
13769       Set_Chars (CW_Type, CW_Name);
13770       Set_Parent (CW_Type, Parent (T));
13771       Set_Next_Entity (CW_Type, Next_E);
13772
13773       --  Ensure we have a new freeze node for the class-wide type. The partial
13774       --  view may have freeze action of its own, requiring a proper freeze
13775       --  node, and the same freeze node cannot be shared between the two
13776       --  types.
13777
13778       Set_Has_Delayed_Freeze (CW_Type);
13779       Set_Freeze_Node (CW_Type, Empty);
13780
13781       --  Customize the class-wide type: It has no prim. op., it cannot be
13782       --  abstract and its Etype points back to the specific root type.
13783
13784       Set_Ekind                (CW_Type, E_Class_Wide_Type);
13785       Set_Is_Tagged_Type       (CW_Type, True);
13786       Set_Primitive_Operations (CW_Type, New_Elmt_List);
13787       Set_Is_Abstract_Type     (CW_Type, False);
13788       Set_Is_Constrained       (CW_Type, False);
13789       Set_Is_First_Subtype     (CW_Type, Is_First_Subtype (T));
13790       Init_Size_Align          (CW_Type);
13791
13792       if Ekind (T) = E_Class_Wide_Subtype then
13793          Set_Etype             (CW_Type, Etype (Base_Type (T)));
13794       else
13795          Set_Etype             (CW_Type, T);
13796       end if;
13797
13798       --  If this is the class_wide type of a constrained subtype, it does
13799       --  not have discriminants.
13800
13801       Set_Has_Discriminants (CW_Type,
13802         Has_Discriminants (T) and then not Is_Constrained (T));
13803
13804       Set_Has_Unknown_Discriminants (CW_Type, True);
13805       Set_Class_Wide_Type (T, CW_Type);
13806       Set_Equivalent_Type (CW_Type, Empty);
13807
13808       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
13809
13810       Set_Class_Wide_Type (CW_Type, CW_Type);
13811    end Make_Class_Wide_Type;
13812
13813    ----------------
13814    -- Make_Index --
13815    ----------------
13816
13817    procedure Make_Index
13818      (I            : Node_Id;
13819       Related_Nod  : Node_Id;
13820       Related_Id   : Entity_Id := Empty;
13821       Suffix_Index : Nat := 1)
13822    is
13823       R      : Node_Id;
13824       T      : Entity_Id;
13825       Def_Id : Entity_Id := Empty;
13826       Found  : Boolean := False;
13827
13828    begin
13829       --  For a discrete range used in a constrained array definition and
13830       --  defined by a range, an implicit conversion to the predefined type
13831       --  INTEGER is assumed if each bound is either a numeric literal, a named
13832       --  number, or an attribute, and the type of both bounds (prior to the
13833       --  implicit conversion) is the type universal_integer. Otherwise, both
13834       --  bounds must be of the same discrete type, other than universal
13835       --  integer; this type must be determinable independently of the
13836       --  context, but using the fact that the type must be discrete and that
13837       --  both bounds must have the same type.
13838
13839       --  Character literals also have a universal type in the absence of
13840       --  of additional context,  and are resolved to Standard_Character.
13841
13842       if Nkind (I) = N_Range then
13843
13844          --  The index is given by a range constraint. The bounds are known
13845          --  to be of a consistent type.
13846
13847          if not Is_Overloaded (I) then
13848             T := Etype (I);
13849
13850             --  For universal bounds, choose the specific predefined type
13851
13852             if T = Universal_Integer then
13853                T := Standard_Integer;
13854
13855             elsif T = Any_Character then
13856                Ambiguous_Character (Low_Bound (I));
13857
13858                T := Standard_Character;
13859             end if;
13860
13861          else
13862             T := Any_Type;
13863
13864             declare
13865                Ind : Interp_Index;
13866                It  : Interp;
13867
13868             begin
13869                Get_First_Interp (I, Ind, It);
13870                while Present (It.Typ) loop
13871                   if Is_Discrete_Type (It.Typ) then
13872
13873                      if Found
13874                        and then not Covers (It.Typ, T)
13875                        and then not Covers (T, It.Typ)
13876                      then
13877                         Error_Msg_N ("ambiguous bounds in discrete range", I);
13878                         exit;
13879                      else
13880                         T := It.Typ;
13881                         Found := True;
13882                      end if;
13883                   end if;
13884
13885                   Get_Next_Interp (Ind, It);
13886                end loop;
13887
13888                if T = Any_Type then
13889                   Error_Msg_N ("discrete type required for range", I);
13890                   Set_Etype (I, Any_Type);
13891                   return;
13892
13893                elsif T = Universal_Integer then
13894                   T := Standard_Integer;
13895                end if;
13896             end;
13897          end if;
13898
13899          if not Is_Discrete_Type (T) then
13900             Error_Msg_N ("discrete type required for range", I);
13901             Set_Etype (I, Any_Type);
13902             return;
13903          end if;
13904
13905          if Nkind (Low_Bound (I)) = N_Attribute_Reference
13906            and then Attribute_Name (Low_Bound (I)) = Name_First
13907            and then Is_Entity_Name (Prefix (Low_Bound (I)))
13908            and then Is_Type (Entity (Prefix (Low_Bound (I))))
13909            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
13910          then
13911             --  The type of the index will be the type of the prefix, as long
13912             --  as the upper bound is 'Last of the same type.
13913
13914             Def_Id := Entity (Prefix (Low_Bound (I)));
13915
13916             if Nkind (High_Bound (I)) /= N_Attribute_Reference
13917               or else Attribute_Name (High_Bound (I)) /= Name_Last
13918               or else not Is_Entity_Name (Prefix (High_Bound (I)))
13919               or else Entity (Prefix (High_Bound (I))) /= Def_Id
13920             then
13921                Def_Id := Empty;
13922             end if;
13923          end if;
13924
13925          R := I;
13926          Process_Range_Expr_In_Decl (R, T);
13927
13928       elsif Nkind (I) = N_Subtype_Indication then
13929
13930          --  The index is given by a subtype with a range constraint
13931
13932          T :=  Base_Type (Entity (Subtype_Mark (I)));
13933
13934          if not Is_Discrete_Type (T) then
13935             Error_Msg_N ("discrete type required for range", I);
13936             Set_Etype (I, Any_Type);
13937             return;
13938          end if;
13939
13940          R := Range_Expression (Constraint (I));
13941
13942          Resolve (R, T);
13943          Process_Range_Expr_In_Decl (R, Entity (Subtype_Mark (I)));
13944
13945       elsif Nkind (I) = N_Attribute_Reference then
13946
13947          --  The parser guarantees that the attribute is a RANGE attribute
13948
13949          --  If the node denotes the range of a type mark, that is also the
13950          --  resulting type, and we do no need to create an Itype for it.
13951
13952          if Is_Entity_Name (Prefix (I))
13953            and then Comes_From_Source (I)
13954            and then Is_Type (Entity (Prefix (I)))
13955            and then Is_Discrete_Type (Entity (Prefix (I)))
13956          then
13957             Def_Id := Entity (Prefix (I));
13958          end if;
13959
13960          Analyze_And_Resolve (I);
13961          T := Etype (I);
13962          R := I;
13963
13964       --  If none of the above, must be a subtype. We convert this to a
13965       --  range attribute reference because in the case of declared first
13966       --  named subtypes, the types in the range reference can be different
13967       --  from the type of the entity. A range attribute normalizes the
13968       --  reference and obtains the correct types for the bounds.
13969
13970       --  This transformation is in the nature of an expansion, is only
13971       --  done if expansion is active. In particular, it is not done on
13972       --  formal generic types,  because we need to retain the name of the
13973       --  original index for instantiation purposes.
13974
13975       else
13976          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
13977             Error_Msg_N ("invalid subtype mark in discrete range ", I);
13978             Set_Etype (I, Any_Integer);
13979             return;
13980
13981          else
13982             --  The type mark may be that of an incomplete type. It is only
13983             --  now that we can get the full view, previous analysis does
13984             --  not look specifically for a type mark.
13985
13986             Set_Entity (I, Get_Full_View (Entity (I)));
13987             Set_Etype  (I, Entity (I));
13988             Def_Id := Entity (I);
13989
13990             if not Is_Discrete_Type (Def_Id) then
13991                Error_Msg_N ("discrete type required for index", I);
13992                Set_Etype (I, Any_Type);
13993                return;
13994             end if;
13995          end if;
13996
13997          if Expander_Active then
13998             Rewrite (I,
13999               Make_Attribute_Reference (Sloc (I),
14000                 Attribute_Name => Name_Range,
14001                 Prefix         => Relocate_Node (I)));
14002
14003             --  The original was a subtype mark that does not freeze. This
14004             --  means that the rewritten version must not freeze either.
14005
14006             Set_Must_Not_Freeze (I);
14007             Set_Must_Not_Freeze (Prefix (I));
14008
14009             --  Is order critical??? if so, document why, if not
14010             --  use Analyze_And_Resolve
14011
14012             Analyze_And_Resolve (I);
14013             T := Etype (I);
14014             R := I;
14015
14016          --  If expander is inactive, type is legal, nothing else to construct
14017
14018          else
14019             return;
14020          end if;
14021       end if;
14022
14023       if not Is_Discrete_Type (T) then
14024          Error_Msg_N ("discrete type required for range", I);
14025          Set_Etype (I, Any_Type);
14026          return;
14027
14028       elsif T = Any_Type then
14029          Set_Etype (I, Any_Type);
14030          return;
14031       end if;
14032
14033       --  We will now create the appropriate Itype to describe the range, but
14034       --  first a check. If we originally had a subtype, then we just label
14035       --  the range with this subtype. Not only is there no need to construct
14036       --  a new subtype, but it is wrong to do so for two reasons:
14037
14038       --    1. A legality concern, if we have a subtype, it must not freeze,
14039       --       and the Itype would cause freezing incorrectly
14040
14041       --    2. An efficiency concern, if we created an Itype, it would not be
14042       --       recognized as the same type for the purposes of eliminating
14043       --       checks in some circumstances.
14044
14045       --  We signal this case by setting the subtype entity in Def_Id
14046
14047       if No (Def_Id) then
14048          Def_Id :=
14049            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
14050          Set_Etype (Def_Id, Base_Type (T));
14051
14052          if Is_Signed_Integer_Type (T) then
14053             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
14054
14055          elsif Is_Modular_Integer_Type (T) then
14056             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
14057
14058          else
14059             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
14060             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
14061             Set_First_Literal     (Def_Id, First_Literal (T));
14062          end if;
14063
14064          Set_Size_Info      (Def_Id,                  (T));
14065          Set_RM_Size        (Def_Id, RM_Size          (T));
14066          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
14067
14068          Set_Scalar_Range   (Def_Id, R);
14069          Conditional_Delay  (Def_Id, T);
14070
14071          --  In the subtype indication case, if the immediate parent of the
14072          --  new subtype is non-static, then the subtype we create is non-
14073          --  static, even if its bounds are static.
14074
14075          if Nkind (I) = N_Subtype_Indication
14076            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
14077          then
14078             Set_Is_Non_Static_Subtype (Def_Id);
14079          end if;
14080       end if;
14081
14082       --  Final step is to label the index with this constructed type
14083
14084       Set_Etype (I, Def_Id);
14085    end Make_Index;
14086
14087    ------------------------------
14088    -- Modular_Type_Declaration --
14089    ------------------------------
14090
14091    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14092       Mod_Expr : constant Node_Id := Expression (Def);
14093       M_Val    : Uint;
14094
14095       procedure Set_Modular_Size (Bits : Int);
14096       --  Sets RM_Size to Bits, and Esize to normal word size above this
14097
14098       ----------------------
14099       -- Set_Modular_Size --
14100       ----------------------
14101
14102       procedure Set_Modular_Size (Bits : Int) is
14103       begin
14104          Set_RM_Size (T, UI_From_Int (Bits));
14105
14106          if Bits <= 8 then
14107             Init_Esize (T, 8);
14108
14109          elsif Bits <= 16 then
14110             Init_Esize (T, 16);
14111
14112          elsif Bits <= 32 then
14113             Init_Esize (T, 32);
14114
14115          else
14116             Init_Esize (T, System_Max_Binary_Modulus_Power);
14117          end if;
14118       end Set_Modular_Size;
14119
14120    --  Start of processing for Modular_Type_Declaration
14121
14122    begin
14123       Analyze_And_Resolve (Mod_Expr, Any_Integer);
14124       Set_Etype (T, T);
14125       Set_Ekind (T, E_Modular_Integer_Type);
14126       Init_Alignment (T);
14127       Set_Is_Constrained (T);
14128
14129       if not Is_OK_Static_Expression (Mod_Expr) then
14130          Flag_Non_Static_Expr
14131            ("non-static expression used for modular type bound!", Mod_Expr);
14132          M_Val := 2 ** System_Max_Binary_Modulus_Power;
14133       else
14134          M_Val := Expr_Value (Mod_Expr);
14135       end if;
14136
14137       if M_Val < 1 then
14138          Error_Msg_N ("modulus value must be positive", Mod_Expr);
14139          M_Val := 2 ** System_Max_Binary_Modulus_Power;
14140       end if;
14141
14142       Set_Modulus (T, M_Val);
14143
14144       --   Create bounds for the modular type based on the modulus given in
14145       --   the type declaration and then analyze and resolve those bounds.
14146
14147       Set_Scalar_Range (T,
14148         Make_Range (Sloc (Mod_Expr),
14149           Low_Bound  =>
14150             Make_Integer_Literal (Sloc (Mod_Expr), 0),
14151           High_Bound =>
14152             Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
14153
14154       --  Properly analyze the literals for the range. We do this manually
14155       --  because we can't go calling Resolve, since we are resolving these
14156       --  bounds with the type, and this type is certainly not complete yet!
14157
14158       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
14159       Set_Etype (High_Bound (Scalar_Range (T)), T);
14160       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
14161       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
14162
14163       --  Loop through powers of two to find number of bits required
14164
14165       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
14166
14167          --  Binary case
14168
14169          if M_Val = 2 ** Bits then
14170             Set_Modular_Size (Bits);
14171             return;
14172
14173          --  Non-binary case
14174
14175          elsif M_Val < 2 ** Bits then
14176             Set_Non_Binary_Modulus (T);
14177
14178             if Bits > System_Max_Nonbinary_Modulus_Power then
14179                Error_Msg_Uint_1 :=
14180                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
14181                Error_Msg_F
14182                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
14183                Set_Modular_Size (System_Max_Binary_Modulus_Power);
14184                return;
14185
14186             else
14187                --  In the non-binary case, set size as per RM 13.3(55)
14188
14189                Set_Modular_Size (Bits);
14190                return;
14191             end if;
14192          end if;
14193
14194       end loop;
14195
14196       --  If we fall through, then the size exceed System.Max_Binary_Modulus
14197       --  so we just signal an error and set the maximum size.
14198
14199       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
14200       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
14201
14202       Set_Modular_Size (System_Max_Binary_Modulus_Power);
14203       Init_Alignment (T);
14204
14205    end Modular_Type_Declaration;
14206
14207    --------------------------
14208    -- New_Concatenation_Op --
14209    --------------------------
14210
14211    procedure New_Concatenation_Op (Typ : Entity_Id) is
14212       Loc : constant Source_Ptr := Sloc (Typ);
14213       Op  : Entity_Id;
14214
14215       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
14216       --  Create abbreviated declaration for the formal of a predefined
14217       --  Operator 'Op' of type 'Typ'
14218
14219       --------------------
14220       -- Make_Op_Formal --
14221       --------------------
14222
14223       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
14224          Formal : Entity_Id;
14225       begin
14226          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
14227          Set_Etype (Formal, Typ);
14228          Set_Mechanism (Formal, Default_Mechanism);
14229          return Formal;
14230       end Make_Op_Formal;
14231
14232    --  Start of processing for New_Concatenation_Op
14233
14234    begin
14235       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
14236
14237       Set_Ekind                   (Op, E_Operator);
14238       Set_Scope                   (Op, Current_Scope);
14239       Set_Etype                   (Op, Typ);
14240       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
14241       Set_Is_Immediately_Visible  (Op);
14242       Set_Is_Intrinsic_Subprogram (Op);
14243       Set_Has_Completion          (Op);
14244       Append_Entity               (Op, Current_Scope);
14245
14246       Set_Name_Entity_Id (Name_Op_Concat, Op);
14247
14248       Append_Entity (Make_Op_Formal (Typ, Op), Op);
14249       Append_Entity (Make_Op_Formal (Typ, Op), Op);
14250    end New_Concatenation_Op;
14251
14252    -------------------------
14253    -- OK_For_Limited_Init --
14254    -------------------------
14255
14256    --  ???Check all calls of this, and compare the conditions under which it's
14257    --  called.
14258
14259    function OK_For_Limited_Init (Exp : Node_Id) return Boolean is
14260    begin
14261       return Ada_Version >= Ada_05
14262         and then not Debug_Flag_Dot_L
14263         and then OK_For_Limited_Init_In_05 (Exp);
14264    end OK_For_Limited_Init;
14265
14266    -------------------------------
14267    -- OK_For_Limited_Init_In_05 --
14268    -------------------------------
14269
14270    function OK_For_Limited_Init_In_05 (Exp : Node_Id) return Boolean is
14271    begin
14272
14273       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
14274       --  case of limited aggregates (including extension aggregates), and
14275       --  function calls. The function call may have been give in prefixed
14276       --  notation, in which case the original node is an indexed component.
14277
14278       case Nkind (Original_Node (Exp)) is
14279          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
14280             return True;
14281
14282          when N_Qualified_Expression =>
14283             return
14284               OK_For_Limited_Init_In_05 (Expression (Original_Node (Exp)));
14285
14286          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
14287          --  with a function call, the expander has rewritten the call into an
14288          --  N_Type_Conversion node to force displacement of the pointer to
14289          --  reference the component containing the secondary dispatch table.
14290          --  Otherwise a type conversion is not a legal context.
14291
14292          when N_Type_Conversion =>
14293             return not Comes_From_Source (Exp)
14294               and then
14295                 OK_For_Limited_Init_In_05 (Expression (Original_Node (Exp)));
14296
14297          when N_Indexed_Component | N_Selected_Component  =>
14298             return Nkind (Exp) = N_Function_Call;
14299
14300          --  A use of 'Input is a function call, hence allowed. Normally the
14301          --  attribute will be changed to a call, but the attribute by itself
14302          --  can occur with -gnatc.
14303
14304          when N_Attribute_Reference =>
14305             return Attribute_Name (Original_Node (Exp)) = Name_Input;
14306
14307          when others =>
14308             return False;
14309       end case;
14310    end OK_For_Limited_Init_In_05;
14311
14312    -------------------------------------------
14313    -- Ordinary_Fixed_Point_Type_Declaration --
14314    -------------------------------------------
14315
14316    procedure Ordinary_Fixed_Point_Type_Declaration
14317      (T   : Entity_Id;
14318       Def : Node_Id)
14319    is
14320       Loc           : constant Source_Ptr := Sloc (Def);
14321       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
14322       RRS           : constant Node_Id    := Real_Range_Specification (Def);
14323       Implicit_Base : Entity_Id;
14324       Delta_Val     : Ureal;
14325       Small_Val     : Ureal;
14326       Low_Val       : Ureal;
14327       High_Val      : Ureal;
14328
14329    begin
14330       Check_Restriction (No_Fixed_Point, Def);
14331
14332       --  Create implicit base type
14333
14334       Implicit_Base :=
14335         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
14336       Set_Etype (Implicit_Base, Implicit_Base);
14337
14338       --  Analyze and process delta expression
14339
14340       Analyze_And_Resolve (Delta_Expr, Any_Real);
14341
14342       Check_Delta_Expression (Delta_Expr);
14343       Delta_Val := Expr_Value_R (Delta_Expr);
14344
14345       Set_Delta_Value (Implicit_Base, Delta_Val);
14346
14347       --  Compute default small from given delta, which is the largest power
14348       --  of two that does not exceed the given delta value.
14349
14350       declare
14351          Tmp   : Ureal;
14352          Scale : Int;
14353
14354       begin
14355          Tmp := Ureal_1;
14356          Scale := 0;
14357
14358          if Delta_Val < Ureal_1 then
14359             while Delta_Val < Tmp loop
14360                Tmp := Tmp / Ureal_2;
14361                Scale := Scale + 1;
14362             end loop;
14363
14364          else
14365             loop
14366                Tmp := Tmp * Ureal_2;
14367                exit when Tmp > Delta_Val;
14368                Scale := Scale - 1;
14369             end loop;
14370          end if;
14371
14372          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
14373       end;
14374
14375       Set_Small_Value (Implicit_Base, Small_Val);
14376
14377       --  If no range was given, set a dummy range
14378
14379       if RRS <= Empty_Or_Error then
14380          Low_Val  := -Small_Val;
14381          High_Val := Small_Val;
14382
14383       --  Otherwise analyze and process given range
14384
14385       else
14386          declare
14387             Low  : constant Node_Id := Low_Bound  (RRS);
14388             High : constant Node_Id := High_Bound (RRS);
14389
14390          begin
14391             Analyze_And_Resolve (Low, Any_Real);
14392             Analyze_And_Resolve (High, Any_Real);
14393             Check_Real_Bound (Low);
14394             Check_Real_Bound (High);
14395
14396             --  Obtain and set the range
14397
14398             Low_Val  := Expr_Value_R (Low);
14399             High_Val := Expr_Value_R (High);
14400
14401             if Low_Val > High_Val then
14402                Error_Msg_NE ("?fixed point type& has null range", Def, T);
14403             end if;
14404          end;
14405       end if;
14406
14407       --  The range for both the implicit base and the declared first subtype
14408       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
14409       --  set a temporary range in place. Note that the bounds of the base
14410       --  type will be widened to be symmetrical and to fill the available
14411       --  bits when the type is frozen.
14412
14413       --  We could do this with all discrete types, and probably should, but
14414       --  we absolutely have to do it for fixed-point, since the end-points
14415       --  of the range and the size are determined by the small value, which
14416       --  could be reset before the freeze point.
14417
14418       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
14419       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
14420
14421       Init_Size_Align (Implicit_Base);
14422
14423       --  Complete definition of first subtype
14424
14425       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
14426       Set_Etype          (T, Implicit_Base);
14427       Init_Size_Align    (T);
14428       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
14429       Set_Small_Value    (T, Small_Val);
14430       Set_Delta_Value    (T, Delta_Val);
14431       Set_Is_Constrained (T);
14432
14433    end Ordinary_Fixed_Point_Type_Declaration;
14434
14435    ----------------------------------------
14436    -- Prepare_Private_Subtype_Completion --
14437    ----------------------------------------
14438
14439    procedure Prepare_Private_Subtype_Completion
14440      (Id          : Entity_Id;
14441       Related_Nod : Node_Id)
14442    is
14443       Id_B   : constant Entity_Id := Base_Type (Id);
14444       Full_B : constant Entity_Id := Full_View (Id_B);
14445       Full   : Entity_Id;
14446
14447    begin
14448       if Present (Full_B) then
14449
14450          --  The Base_Type is already completed, we can complete the subtype
14451          --  now. We have to create a new entity with the same name, Thus we
14452          --  can't use Create_Itype.
14453
14454          --  This is messy, should be fixed ???
14455
14456          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
14457          Set_Is_Itype (Full);
14458          Set_Associated_Node_For_Itype (Full, Related_Nod);
14459          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
14460       end if;
14461
14462       --  The parent subtype may be private, but the base might not, in some
14463       --  nested instances. In that case, the subtype does not need to be
14464       --  exchanged. It would still be nice to make private subtypes and their
14465       --  bases consistent at all times ???
14466
14467       if Is_Private_Type (Id_B) then
14468          Append_Elmt (Id, Private_Dependents (Id_B));
14469       end if;
14470
14471    end Prepare_Private_Subtype_Completion;
14472
14473    ---------------------------
14474    -- Process_Discriminants --
14475    ---------------------------
14476
14477    procedure Process_Discriminants
14478      (N    : Node_Id;
14479       Prev : Entity_Id := Empty)
14480    is
14481       Elist               : constant Elist_Id := New_Elmt_List;
14482       Id                  : Node_Id;
14483       Discr               : Node_Id;
14484       Discr_Number        : Uint;
14485       Discr_Type          : Entity_Id;
14486       Default_Present     : Boolean := False;
14487       Default_Not_Present : Boolean := False;
14488
14489    begin
14490       --  A composite type other than an array type can have discriminants.
14491       --  On entry, the current scope is the composite type.
14492
14493       --  The discriminants are initially entered into the scope of the type
14494       --  via Enter_Name with the default Ekind of E_Void to prevent premature
14495       --  use, as explained at the end of this procedure.
14496
14497       Discr := First (Discriminant_Specifications (N));
14498       while Present (Discr) loop
14499          Enter_Name (Defining_Identifier (Discr));
14500
14501          --  For navigation purposes we add a reference to the discriminant
14502          --  in the entity for the type. If the current declaration is a
14503          --  completion, place references on the partial view. Otherwise the
14504          --  type is the current scope.
14505
14506          if Present (Prev) then
14507
14508             --  The references go on the partial view, if present. If the
14509             --  partial view has discriminants, the references have been
14510             --  generated already.
14511
14512             if not Has_Discriminants (Prev) then
14513                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
14514             end if;
14515          else
14516             Generate_Reference
14517               (Current_Scope, Defining_Identifier (Discr), 'd');
14518          end if;
14519
14520          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
14521             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
14522
14523             --  Ada 2005 (AI-254)
14524
14525             if Present (Access_To_Subprogram_Definition
14526                          (Discriminant_Type (Discr)))
14527               and then Protected_Present (Access_To_Subprogram_Definition
14528                                            (Discriminant_Type (Discr)))
14529             then
14530                Discr_Type :=
14531                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
14532             end if;
14533
14534          else
14535             Find_Type (Discriminant_Type (Discr));
14536             Discr_Type := Etype (Discriminant_Type (Discr));
14537
14538             if Error_Posted (Discriminant_Type (Discr)) then
14539                Discr_Type := Any_Type;
14540             end if;
14541          end if;
14542
14543          if Is_Access_Type (Discr_Type) then
14544
14545             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
14546             --  record types
14547
14548             if Ada_Version < Ada_05 then
14549                Check_Access_Discriminant_Requires_Limited
14550                  (Discr, Discriminant_Type (Discr));
14551             end if;
14552
14553             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
14554                Error_Msg_N
14555                  ("(Ada 83) access discriminant not allowed", Discr);
14556             end if;
14557
14558          elsif not Is_Discrete_Type (Discr_Type) then
14559             Error_Msg_N ("discriminants must have a discrete or access type",
14560               Discriminant_Type (Discr));
14561          end if;
14562
14563          Set_Etype (Defining_Identifier (Discr), Discr_Type);
14564
14565          --  If a discriminant specification includes the assignment compound
14566          --  delimiter followed by an expression, the expression is the default
14567          --  expression of the discriminant; the default expression must be of
14568          --  the type of the discriminant. (RM 3.7.1) Since this expression is
14569          --  a default expression, we do the special preanalysis, since this
14570          --  expression does not freeze (see "Handling of Default and Per-
14571          --  Object Expressions" in spec of package Sem).
14572
14573          if Present (Expression (Discr)) then
14574             Analyze_Per_Use_Expression (Expression (Discr), Discr_Type);
14575
14576             if Nkind (N) = N_Formal_Type_Declaration then
14577                Error_Msg_N
14578                  ("discriminant defaults not allowed for formal type",
14579                   Expression (Discr));
14580
14581             --  Tagged types cannot have defaulted discriminants, but a
14582             --  non-tagged private type with defaulted discriminants
14583             --   can have a tagged completion.
14584
14585             elsif Is_Tagged_Type (Current_Scope)
14586               and then Comes_From_Source (N)
14587             then
14588                Error_Msg_N
14589                  ("discriminants of tagged type cannot have defaults",
14590                   Expression (Discr));
14591
14592             else
14593                Default_Present := True;
14594                Append_Elmt (Expression (Discr), Elist);
14595
14596                --  Tag the defining identifiers for the discriminants with
14597                --  their corresponding default expressions from the tree.
14598
14599                Set_Discriminant_Default_Value
14600                  (Defining_Identifier (Discr), Expression (Discr));
14601             end if;
14602
14603          else
14604             Default_Not_Present := True;
14605          end if;
14606
14607          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
14608          --  Discr_Type but with the null-exclusion attribute
14609
14610          if Ada_Version >= Ada_05 then
14611
14612             --  Ada 2005 (AI-231): Static checks
14613
14614             if Can_Never_Be_Null (Discr_Type) then
14615                Null_Exclusion_Static_Checks (Discr);
14616
14617             elsif Is_Access_Type (Discr_Type)
14618               and then Null_Exclusion_Present (Discr)
14619
14620                --  No need to check itypes because in their case this check
14621                --  was done at their point of creation
14622
14623               and then not Is_Itype (Discr_Type)
14624             then
14625                if Can_Never_Be_Null (Discr_Type) then
14626                   Error_Msg_NE
14627                     ("`NOT NULL` not allowed (& already excludes null)",
14628                      Discr,
14629                      Discr_Type);
14630                end if;
14631
14632                Set_Etype (Defining_Identifier (Discr),
14633                  Create_Null_Excluding_Itype
14634                    (T           => Discr_Type,
14635                     Related_Nod => Discr));
14636             end if;
14637
14638             --  Ada 2005 (AI-402): access discriminants of nonlimited types
14639             --  can't have defaults
14640
14641             if Is_Access_Type (Discr_Type) then
14642                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
14643                  or else not Default_Present
14644                  or else Is_Limited_Record (Current_Scope)
14645                  or else Is_Concurrent_Type (Current_Scope)
14646                  or else Is_Concurrent_Record_Type (Current_Scope)
14647                  or else Ekind (Current_Scope) = E_Limited_Private_Type
14648                then
14649                   null;
14650
14651                elsif Present (Expression (Discr)) then
14652                   Error_Msg_N
14653                     ("(Ada 2005) access discriminants of nonlimited types",
14654                      Expression (Discr));
14655                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
14656                end if;
14657             end if;
14658          end if;
14659
14660          Next (Discr);
14661       end loop;
14662
14663       --  An element list consisting of the default expressions of the
14664       --  discriminants is constructed in the above loop and used to set
14665       --  the Discriminant_Constraint attribute for the type. If an object
14666       --  is declared of this (record or task) type without any explicit
14667       --  discriminant constraint given, this element list will form the
14668       --  actual parameters for the corresponding initialization procedure
14669       --  for the type.
14670
14671       Set_Discriminant_Constraint (Current_Scope, Elist);
14672       Set_Stored_Constraint (Current_Scope, No_Elist);
14673
14674       --  Default expressions must be provided either for all or for none
14675       --  of the discriminants of a discriminant part. (RM 3.7.1)
14676
14677       if Default_Present and then Default_Not_Present then
14678          Error_Msg_N
14679            ("incomplete specification of defaults for discriminants", N);
14680       end if;
14681
14682       --  The use of the name of a discriminant is not allowed in default
14683       --  expressions of a discriminant part if the specification of the
14684       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
14685
14686       --  To detect this, the discriminant names are entered initially with an
14687       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
14688       --  attempt to use a void entity (for example in an expression that is
14689       --  type-checked) produces the error message: premature usage. Now after
14690       --  completing the semantic analysis of the discriminant part, we can set
14691       --  the Ekind of all the discriminants appropriately.
14692
14693       Discr := First (Discriminant_Specifications (N));
14694       Discr_Number := Uint_1;
14695       while Present (Discr) loop
14696          Id := Defining_Identifier (Discr);
14697          Set_Ekind (Id, E_Discriminant);
14698          Init_Component_Location (Id);
14699          Init_Esize (Id);
14700          Set_Discriminant_Number (Id, Discr_Number);
14701
14702          --  Make sure this is always set, even in illegal programs
14703
14704          Set_Corresponding_Discriminant (Id, Empty);
14705
14706          --  Initialize the Original_Record_Component to the entity itself.
14707          --  Inherit_Components will propagate the right value to
14708          --  discriminants in derived record types.
14709
14710          Set_Original_Record_Component (Id, Id);
14711
14712          --  Create the discriminal for the discriminant
14713
14714          Build_Discriminal (Id);
14715
14716          Next (Discr);
14717          Discr_Number := Discr_Number + 1;
14718       end loop;
14719
14720       Set_Has_Discriminants (Current_Scope);
14721    end Process_Discriminants;
14722
14723    -----------------------
14724    -- Process_Full_View --
14725    -----------------------
14726
14727    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
14728       Priv_Parent : Entity_Id;
14729       Full_Parent : Entity_Id;
14730       Full_Indic  : Node_Id;
14731
14732       procedure Collect_Implemented_Interfaces
14733         (Typ    : Entity_Id;
14734          Ifaces : Elist_Id);
14735       --  Ada 2005: Gather all the interfaces that Typ directly or
14736       --  inherently implements. Duplicate entries are not added to
14737       --  the list Ifaces.
14738
14739       ------------------------------------
14740       -- Collect_Implemented_Interfaces --
14741       ------------------------------------
14742
14743       procedure Collect_Implemented_Interfaces
14744         (Typ    : Entity_Id;
14745          Ifaces : Elist_Id)
14746       is
14747          Iface      : Entity_Id;
14748          Iface_Elmt : Elmt_Id;
14749
14750       begin
14751          --  Abstract interfaces are only associated with tagged record types
14752
14753          if not Is_Tagged_Type (Typ)
14754            or else not Is_Record_Type (Typ)
14755          then
14756             return;
14757          end if;
14758
14759          --  Recursively climb to the ancestors
14760
14761          if Etype (Typ) /= Typ
14762
14763             --  Protect the frontend against wrong cyclic declarations like:
14764
14765             --     type B is new A with private;
14766             --     type C is new A with private;
14767             --  private
14768             --     type B is new C with null record;
14769             --     type C is new B with null record;
14770
14771            and then Etype (Typ) /= Priv_T
14772            and then Etype (Typ) /= Full_T
14773          then
14774             --  Keep separate the management of private type declarations
14775
14776             if Ekind (Typ) = E_Record_Type_With_Private then
14777
14778                --  Handle the following erronous case:
14779                --      type Private_Type is tagged private;
14780                --   private
14781                --      type Private_Type is new Type_Implementing_Iface;
14782
14783                if Present (Full_View (Typ))
14784                  and then Etype (Typ) /= Full_View (Typ)
14785                then
14786                   if Is_Interface (Etype (Typ)) then
14787                      Append_Unique_Elmt (Etype (Typ), Ifaces);
14788                   end if;
14789
14790                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
14791                end if;
14792
14793             --  Non-private types
14794
14795             else
14796                if Is_Interface (Etype (Typ)) then
14797                   Append_Unique_Elmt (Etype (Typ), Ifaces);
14798                end if;
14799
14800                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
14801             end if;
14802          end if;
14803
14804          --  Handle entities in the list of abstract interfaces
14805
14806          if Present (Abstract_Interfaces (Typ)) then
14807             Iface_Elmt := First_Elmt (Abstract_Interfaces (Typ));
14808             while Present (Iface_Elmt) loop
14809                Iface := Node (Iface_Elmt);
14810
14811                pragma Assert (Is_Interface (Iface));
14812
14813                if not Contain_Interface (Iface, Ifaces) then
14814                   Append_Elmt (Iface, Ifaces);
14815                   Collect_Implemented_Interfaces (Iface, Ifaces);
14816                end if;
14817
14818                Next_Elmt (Iface_Elmt);
14819             end loop;
14820          end if;
14821       end Collect_Implemented_Interfaces;
14822
14823    --  Start of processing for Process_Full_View
14824
14825    begin
14826       --  First some sanity checks that must be done after semantic
14827       --  decoration of the full view and thus cannot be placed with other
14828       --  similar checks in Find_Type_Name
14829
14830       if not Is_Limited_Type (Priv_T)
14831         and then (Is_Limited_Type (Full_T)
14832                    or else Is_Limited_Composite (Full_T))
14833       then
14834          Error_Msg_N
14835            ("completion of nonlimited type cannot be limited", Full_T);
14836          Explain_Limited_Type (Full_T, Full_T);
14837
14838       elsif Is_Abstract_Type (Full_T)
14839         and then not Is_Abstract_Type (Priv_T)
14840       then
14841          Error_Msg_N
14842            ("completion of nonabstract type cannot be abstract", Full_T);
14843
14844       elsif Is_Tagged_Type (Priv_T)
14845         and then Is_Limited_Type (Priv_T)
14846         and then not Is_Limited_Type (Full_T)
14847       then
14848          --  If pragma CPP_Class was applied to the private declaration
14849          --  propagate the limitedness to the full-view
14850
14851          if Is_CPP_Class (Priv_T) then
14852             Set_Is_Limited_Record (Full_T);
14853
14854          --  GNAT allow its own definition of Limited_Controlled to disobey
14855          --  this rule in order in ease the implementation. The next test is
14856          --  safe because Root_Controlled is defined in a private system child
14857
14858          elsif Etype (Full_T) = Full_View (RTE (RE_Root_Controlled)) then
14859             Set_Is_Limited_Composite (Full_T);
14860          else
14861             Error_Msg_N
14862               ("completion of limited tagged type must be limited", Full_T);
14863          end if;
14864
14865       elsif Is_Generic_Type (Priv_T) then
14866          Error_Msg_N ("generic type cannot have a completion", Full_T);
14867       end if;
14868
14869       --  Check that ancestor interfaces of private and full views are
14870       --  consistent. We omit this check for synchronized types because
14871       --  they are performed on the corresponding record type when frozen.
14872
14873       if Ada_Version >= Ada_05
14874         and then Is_Tagged_Type (Priv_T)
14875         and then Is_Tagged_Type (Full_T)
14876         and then not Is_Concurrent_Type (Full_T)
14877       then
14878          declare
14879             Iface         : Entity_Id;
14880             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
14881             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
14882
14883          begin
14884             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
14885             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
14886
14887             --  Ada 2005 (AI-251): The partial view shall be a descendant of
14888             --  an interface type if and only if the full type is descendant
14889             --  of the interface type (AARM 7.3 (7.3/2).
14890
14891             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
14892
14893             if Present (Iface) then
14894                Error_Msg_NE ("interface & not implemented by full type " &
14895                              "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
14896             end if;
14897
14898             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
14899
14900             if Present (Iface) then
14901                Error_Msg_NE ("interface & not implemented by partial view " &
14902                              "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
14903             end if;
14904          end;
14905       end if;
14906
14907       if Is_Tagged_Type (Priv_T)
14908         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
14909         and then Is_Derived_Type (Full_T)
14910       then
14911          Priv_Parent := Etype (Priv_T);
14912
14913          --  The full view of a private extension may have been transformed
14914          --  into an unconstrained derived type declaration and a subtype
14915          --  declaration (see build_derived_record_type for details).
14916
14917          if Nkind (N) = N_Subtype_Declaration then
14918             Full_Indic  := Subtype_Indication (N);
14919             Full_Parent := Etype (Base_Type (Full_T));
14920          else
14921             Full_Indic  := Subtype_Indication (Type_Definition (N));
14922             Full_Parent := Etype (Full_T);
14923          end if;
14924
14925          --  Check that the parent type of the full type is a descendant of
14926          --  the ancestor subtype given in the private extension. If either
14927          --  entity has an Etype equal to Any_Type then we had some previous
14928          --  error situation [7.3(8)].
14929
14930          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
14931             return;
14932
14933          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
14934          --  any order. Therefore we don't have to check that its parent must
14935          --  be a descendant of the parent of the private type declaration.
14936
14937          elsif Is_Interface (Priv_Parent)
14938            and then Is_Interface (Full_Parent)
14939          then
14940             null;
14941
14942          --  Ada 2005 (AI-251): If the parent of the private type declaration
14943          --  is an interface there is no need to check that it is an ancestor
14944          --  of the associated full type declaration. The required tests for
14945          --  this case case are performed by Build_Derived_Record_Type.
14946
14947          elsif not Is_Interface (Base_Type (Priv_Parent))
14948            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
14949          then
14950             Error_Msg_N
14951               ("parent of full type must descend from parent"
14952                   & " of private extension", Full_Indic);
14953
14954          --  Check the rules of 7.3(10): if the private extension inherits
14955          --  known discriminants, then the full type must also inherit those
14956          --  discriminants from the same (ancestor) type, and the parent
14957          --  subtype of the full type must be constrained if and only if
14958          --  the ancestor subtype of the private extension is constrained.
14959
14960          elsif No (Discriminant_Specifications (Parent (Priv_T)))
14961            and then not Has_Unknown_Discriminants (Priv_T)
14962            and then Has_Discriminants (Base_Type (Priv_Parent))
14963          then
14964             declare
14965                Priv_Indic  : constant Node_Id :=
14966                                Subtype_Indication (Parent (Priv_T));
14967
14968                Priv_Constr : constant Boolean :=
14969                                Is_Constrained (Priv_Parent)
14970                                  or else
14971                                    Nkind (Priv_Indic) = N_Subtype_Indication
14972                                  or else Is_Constrained (Entity (Priv_Indic));
14973
14974                Full_Constr : constant Boolean :=
14975                                Is_Constrained (Full_Parent)
14976                                  or else
14977                                    Nkind (Full_Indic) = N_Subtype_Indication
14978                                  or else Is_Constrained (Entity (Full_Indic));
14979
14980                Priv_Discr : Entity_Id;
14981                Full_Discr : Entity_Id;
14982
14983             begin
14984                Priv_Discr := First_Discriminant (Priv_Parent);
14985                Full_Discr := First_Discriminant (Full_Parent);
14986                while Present (Priv_Discr) and then Present (Full_Discr) loop
14987                   if Original_Record_Component (Priv_Discr) =
14988                      Original_Record_Component (Full_Discr)
14989                     or else
14990                      Corresponding_Discriminant (Priv_Discr) =
14991                      Corresponding_Discriminant (Full_Discr)
14992                   then
14993                      null;
14994                   else
14995                      exit;
14996                   end if;
14997
14998                   Next_Discriminant (Priv_Discr);
14999                   Next_Discriminant (Full_Discr);
15000                end loop;
15001
15002                if Present (Priv_Discr) or else Present (Full_Discr) then
15003                   Error_Msg_N
15004                     ("full view must inherit discriminants of the parent type"
15005                      & " used in the private extension", Full_Indic);
15006
15007                elsif Priv_Constr and then not Full_Constr then
15008                   Error_Msg_N
15009                     ("parent subtype of full type must be constrained",
15010                      Full_Indic);
15011
15012                elsif Full_Constr and then not Priv_Constr then
15013                   Error_Msg_N
15014                     ("parent subtype of full type must be unconstrained",
15015                      Full_Indic);
15016                end if;
15017             end;
15018
15019          --  Check the rules of 7.3(12): if a partial view has neither known
15020          --  or unknown discriminants, then the full type declaration shall
15021          --  define a definite subtype.
15022
15023          elsif      not Has_Unknown_Discriminants (Priv_T)
15024            and then not Has_Discriminants (Priv_T)
15025            and then not Is_Constrained (Full_T)
15026          then
15027             Error_Msg_N
15028               ("full view must define a constrained type if partial view"
15029                 & " has no discriminants", Full_T);
15030          end if;
15031
15032          --  ??????? Do we implement the following properly ?????
15033          --  If the ancestor subtype of a private extension has constrained
15034          --  discriminants, then the parent subtype of the full view shall
15035          --  impose a statically matching constraint on those discriminants
15036          --  [7.3(13)].
15037
15038       else
15039          --  For untagged types, verify that a type without discriminants
15040          --  is not completed with an unconstrained type.
15041
15042          if not Is_Indefinite_Subtype (Priv_T)
15043            and then Is_Indefinite_Subtype (Full_T)
15044          then
15045             Error_Msg_N ("full view of type must be definite subtype", Full_T);
15046          end if;
15047       end if;
15048
15049       --  AI-419: verify that the use of "limited" is consistent
15050
15051       declare
15052          Orig_Decl : constant Node_Id := Original_Node (N);
15053
15054       begin
15055          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
15056            and then not Limited_Present (Parent (Priv_T))
15057            and then not Synchronized_Present (Parent (Priv_T))
15058            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
15059            and then Nkind
15060              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
15061            and then Limited_Present (Type_Definition (Orig_Decl))
15062          then
15063             Error_Msg_N
15064               ("full view of non-limited extension cannot be limited", N);
15065          end if;
15066       end;
15067
15068       --  Ada 2005 (AI-443): A synchronized private extension must be
15069       --  completed by a task or protected type.
15070
15071       if Ada_Version >= Ada_05
15072         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
15073         and then Synchronized_Present (Parent (Priv_T))
15074         and then not Is_Concurrent_Type (Full_T)
15075       then
15076          Error_Msg_N ("full view of synchronized extension must " &
15077                       "be synchronized type", N);
15078       end if;
15079
15080       --  Ada 2005 AI-363: if the full view has discriminants with
15081       --  defaults, it is illegal to declare constrained access subtypes
15082       --  whose designated type is the current type. This allows objects
15083       --  of the type that are declared in the heap to be unconstrained.
15084
15085       if not Has_Unknown_Discriminants (Priv_T)
15086         and then not Has_Discriminants (Priv_T)
15087         and then Has_Discriminants (Full_T)
15088         and then
15089           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
15090       then
15091          Set_Has_Constrained_Partial_View (Full_T);
15092          Set_Has_Constrained_Partial_View (Priv_T);
15093       end if;
15094
15095       --  Create a full declaration for all its subtypes recorded in
15096       --  Private_Dependents and swap them similarly to the base type. These
15097       --  are subtypes that have been define before the full declaration of
15098       --  the private type. We also swap the entry in Private_Dependents list
15099       --  so we can properly restore the private view on exit from the scope.
15100
15101       declare
15102          Priv_Elmt : Elmt_Id;
15103          Priv      : Entity_Id;
15104          Full      : Entity_Id;
15105
15106       begin
15107          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
15108          while Present (Priv_Elmt) loop
15109             Priv := Node (Priv_Elmt);
15110
15111             if Ekind (Priv) = E_Private_Subtype
15112               or else Ekind (Priv) = E_Limited_Private_Subtype
15113               or else Ekind (Priv) = E_Record_Subtype_With_Private
15114             then
15115                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
15116                Set_Is_Itype (Full);
15117                Set_Parent (Full, Parent (Priv));
15118                Set_Associated_Node_For_Itype (Full, N);
15119
15120                --  Now we need to complete the private subtype, but since the
15121                --  base type has already been swapped, we must also swap the
15122                --  subtypes (and thus, reverse the arguments in the call to
15123                --  Complete_Private_Subtype).
15124
15125                Copy_And_Swap (Priv, Full);
15126                Complete_Private_Subtype (Full, Priv, Full_T, N);
15127                Replace_Elmt (Priv_Elmt, Full);
15128             end if;
15129
15130             Next_Elmt (Priv_Elmt);
15131          end loop;
15132       end;
15133
15134       --  If the private view was tagged, copy the new primitive operations
15135       --  from the private view to the full view.
15136
15137       if Is_Tagged_Type (Full_T)
15138         and then not Is_Concurrent_Type (Full_T)
15139       then
15140          declare
15141             Priv_List : Elist_Id;
15142             Full_List : constant Elist_Id := Primitive_Operations (Full_T);
15143             P1, P2    : Elmt_Id;
15144             Prim      : Entity_Id;
15145             D_Type    : Entity_Id;
15146
15147          begin
15148             if Is_Tagged_Type (Priv_T) then
15149                Priv_List := Primitive_Operations (Priv_T);
15150
15151                P1 := First_Elmt (Priv_List);
15152                while Present (P1) loop
15153                   Prim := Node (P1);
15154
15155                   --  Transfer explicit primitives, not those inherited from
15156                   --  parent of partial view, which will be re-inherited on
15157                   --  the full view.
15158
15159                   if Comes_From_Source (Prim) then
15160                      P2 := First_Elmt (Full_List);
15161                      while Present (P2) and then Node (P2) /= Prim loop
15162                         Next_Elmt (P2);
15163                      end loop;
15164
15165                      --  If not found, that is a new one
15166
15167                      if No (P2) then
15168                         Append_Elmt (Prim, Full_List);
15169                      end if;
15170                   end if;
15171
15172                   Next_Elmt (P1);
15173                end loop;
15174
15175             else
15176                --  In this case the partial view is untagged, so here we locate
15177                --  all of the earlier primitives that need to be treated as
15178                --  dispatching (those that appear between the two views). Note
15179                --  that these additional operations must all be new operations
15180                --  (any earlier operations that override inherited operations
15181                --  of the full view will already have been inserted in the
15182                --  primitives list, marked by Check_Operation_From_Private_View
15183                --  as dispatching. Note that implicit "/=" operators are
15184                --  excluded from being added to the primitives list since they
15185                --  shouldn't be treated as dispatching (tagged "/=" is handled
15186                --  specially).
15187
15188                Prim := Next_Entity (Full_T);
15189                while Present (Prim) and then Prim /= Priv_T loop
15190                   if Ekind (Prim) = E_Procedure
15191                        or else
15192                      Ekind (Prim) = E_Function
15193                   then
15194
15195                      D_Type := Find_Dispatching_Type (Prim);
15196
15197                      if D_Type = Full_T
15198                        and then (Chars (Prim) /= Name_Op_Ne
15199                                   or else Comes_From_Source (Prim))
15200                      then
15201                         Check_Controlling_Formals (Full_T, Prim);
15202
15203                         if not Is_Dispatching_Operation (Prim) then
15204                            Append_Elmt (Prim, Full_List);
15205                            Set_Is_Dispatching_Operation (Prim, True);
15206                            Set_DT_Position (Prim, No_Uint);
15207                         end if;
15208
15209                      elsif Is_Dispatching_Operation (Prim)
15210                        and then D_Type  /= Full_T
15211                      then
15212
15213                         --  Verify that it is not otherwise controlled by a
15214                         --  formal or a return value of type T.
15215
15216                         Check_Controlling_Formals (D_Type, Prim);
15217                      end if;
15218                   end if;
15219
15220                   Next_Entity (Prim);
15221                end loop;
15222             end if;
15223
15224             --  For the tagged case, the two views can share the same
15225             --  Primitive Operation list and the same class wide type.
15226             --  Update attributes of the class-wide type which depend on
15227             --  the full declaration.
15228
15229             if Is_Tagged_Type (Priv_T) then
15230                Set_Primitive_Operations (Priv_T, Full_List);
15231                Set_Class_Wide_Type
15232                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
15233
15234                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
15235             end if;
15236          end;
15237       end if;
15238
15239       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
15240
15241       if Known_To_Have_Preelab_Init (Priv_T) then
15242
15243          --  Case where there is a pragma Preelaborable_Initialization. We
15244          --  always allow this in predefined units, which is a bit of a kludge,
15245          --  but it means we don't have to struggle to meet the requirements in
15246          --  the RM for having Preelaborable Initialization. Otherwise we
15247          --  require that the type meets the RM rules. But we can't check that
15248          --  yet, because of the rule about overriding Ininitialize, so we
15249          --  simply set a flag that will be checked at freeze time.
15250
15251          if not In_Predefined_Unit (Full_T) then
15252             Set_Must_Have_Preelab_Init (Full_T);
15253          end if;
15254       end if;
15255
15256       --  If pragma CPP_Class was applied to the private type declaration,
15257       --  propagate it now to the full type declaration.
15258
15259       if Is_CPP_Class (Priv_T) then
15260          Set_Is_CPP_Class (Full_T);
15261          Set_Convention   (Full_T, Convention_CPP);
15262       end if;
15263    end Process_Full_View;
15264
15265    -----------------------------------
15266    -- Process_Incomplete_Dependents --
15267    -----------------------------------
15268
15269    procedure Process_Incomplete_Dependents
15270      (N      : Node_Id;
15271       Full_T : Entity_Id;
15272       Inc_T  : Entity_Id)
15273    is
15274       Inc_Elmt : Elmt_Id;
15275       Priv_Dep : Entity_Id;
15276       New_Subt : Entity_Id;
15277
15278       Disc_Constraint : Elist_Id;
15279
15280    begin
15281       if No (Private_Dependents (Inc_T)) then
15282          return;
15283       end if;
15284
15285       --  Itypes that may be generated by the completion of an incomplete
15286       --  subtype are not used by the back-end and not attached to the tree.
15287       --  They are created only for constraint-checking purposes.
15288
15289       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
15290       while Present (Inc_Elmt) loop
15291          Priv_Dep := Node (Inc_Elmt);
15292
15293          if Ekind (Priv_Dep) = E_Subprogram_Type then
15294
15295             --  An Access_To_Subprogram type may have a return type or a
15296             --  parameter type that is incomplete. Replace with the full view.
15297
15298             if Etype (Priv_Dep) = Inc_T then
15299                Set_Etype (Priv_Dep, Full_T);
15300             end if;
15301
15302             declare
15303                Formal : Entity_Id;
15304
15305             begin
15306                Formal := First_Formal (Priv_Dep);
15307                while Present (Formal) loop
15308                   if Etype (Formal) = Inc_T then
15309                      Set_Etype (Formal, Full_T);
15310                   end if;
15311
15312                   Next_Formal (Formal);
15313                end loop;
15314             end;
15315
15316          elsif Is_Overloadable (Priv_Dep) then
15317
15318             --  A protected operation is never dispatching: only its
15319             --  wrapper operation (which has convention Ada) is.
15320
15321             if Is_Tagged_Type (Full_T)
15322               and then Convention (Priv_Dep) /= Convention_Protected
15323             then
15324
15325                --  Subprogram has an access parameter whose designated type
15326                --  was incomplete. Reexamine declaration now, because it may
15327                --  be a primitive operation of the full type.
15328
15329                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
15330                Set_Is_Dispatching_Operation (Priv_Dep);
15331                Check_Controlling_Formals (Full_T, Priv_Dep);
15332             end if;
15333
15334          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
15335
15336             --  Can happen during processing of a body before the completion
15337             --  of a TA type. Ignore, because spec is also on dependent list.
15338
15339             return;
15340
15341          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
15342          --  corresponding subtype of the full view.
15343
15344          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
15345             Set_Subtype_Indication
15346               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
15347             Set_Etype (Priv_Dep, Full_T);
15348             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
15349             Set_Analyzed (Parent (Priv_Dep), False);
15350
15351             --  Reanalyze the declaration, suppressing the call to
15352             --  Enter_Name to avoid duplicate names.
15353
15354             Analyze_Subtype_Declaration
15355               (N    => Parent (Priv_Dep),
15356                Skip => True);
15357
15358          --  Dependent is a subtype
15359
15360          else
15361             --  We build a new subtype indication using the full view of the
15362             --  incomplete parent. The discriminant constraints have been
15363             --  elaborated already at the point of the subtype declaration.
15364
15365             New_Subt := Create_Itype (E_Void, N);
15366
15367             if Has_Discriminants (Full_T) then
15368                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
15369             else
15370                Disc_Constraint := No_Elist;
15371             end if;
15372
15373             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
15374             Set_Full_View (Priv_Dep, New_Subt);
15375          end if;
15376
15377          Next_Elmt (Inc_Elmt);
15378       end loop;
15379    end Process_Incomplete_Dependents;
15380
15381    --------------------------------
15382    -- Process_Range_Expr_In_Decl --
15383    --------------------------------
15384
15385    procedure Process_Range_Expr_In_Decl
15386      (R           : Node_Id;
15387       T           : Entity_Id;
15388       Check_List  : List_Id := Empty_List;
15389       R_Check_Off : Boolean := False)
15390    is
15391       Lo, Hi    : Node_Id;
15392       R_Checks  : Check_Result;
15393       Type_Decl : Node_Id;
15394       Def_Id    : Entity_Id;
15395
15396    begin
15397       Analyze_And_Resolve (R, Base_Type (T));
15398
15399       if Nkind (R) = N_Range then
15400          Lo := Low_Bound (R);
15401          Hi := High_Bound (R);
15402
15403          --  We need to ensure validity of the bounds here, because if we
15404          --  go ahead and do the expansion, then the expanded code will get
15405          --  analyzed with range checks suppressed and we miss the check.
15406
15407          Validity_Check_Range (R);
15408
15409          --  If there were errors in the declaration, try and patch up some
15410          --  common mistakes in the bounds. The cases handled are literals
15411          --  which are Integer where the expected type is Real and vice versa.
15412          --  These corrections allow the compilation process to proceed further
15413          --  along since some basic assumptions of the format of the bounds
15414          --  are guaranteed.
15415
15416          if Etype (R) = Any_Type then
15417
15418             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
15419                Rewrite (Lo,
15420                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
15421
15422             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
15423                Rewrite (Hi,
15424                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
15425
15426             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
15427                Rewrite (Lo,
15428                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
15429
15430             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
15431                Rewrite (Hi,
15432                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
15433             end if;
15434
15435             Set_Etype (Lo, T);
15436             Set_Etype (Hi, T);
15437          end if;
15438
15439          --  If the bounds of the range have been mistakenly given as string
15440          --  literals (perhaps in place of character literals), then an error
15441          --  has already been reported, but we rewrite the string literal as a
15442          --  bound of the range's type to avoid blowups in later processing
15443          --  that looks at static values.
15444
15445          if Nkind (Lo) = N_String_Literal then
15446             Rewrite (Lo,
15447               Make_Attribute_Reference (Sloc (Lo),
15448                 Attribute_Name => Name_First,
15449                 Prefix => New_Reference_To (T, Sloc (Lo))));
15450             Analyze_And_Resolve (Lo);
15451          end if;
15452
15453          if Nkind (Hi) = N_String_Literal then
15454             Rewrite (Hi,
15455               Make_Attribute_Reference (Sloc (Hi),
15456                 Attribute_Name => Name_First,
15457                 Prefix => New_Reference_To (T, Sloc (Hi))));
15458             Analyze_And_Resolve (Hi);
15459          end if;
15460
15461          --  If bounds aren't scalar at this point then exit, avoiding
15462          --  problems with further processing of the range in this procedure.
15463
15464          if not Is_Scalar_Type (Etype (Lo)) then
15465             return;
15466          end if;
15467
15468          --  Resolve (actually Sem_Eval) has checked that the bounds are in
15469          --  then range of the base type. Here we check whether the bounds
15470          --  are in the range of the subtype itself. Note that if the bounds
15471          --  represent the null range the Constraint_Error exception should
15472          --  not be raised.
15473
15474          --  ??? The following code should be cleaned up as follows
15475
15476          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
15477          --     is done in the call to Range_Check (R, T); below
15478
15479          --  2. The use of R_Check_Off should be investigated and possibly
15480          --     removed, this would clean up things a bit.
15481
15482          if Is_Null_Range (Lo, Hi) then
15483             null;
15484
15485          else
15486             --  Capture values of bounds and generate temporaries for them
15487             --  if needed, before applying checks, since checks may cause
15488             --  duplication of the expression without forcing evaluation.
15489
15490             if Expander_Active then
15491                Force_Evaluation (Lo);
15492                Force_Evaluation (Hi);
15493             end if;
15494
15495             --  We use a flag here instead of suppressing checks on the
15496             --  type because the type we check against isn't necessarily
15497             --  the place where we put the check.
15498
15499             if not R_Check_Off then
15500                R_Checks := Get_Range_Checks (R, T);
15501
15502                --  Look up tree to find an appropriate insertion point.
15503                --  This seems really junk code, and very brittle, couldn't
15504                --  we just use an insert actions call of some kind ???
15505
15506                Type_Decl := Parent (R);
15507                while Present (Type_Decl) and then not
15508                  (Nkind (Type_Decl) = N_Full_Type_Declaration
15509                     or else
15510                   Nkind (Type_Decl) = N_Subtype_Declaration
15511                     or else
15512                   Nkind (Type_Decl) = N_Loop_Statement
15513                     or else
15514                   Nkind (Type_Decl) = N_Task_Type_Declaration
15515                     or else
15516                   Nkind (Type_Decl) = N_Single_Task_Declaration
15517                     or else
15518                   Nkind (Type_Decl) = N_Protected_Type_Declaration
15519                     or else
15520                   Nkind (Type_Decl) = N_Single_Protected_Declaration)
15521                loop
15522                   Type_Decl := Parent (Type_Decl);
15523                end loop;
15524
15525                --  Why would Type_Decl not be present???  Without this test,
15526                --  short regression tests fail.
15527
15528                if Present (Type_Decl) then
15529
15530                   --  Case of loop statement (more comments ???)
15531
15532                   if Nkind (Type_Decl) = N_Loop_Statement then
15533                      declare
15534                         Indic : Node_Id;
15535
15536                      begin
15537                         Indic := Parent (R);
15538                         while Present (Indic) and then not
15539                           (Nkind (Indic) = N_Subtype_Indication)
15540                         loop
15541                            Indic := Parent (Indic);
15542                         end loop;
15543
15544                         if Present (Indic) then
15545                            Def_Id := Etype (Subtype_Mark (Indic));
15546
15547                            Insert_Range_Checks
15548                              (R_Checks,
15549                               Type_Decl,
15550                               Def_Id,
15551                               Sloc (Type_Decl),
15552                               R,
15553                               Do_Before => True);
15554                         end if;
15555                      end;
15556
15557                   --  All other cases (more comments ???)
15558
15559                   else
15560                      Def_Id := Defining_Identifier (Type_Decl);
15561
15562                      if (Ekind (Def_Id) = E_Record_Type
15563                           and then Depends_On_Discriminant (R))
15564                        or else
15565                         (Ekind (Def_Id) = E_Protected_Type
15566                           and then Has_Discriminants (Def_Id))
15567                      then
15568                         Append_Range_Checks
15569                           (R_Checks, Check_List, Def_Id, Sloc (Type_Decl), R);
15570
15571                      else
15572                         Insert_Range_Checks
15573                           (R_Checks, Type_Decl, Def_Id, Sloc (Type_Decl), R);
15574
15575                      end if;
15576                   end if;
15577                end if;
15578             end if;
15579          end if;
15580
15581       elsif Expander_Active then
15582          Get_Index_Bounds (R, Lo, Hi);
15583          Force_Evaluation (Lo);
15584          Force_Evaluation (Hi);
15585       end if;
15586    end Process_Range_Expr_In_Decl;
15587
15588    --------------------------------------
15589    -- Process_Real_Range_Specification --
15590    --------------------------------------
15591
15592    procedure Process_Real_Range_Specification (Def : Node_Id) is
15593       Spec : constant Node_Id := Real_Range_Specification (Def);
15594       Lo   : Node_Id;
15595       Hi   : Node_Id;
15596       Err  : Boolean := False;
15597
15598       procedure Analyze_Bound (N : Node_Id);
15599       --  Analyze and check one bound
15600
15601       -------------------
15602       -- Analyze_Bound --
15603       -------------------
15604
15605       procedure Analyze_Bound (N : Node_Id) is
15606       begin
15607          Analyze_And_Resolve (N, Any_Real);
15608
15609          if not Is_OK_Static_Expression (N) then
15610             Flag_Non_Static_Expr
15611               ("bound in real type definition is not static!", N);
15612             Err := True;
15613          end if;
15614       end Analyze_Bound;
15615
15616    --  Start of processing for Process_Real_Range_Specification
15617
15618    begin
15619       if Present (Spec) then
15620          Lo := Low_Bound (Spec);
15621          Hi := High_Bound (Spec);
15622          Analyze_Bound (Lo);
15623          Analyze_Bound (Hi);
15624
15625          --  If error, clear away junk range specification
15626
15627          if Err then
15628             Set_Real_Range_Specification (Def, Empty);
15629          end if;
15630       end if;
15631    end Process_Real_Range_Specification;
15632
15633    ---------------------
15634    -- Process_Subtype --
15635    ---------------------
15636
15637    function Process_Subtype
15638      (S           : Node_Id;
15639       Related_Nod : Node_Id;
15640       Related_Id  : Entity_Id := Empty;
15641       Suffix      : Character := ' ') return Entity_Id
15642    is
15643       P               : Node_Id;
15644       Def_Id          : Entity_Id;
15645       Error_Node      : Node_Id;
15646       Full_View_Id    : Entity_Id;
15647       Subtype_Mark_Id : Entity_Id;
15648
15649       May_Have_Null_Exclusion : Boolean;
15650
15651       procedure Check_Incomplete (T : Entity_Id);
15652       --  Called to verify that an incomplete type is not used prematurely
15653
15654       ----------------------
15655       -- Check_Incomplete --
15656       ----------------------
15657
15658       procedure Check_Incomplete (T : Entity_Id) is
15659       begin
15660          --  Ada 2005 (AI-412): Incomplete subtypes are legal
15661
15662          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
15663            and then
15664              not (Ada_Version >= Ada_05
15665                     and then
15666                        (Nkind (Parent (T)) = N_Subtype_Declaration
15667                           or else
15668                             (Nkind (Parent (T)) = N_Subtype_Indication
15669                                and then Nkind (Parent (Parent (T))) =
15670                                           N_Subtype_Declaration)))
15671          then
15672             Error_Msg_N ("invalid use of type before its full declaration", T);
15673          end if;
15674       end Check_Incomplete;
15675
15676    --  Start of processing for Process_Subtype
15677
15678    begin
15679       --  Case of no constraints present
15680
15681       if Nkind (S) /= N_Subtype_Indication then
15682
15683          Find_Type (S);
15684          Check_Incomplete (S);
15685          P := Parent (S);
15686
15687          --  Ada 2005 (AI-231): Static check
15688
15689          if Ada_Version >= Ada_05
15690            and then Present (P)
15691            and then Null_Exclusion_Present (P)
15692            and then Nkind (P) /= N_Access_To_Object_Definition
15693            and then not Is_Access_Type (Entity (S))
15694          then
15695             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
15696          end if;
15697
15698          May_Have_Null_Exclusion :=
15699            Nkind (P) = N_Access_Definition
15700            or else Nkind (P) = N_Access_Function_Definition
15701            or else Nkind (P) = N_Access_Procedure_Definition
15702            or else Nkind (P) = N_Access_To_Object_Definition
15703            or else Nkind (P) = N_Allocator
15704            or else Nkind (P) = N_Component_Definition
15705            or else Nkind (P) = N_Derived_Type_Definition
15706            or else Nkind (P) = N_Discriminant_Specification
15707            or else Nkind (P) = N_Object_Declaration
15708            or else Nkind (P) = N_Parameter_Specification
15709            or else Nkind (P) = N_Subtype_Declaration;
15710
15711          --  Create an Itype that is a duplicate of Entity (S) but with the
15712          --  null-exclusion attribute
15713
15714          if May_Have_Null_Exclusion
15715            and then Is_Access_Type (Entity (S))
15716            and then Null_Exclusion_Present (P)
15717
15718             --  No need to check the case of an access to object definition.
15719             --  It is correct to define double not-null pointers.
15720
15721             --  Example:
15722             --     type Not_Null_Int_Ptr is not null access Integer;
15723             --     type Acc is not null access Not_Null_Int_Ptr;
15724
15725            and then Nkind (P) /= N_Access_To_Object_Definition
15726          then
15727             if Can_Never_Be_Null (Entity (S)) then
15728                case Nkind (Related_Nod) is
15729                   when N_Full_Type_Declaration =>
15730                      if Nkind (Type_Definition (Related_Nod))
15731                        in N_Array_Type_Definition
15732                      then
15733                         Error_Node :=
15734                           Subtype_Indication
15735                             (Component_Definition
15736                              (Type_Definition (Related_Nod)));
15737                      else
15738                         Error_Node :=
15739                           Subtype_Indication (Type_Definition (Related_Nod));
15740                      end if;
15741
15742                   when N_Subtype_Declaration =>
15743                      Error_Node := Subtype_Indication (Related_Nod);
15744
15745                   when N_Object_Declaration =>
15746                      Error_Node := Object_Definition (Related_Nod);
15747
15748                   when N_Component_Declaration =>
15749                      Error_Node :=
15750                        Subtype_Indication (Component_Definition (Related_Nod));
15751
15752                   when others =>
15753                      pragma Assert (False);
15754                      Error_Node := Related_Nod;
15755                end case;
15756
15757                Error_Msg_NE
15758                  ("`NOT NULL` not allowed (& already excludes null)",
15759                   Error_Node,
15760                   Entity (S));
15761             end if;
15762
15763             Set_Etype  (S,
15764               Create_Null_Excluding_Itype
15765                 (T           => Entity (S),
15766                  Related_Nod => P));
15767             Set_Entity (S, Etype (S));
15768          end if;
15769
15770          return Entity (S);
15771
15772       --  Case of constraint present, so that we have an N_Subtype_Indication
15773       --  node (this node is created only if constraints are present).
15774
15775       else
15776          Find_Type (Subtype_Mark (S));
15777
15778          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
15779            and then not
15780             (Nkind (Parent (S)) = N_Subtype_Declaration
15781               and then Is_Itype (Defining_Identifier (Parent (S))))
15782          then
15783             Check_Incomplete (Subtype_Mark (S));
15784          end if;
15785
15786          P := Parent (S);
15787          Subtype_Mark_Id := Entity (Subtype_Mark (S));
15788
15789          --  Explicit subtype declaration case
15790
15791          if Nkind (P) = N_Subtype_Declaration then
15792             Def_Id := Defining_Identifier (P);
15793
15794          --  Explicit derived type definition case
15795
15796          elsif Nkind (P) = N_Derived_Type_Definition then
15797             Def_Id := Defining_Identifier (Parent (P));
15798
15799          --  Implicit case, the Def_Id must be created as an implicit type.
15800          --  The one exception arises in the case of concurrent types, array
15801          --  and access types, where other subsidiary implicit types may be
15802          --  created and must appear before the main implicit type. In these
15803          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
15804          --  has not yet been called to create Def_Id.
15805
15806          else
15807             if Is_Array_Type (Subtype_Mark_Id)
15808               or else Is_Concurrent_Type (Subtype_Mark_Id)
15809               or else Is_Access_Type (Subtype_Mark_Id)
15810             then
15811                Def_Id := Empty;
15812
15813             --  For the other cases, we create a new unattached Itype,
15814             --  and set the indication to ensure it gets attached later.
15815
15816             else
15817                Def_Id :=
15818                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
15819             end if;
15820          end if;
15821
15822          --  If the kind of constraint is invalid for this kind of type,
15823          --  then give an error, and then pretend no constraint was given.
15824
15825          if not Is_Valid_Constraint_Kind
15826                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
15827          then
15828             Error_Msg_N
15829               ("incorrect constraint for this kind of type", Constraint (S));
15830
15831             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
15832
15833             --  Set Ekind of orphan itype, to prevent cascaded errors
15834
15835             if Present (Def_Id) then
15836                Set_Ekind (Def_Id, Ekind (Any_Type));
15837             end if;
15838
15839             --  Make recursive call, having got rid of the bogus constraint
15840
15841             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
15842          end if;
15843
15844          --  Remaining processing depends on type
15845
15846          case Ekind (Subtype_Mark_Id) is
15847             when Access_Kind =>
15848                Constrain_Access (Def_Id, S, Related_Nod);
15849
15850                if Expander_Active
15851                  and then  Is_Itype (Designated_Type (Def_Id))
15852                  and then Nkind (Related_Nod) = N_Subtype_Declaration
15853                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
15854                then
15855                   Build_Itype_Reference
15856                     (Designated_Type (Def_Id), Related_Nod);
15857                end if;
15858
15859             when Array_Kind =>
15860                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
15861
15862             when Decimal_Fixed_Point_Kind =>
15863                Constrain_Decimal (Def_Id, S);
15864
15865             when Enumeration_Kind =>
15866                Constrain_Enumeration (Def_Id, S);
15867
15868             when Ordinary_Fixed_Point_Kind =>
15869                Constrain_Ordinary_Fixed (Def_Id, S);
15870
15871             when Float_Kind =>
15872                Constrain_Float (Def_Id, S);
15873
15874             when Integer_Kind =>
15875                Constrain_Integer (Def_Id, S);
15876
15877             when E_Record_Type     |
15878                  E_Record_Subtype  |
15879                  Class_Wide_Kind   |
15880                  E_Incomplete_Type =>
15881                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
15882
15883             when Private_Kind =>
15884                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
15885                Set_Private_Dependents (Def_Id, New_Elmt_List);
15886
15887                --  In case of an invalid constraint prevent further processing
15888                --  since the type constructed is missing expected fields.
15889
15890                if Etype (Def_Id) = Any_Type then
15891                   return Def_Id;
15892                end if;
15893
15894                --  If the full view is that of a task with discriminants,
15895                --  we must constrain both the concurrent type and its
15896                --  corresponding record type. Otherwise we will just propagate
15897                --  the constraint to the full view, if available.
15898
15899                if Present (Full_View (Subtype_Mark_Id))
15900                  and then Has_Discriminants (Subtype_Mark_Id)
15901                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
15902                then
15903                   Full_View_Id :=
15904                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
15905
15906                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
15907                   Constrain_Concurrent (Full_View_Id, S,
15908                     Related_Nod, Related_Id, Suffix);
15909                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
15910                   Set_Full_View (Def_Id, Full_View_Id);
15911
15912                   --  Introduce an explicit reference to the private subtype,
15913                   --  to prevent scope anomalies in gigi if first use appears
15914                   --  in a nested context, e.g. a later function body.
15915                   --  Should this be generated in other contexts than a full
15916                   --  type declaration?
15917
15918                   if Is_Itype (Def_Id)
15919                     and then
15920                       Nkind (Parent (P)) = N_Full_Type_Declaration
15921                   then
15922                      Build_Itype_Reference (Def_Id, Parent (P));
15923                   end if;
15924
15925                else
15926                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
15927                end if;
15928
15929             when Concurrent_Kind  =>
15930                Constrain_Concurrent (Def_Id, S,
15931                  Related_Nod, Related_Id, Suffix);
15932
15933             when others =>
15934                Error_Msg_N ("invalid subtype mark in subtype indication", S);
15935          end case;
15936
15937          --  Size and Convention are always inherited from the base type
15938
15939          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
15940          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
15941
15942          return Def_Id;
15943       end if;
15944    end Process_Subtype;
15945
15946    ---------------------------------------
15947    -- Check_Anonymous_Access_Components --
15948    ---------------------------------------
15949
15950    procedure Check_Anonymous_Access_Components
15951       (Typ_Decl  : Node_Id;
15952        Typ       : Entity_Id;
15953        Prev      : Entity_Id;
15954        Comp_List : Node_Id)
15955    is
15956       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
15957       Anon_Access : Entity_Id;
15958       Acc_Def     : Node_Id;
15959       Comp        : Node_Id;
15960       Comp_Def    : Node_Id;
15961       Decl        : Node_Id;
15962       Type_Def    : Node_Id;
15963
15964       procedure Build_Incomplete_Type_Declaration;
15965       --  If the record type contains components that include an access to the
15966       --  current record, then create an incomplete type declaration for the
15967       --  record, to be used as the designated type of the anonymous access.
15968       --  This is done only once, and only if there is no previous partial
15969       --  view of the type.
15970
15971       function Mentions_T (Acc_Def : Node_Id) return Boolean;
15972       --  Check whether an access definition includes a reference to
15973       --  the enclosing record type. The reference can be a subtype
15974       --  mark in the access definition itself, or a 'Class attribute
15975       --  reference, or recursively a reference appearing in a parameter
15976       --  type in an access_to_subprogram definition.
15977
15978       --------------------------------------
15979       -- Build_Incomplete_Type_Declaration --
15980       --------------------------------------
15981
15982       procedure Build_Incomplete_Type_Declaration is
15983          Decl  : Node_Id;
15984          Inc_T : Entity_Id;
15985          H     : Entity_Id;
15986
15987       begin
15988          --  If there is a previous partial view, no need to create a new one
15989          --  If the partial view, given by Prev, is incomplete,  If Prev is
15990          --  a private declaration, full declaration is flagged accordingly.
15991
15992          if Prev /= Typ then
15993             if Tagged_Present (Type_Definition (Typ_Decl)) then
15994                Make_Class_Wide_Type (Prev);
15995                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
15996                Set_Etype (Class_Wide_Type (Typ), Typ);
15997             end if;
15998
15999             return;
16000
16001          elsif Has_Private_Declaration (Typ) then
16002             return;
16003
16004          --  If there was a previous anonymous access type, the incomplete
16005          --  type declaration will have been created already.
16006
16007          elsif Present (Current_Entity (Typ))
16008            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
16009            and then Full_View (Current_Entity (Typ)) = Typ
16010          then
16011             return;
16012
16013          else
16014             Inc_T  := Make_Defining_Identifier (Loc, Chars (Typ));
16015             Decl   := Make_Incomplete_Type_Declaration (Loc, Inc_T);
16016
16017             --  Type has already been inserted into the current scope.
16018             --  Remove it, and add incomplete declaration for type, so
16019             --  that subsequent anonymous access types can use it.
16020             --  The entity is unchained from the homonym list and from
16021             --  immediate visibility. After analysis, the entity in the
16022             --  incomplete declaration becomes immediately visible in the
16023             --  record declaration that follows.
16024
16025             H := Current_Entity (Typ);
16026
16027             if H = Typ then
16028                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
16029             else
16030                while Present (H)
16031                  and then Homonym (H) /= Typ
16032                loop
16033                   H := Homonym (Typ);
16034                end loop;
16035
16036                Set_Homonym (H, Homonym (Typ));
16037             end if;
16038
16039             Insert_Before (Typ_Decl, Decl);
16040             Analyze (Decl);
16041             Set_Full_View (Inc_T, Typ);
16042
16043             if (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
16044                  and then
16045                    Present
16046                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
16047               or else Tagged_Present (Type_Definition (Typ_Decl))
16048             then
16049                --  Create a common class-wide type for both views, and set
16050                --  the etype of the class-wide type to the full view.
16051
16052                Make_Class_Wide_Type (Inc_T);
16053                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
16054                Set_Etype (Class_Wide_Type (Typ), Typ);
16055             end if;
16056          end if;
16057       end Build_Incomplete_Type_Declaration;
16058
16059       ----------------
16060       -- Mentions_T --
16061       ----------------
16062
16063       function Mentions_T (Acc_Def : Node_Id) return Boolean is
16064          Subt : Node_Id;
16065          Type_Id : constant Name_Id := Chars (Typ);
16066
16067          function Names_T (Nam : Node_Id) return Boolean;
16068          --  The record type has not been introduced in the current scope
16069          --  yet, so we must examine the name of the type itself, either
16070          --  an identifier T, or an expanded name of the form P.T, where
16071          --  P denotes the current scope.
16072
16073          -------------
16074          -- Names_T --
16075          -------------
16076
16077          function Names_T (Nam : Node_Id) return Boolean is
16078          begin
16079             if Nkind (Nam) = N_Identifier then
16080                return Chars (Nam) = Type_Id;
16081
16082             elsif Nkind (Nam) = N_Selected_Component then
16083                if Chars (Selector_Name (Nam)) = Type_Id then
16084                   if Nkind (Prefix (Nam)) = N_Identifier then
16085                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
16086
16087                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
16088                      return Chars (Selector_Name (Prefix (Nam))) =
16089                             Chars (Current_Scope);
16090                   else
16091                      return False;
16092                   end if;
16093                else
16094                   return False;
16095                end if;
16096             else
16097                return False;
16098             end if;
16099          end Names_T;
16100
16101       --  Start of processing for Mentions_T
16102
16103       begin
16104          if No (Access_To_Subprogram_Definition (Acc_Def)) then
16105             Subt := Subtype_Mark (Acc_Def);
16106
16107             if Nkind (Subt) = N_Identifier then
16108                return Chars (Subt) = Type_Id;
16109
16110             --  Reference can be through an expanded name which has not been
16111             --  analyzed yet, and which designates enclosing scopes.
16112
16113             elsif Nkind (Subt) = N_Selected_Component then
16114                if Names_T (Subt) then
16115                   return True;
16116
16117                --  Otherwise it must denote an entity that is already visible.
16118                --  The access definition may name a subtype of the enclosing
16119                --  type, if there is a previous incomplete declaration for it.
16120
16121                else
16122                   Find_Selected_Component (Subt);
16123                   return
16124                     Is_Entity_Name (Subt)
16125                       and then Scope (Entity (Subt)) = Current_Scope
16126                       and then (Chars (Base_Type (Entity (Subt))) = Type_Id
16127                         or else
16128                           (Is_Class_Wide_Type (Entity (Subt))
16129                             and then
16130                               Chars (Etype (Base_Type (Entity (Subt))))
16131                                 = Type_Id));
16132                end if;
16133
16134             --  A reference to the current type may appear as the prefix of
16135             --  a 'Class attribute.
16136
16137             elsif Nkind (Subt) = N_Attribute_Reference
16138               and then Attribute_Name (Subt) = Name_Class
16139             then
16140                return Names_T (Prefix (Subt));
16141             else
16142                return False;
16143             end if;
16144
16145          else
16146             --  Component is an access_to_subprogram: examine its formals
16147
16148             declare
16149                Param_Spec : Node_Id;
16150
16151             begin
16152                Param_Spec :=
16153                  First
16154                    (Parameter_Specifications
16155                      (Access_To_Subprogram_Definition (Acc_Def)));
16156                while Present (Param_Spec) loop
16157                   if Nkind (Parameter_Type (Param_Spec))
16158                        = N_Access_Definition
16159                     and then Mentions_T (Parameter_Type (Param_Spec))
16160                   then
16161                      return True;
16162                   end if;
16163
16164                   Next (Param_Spec);
16165                end loop;
16166
16167                return False;
16168             end;
16169          end if;
16170       end Mentions_T;
16171
16172    --  Start of processing for Check_Anonymous_Access_Components
16173
16174    begin
16175       if No (Comp_List) then
16176          return;
16177       end if;
16178
16179       Comp := First (Component_Items (Comp_List));
16180       while Present (Comp) loop
16181          if Nkind (Comp) = N_Component_Declaration
16182            and then Present
16183              (Access_Definition (Component_Definition (Comp)))
16184            and then
16185              Mentions_T (Access_Definition (Component_Definition (Comp)))
16186          then
16187             Comp_Def := Component_Definition (Comp);
16188             Acc_Def :=
16189               Access_To_Subprogram_Definition
16190                 (Access_Definition (Comp_Def));
16191
16192             Build_Incomplete_Type_Declaration;
16193             Anon_Access :=
16194               Make_Defining_Identifier (Loc,
16195                 Chars => New_Internal_Name ('S'));
16196
16197             --  Create a declaration for the anonymous access type: either
16198             --  an access_to_object or an access_to_subprogram.
16199
16200             if Present (Acc_Def) then
16201                if Nkind  (Acc_Def) = N_Access_Function_Definition then
16202                   Type_Def :=
16203                     Make_Access_Function_Definition (Loc,
16204                       Parameter_Specifications =>
16205                         Parameter_Specifications (Acc_Def),
16206                       Result_Definition => Result_Definition (Acc_Def));
16207                else
16208                   Type_Def :=
16209                     Make_Access_Procedure_Definition (Loc,
16210                       Parameter_Specifications =>
16211                         Parameter_Specifications (Acc_Def));
16212                end if;
16213
16214             else
16215                Type_Def :=
16216                  Make_Access_To_Object_Definition (Loc,
16217                    Subtype_Indication =>
16218                       Relocate_Node
16219                         (Subtype_Mark
16220                           (Access_Definition (Comp_Def))));
16221
16222                Set_Constant_Present
16223                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
16224                Set_All_Present
16225                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
16226             end if;
16227
16228             Set_Null_Exclusion_Present
16229               (Type_Def,
16230                Null_Exclusion_Present (Access_Definition (Comp_Def)));
16231
16232             Decl :=
16233               Make_Full_Type_Declaration (Loc,
16234                 Defining_Identifier => Anon_Access,
16235                 Type_Definition     => Type_Def);
16236
16237             Insert_Before (Typ_Decl, Decl);
16238             Analyze (Decl);
16239
16240             --  If an access to object, Preserve entity of designated type,
16241             --  for ASIS use, before rewriting the component definition.
16242
16243             if No (Acc_Def) then
16244                declare
16245                   Desig : Entity_Id;
16246
16247                begin
16248                   Desig := Entity (Subtype_Indication (Type_Def));
16249
16250                   --  If the access definition is to the current  record,
16251                   --  the visible entity at this point is an  incomplete
16252                   --  type. Retrieve the full view to simplify  ASIS queries
16253
16254                   if Ekind (Desig) = E_Incomplete_Type then
16255                      Desig := Full_View (Desig);
16256                   end if;
16257
16258                   Set_Entity
16259                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
16260                end;
16261             end if;
16262
16263             Rewrite (Comp_Def,
16264               Make_Component_Definition (Loc,
16265                 Subtype_Indication =>
16266                New_Occurrence_Of (Anon_Access, Loc)));
16267             Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
16268             Set_Is_Local_Anonymous_Access (Anon_Access);
16269          end if;
16270
16271          Next (Comp);
16272       end loop;
16273
16274       if Present (Variant_Part (Comp_List)) then
16275          declare
16276             V : Node_Id;
16277          begin
16278             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
16279             while Present (V) loop
16280                Check_Anonymous_Access_Components
16281                  (Typ_Decl, Typ, Prev, Component_List (V));
16282                Next_Non_Pragma (V);
16283             end loop;
16284          end;
16285       end if;
16286    end Check_Anonymous_Access_Components;
16287
16288    -----------------------------
16289    -- Record_Type_Declaration --
16290    -----------------------------
16291
16292    procedure Record_Type_Declaration
16293      (T    : Entity_Id;
16294       N    : Node_Id;
16295       Prev : Entity_Id)
16296    is
16297       Def       : constant Node_Id := Type_Definition (N);
16298       Is_Tagged : Boolean;
16299       Tag_Comp  : Entity_Id;
16300
16301    begin
16302       --  These flags must be initialized before calling Process_Discriminants
16303       --  because this routine makes use of them.
16304
16305       Set_Ekind               (T, E_Record_Type);
16306       Set_Etype               (T, T);
16307       Init_Size_Align         (T);
16308       Set_Abstract_Interfaces (T, No_Elist);
16309       Set_Stored_Constraint   (T, No_Elist);
16310
16311       --  Normal case
16312
16313       if Ada_Version < Ada_05
16314         or else not Interface_Present (Def)
16315       then
16316          --  The flag Is_Tagged_Type might have already been set by
16317          --  Find_Type_Name if it detected an error for declaration T. This
16318          --  arises in the case of private tagged types where the full view
16319          --  omits the word tagged.
16320
16321          Is_Tagged :=
16322            Tagged_Present (Def)
16323              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
16324
16325          Set_Is_Tagged_Type      (T, Is_Tagged);
16326          Set_Is_Limited_Record   (T, Limited_Present (Def));
16327
16328          --  Type is abstract if full declaration carries keyword, or if
16329          --  previous partial view did.
16330
16331          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
16332                                       or else Abstract_Present (Def));
16333
16334       else
16335          Is_Tagged := True;
16336          Analyze_Interface_Declaration (T, Def);
16337
16338          if Present (Discriminant_Specifications (N)) then
16339             Error_Msg_N
16340               ("interface types cannot have discriminants",
16341                 Defining_Identifier
16342                   (First (Discriminant_Specifications (N))));
16343          end if;
16344       end if;
16345
16346       --  First pass: if there are self-referential access components,
16347       --  create the required anonymous access type declarations, and if
16348       --  need be an incomplete type declaration for T itself.
16349
16350       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
16351
16352       if Ada_Version >= Ada_05
16353         and then Present (Interface_List (Def))
16354       then
16355          Check_Abstract_Interfaces (N, Def);
16356
16357          declare
16358             Ifaces_List : Elist_Id;
16359
16360          begin
16361             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
16362             --  already in the parents.
16363
16364             Collect_Abstract_Interfaces
16365               (T                         => T,
16366                Ifaces_List               => Ifaces_List,
16367                Exclude_Parent_Interfaces => True);
16368
16369             Set_Abstract_Interfaces (T, Ifaces_List);
16370          end;
16371       end if;
16372
16373       --  Records constitute a scope for the component declarations within.
16374       --  The scope is created prior to the processing of these declarations.
16375       --  Discriminants are processed first, so that they are visible when
16376       --  processing the other components. The Ekind of the record type itself
16377       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
16378
16379       --  Enter record scope
16380
16381       Push_Scope (T);
16382
16383       --  If an incomplete or private type declaration was already given for
16384       --  the type, then this scope already exists, and the discriminants have
16385       --  been declared within. We must verify that the full declaration
16386       --  matches the incomplete one.
16387
16388       Check_Or_Process_Discriminants (N, T, Prev);
16389
16390       Set_Is_Constrained     (T, not Has_Discriminants (T));
16391       Set_Has_Delayed_Freeze (T, True);
16392
16393       --  For tagged types add a manually analyzed component corresponding
16394       --  to the component _tag, the corresponding piece of tree will be
16395       --  expanded as part of the freezing actions if it is not a CPP_Class.
16396
16397       if Is_Tagged then
16398
16399          --  Do not add the tag unless we are in expansion mode
16400
16401          if Expander_Active then
16402             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
16403             Enter_Name (Tag_Comp);
16404
16405             Set_Is_Tag                    (Tag_Comp);
16406             Set_Is_Aliased                (Tag_Comp);
16407             Set_Ekind                     (Tag_Comp, E_Component);
16408             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
16409             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
16410             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
16411             Init_Component_Location       (Tag_Comp);
16412
16413             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
16414             --  implemented interfaces.
16415
16416             if Has_Abstract_Interfaces (T) then
16417                Add_Interface_Tag_Components (N, T);
16418             end if;
16419          end if;
16420
16421          Make_Class_Wide_Type (T);
16422          Set_Primitive_Operations (T, New_Elmt_List);
16423       end if;
16424
16425       --  We must suppress range checks when processing the components
16426       --  of a record in the presence of discriminants, since we don't
16427       --  want spurious checks to be generated during their analysis, but
16428       --  must reset the Suppress_Range_Checks flags after having processed
16429       --  the record definition.
16430
16431       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
16432       --  couldn't we just use the normal range check suppression method here.
16433       --  That would seem cleaner ???
16434
16435       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
16436          Set_Kill_Range_Checks (T, True);
16437          Record_Type_Definition (Def, Prev);
16438          Set_Kill_Range_Checks (T, False);
16439       else
16440          Record_Type_Definition (Def, Prev);
16441       end if;
16442
16443       --  Exit from record scope
16444
16445       End_Scope;
16446
16447       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
16448       --  the implemented interfaces and associate them an aliased entity.
16449
16450       if Is_Tagged
16451         and then not Is_Empty_List (Interface_List (Def))
16452       then
16453          declare
16454             Ifaces_List : constant Elist_Id := New_Elmt_List;
16455          begin
16456             Derive_Interface_Subprograms (T, T, Ifaces_List);
16457          end;
16458       end if;
16459    end Record_Type_Declaration;
16460
16461    ----------------------------
16462    -- Record_Type_Definition --
16463    ----------------------------
16464
16465    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
16466       Component          : Entity_Id;
16467       Ctrl_Components    : Boolean := False;
16468       Final_Storage_Only : Boolean;
16469       T                  : Entity_Id;
16470
16471    begin
16472       if Ekind (Prev_T) = E_Incomplete_Type then
16473          T := Full_View (Prev_T);
16474       else
16475          T := Prev_T;
16476       end if;
16477
16478       Final_Storage_Only := not Is_Controlled (T);
16479
16480       --  Ada 2005: check whether an explicit Limited is present in a derived
16481       --  type declaration.
16482
16483       if Nkind (Parent (Def)) = N_Derived_Type_Definition
16484         and then Limited_Present (Parent (Def))
16485       then
16486          Set_Is_Limited_Record (T);
16487       end if;
16488
16489       --  If the component list of a record type is defined by the reserved
16490       --  word null and there is no discriminant part, then the record type has
16491       --  no components and all records of the type are null records (RM 3.7)
16492       --  This procedure is also called to process the extension part of a
16493       --  record extension, in which case the current scope may have inherited
16494       --  components.
16495
16496       if No (Def)
16497         or else No (Component_List (Def))
16498         or else Null_Present (Component_List (Def))
16499       then
16500          null;
16501
16502       else
16503          Analyze_Declarations (Component_Items (Component_List (Def)));
16504
16505          if Present (Variant_Part (Component_List (Def))) then
16506             Analyze (Variant_Part (Component_List (Def)));
16507          end if;
16508       end if;
16509
16510       --  After completing the semantic analysis of the record definition,
16511       --  record components, both new and inherited, are accessible. Set their
16512       --  kind accordingly. Exclude malformed itypes from illegal declarations,
16513       --  whose Ekind may be void.
16514
16515       Component := First_Entity (Current_Scope);
16516       while Present (Component) loop
16517          if Ekind (Component) = E_Void
16518            and then not Is_Itype (Component)
16519          then
16520             Set_Ekind (Component, E_Component);
16521             Init_Component_Location (Component);
16522          end if;
16523
16524          if Has_Task (Etype (Component)) then
16525             Set_Has_Task (T);
16526          end if;
16527
16528          if Ekind (Component) /= E_Component then
16529             null;
16530
16531          elsif Has_Controlled_Component (Etype (Component))
16532            or else (Chars (Component) /= Name_uParent
16533                     and then Is_Controlled (Etype (Component)))
16534          then
16535             Set_Has_Controlled_Component (T, True);
16536             Final_Storage_Only := Final_Storage_Only
16537               and then Finalize_Storage_Only (Etype (Component));
16538             Ctrl_Components := True;
16539          end if;
16540
16541          Next_Entity (Component);
16542       end loop;
16543
16544       --  A Type is Finalize_Storage_Only only if all its controlled components
16545       --  are also.
16546
16547       if Ctrl_Components then
16548          Set_Finalize_Storage_Only (T, Final_Storage_Only);
16549       end if;
16550
16551       --  Place reference to end record on the proper entity, which may
16552       --  be a partial view.
16553
16554       if Present (Def) then
16555          Process_End_Label (Def, 'e', Prev_T);
16556       end if;
16557    end Record_Type_Definition;
16558
16559    ------------------------
16560    -- Replace_Components --
16561    ------------------------
16562
16563    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
16564       function Process (N : Node_Id) return Traverse_Result;
16565
16566       -------------
16567       -- Process --
16568       -------------
16569
16570       function Process (N : Node_Id) return Traverse_Result is
16571          Comp : Entity_Id;
16572
16573       begin
16574          if Nkind (N) = N_Discriminant_Specification then
16575             Comp := First_Discriminant (Typ);
16576             while Present (Comp) loop
16577                if Chars (Comp) = Chars (Defining_Identifier (N)) then
16578                   Set_Defining_Identifier (N, Comp);
16579                   exit;
16580                end if;
16581
16582                Next_Discriminant (Comp);
16583             end loop;
16584
16585          elsif Nkind (N) = N_Component_Declaration then
16586             Comp := First_Component (Typ);
16587             while Present (Comp) loop
16588                if Chars (Comp) = Chars (Defining_Identifier (N)) then
16589                   Set_Defining_Identifier (N, Comp);
16590                   exit;
16591                end if;
16592
16593                Next_Component (Comp);
16594             end loop;
16595          end if;
16596
16597          return OK;
16598       end Process;
16599
16600       procedure Replace is new Traverse_Proc (Process);
16601
16602    --  Start of processing for Replace_Components
16603
16604    begin
16605       Replace (Decl);
16606    end Replace_Components;
16607
16608    -------------------------------
16609    -- Set_Completion_Referenced --
16610    -------------------------------
16611
16612    procedure Set_Completion_Referenced (E : Entity_Id) is
16613    begin
16614       --  If in main unit, mark entity that is a completion as referenced,
16615       --  warnings go on the partial view when needed.
16616
16617       if In_Extended_Main_Source_Unit (E) then
16618          Set_Referenced (E);
16619       end if;
16620    end Set_Completion_Referenced;
16621
16622    ---------------------
16623    -- Set_Fixed_Range --
16624    ---------------------
16625
16626    --  The range for fixed-point types is complicated by the fact that we
16627    --  do not know the exact end points at the time of the declaration. This
16628    --  is true for three reasons:
16629
16630    --     A size clause may affect the fudging of the end-points
16631    --     A small clause may affect the values of the end-points
16632    --     We try to include the end-points if it does not affect the size
16633
16634    --  This means that the actual end-points must be established at the point
16635    --  when the type is frozen. Meanwhile, we first narrow the range as
16636    --  permitted (so that it will fit if necessary in a small specified size),
16637    --  and then build a range subtree with these narrowed bounds.
16638
16639    --  Set_Fixed_Range constructs the range from real literal values, and sets
16640    --  the range as the Scalar_Range of the given fixed-point type entity.
16641
16642    --  The parent of this range is set to point to the entity so that it is
16643    --  properly hooked into the tree (unlike normal Scalar_Range entries for
16644    --  other scalar types, which are just pointers to the range in the
16645    --  original tree, this would otherwise be an orphan).
16646
16647    --  The tree is left unanalyzed. When the type is frozen, the processing
16648    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
16649    --  analyzed, and uses this as an indication that it should complete
16650    --  work on the range (it will know the final small and size values).
16651
16652    procedure Set_Fixed_Range
16653      (E   : Entity_Id;
16654       Loc : Source_Ptr;
16655       Lo  : Ureal;
16656       Hi  : Ureal)
16657    is
16658       S : constant Node_Id :=
16659             Make_Range (Loc,
16660               Low_Bound  => Make_Real_Literal (Loc, Lo),
16661               High_Bound => Make_Real_Literal (Loc, Hi));
16662    begin
16663       Set_Scalar_Range (E, S);
16664       Set_Parent (S, E);
16665    end Set_Fixed_Range;
16666
16667    ----------------------------------
16668    -- Set_Scalar_Range_For_Subtype --
16669    ----------------------------------
16670
16671    procedure Set_Scalar_Range_For_Subtype
16672      (Def_Id : Entity_Id;
16673       R      : Node_Id;
16674       Subt   : Entity_Id)
16675    is
16676       Kind : constant Entity_Kind :=  Ekind (Def_Id);
16677
16678    begin
16679       Set_Scalar_Range (Def_Id, R);
16680
16681       --  We need to link the range into the tree before resolving it so
16682       --  that types that are referenced, including importantly the subtype
16683       --  itself, are properly frozen (Freeze_Expression requires that the
16684       --  expression be properly linked into the tree). Of course if it is
16685       --  already linked in, then we do not disturb the current link.
16686
16687       if No (Parent (R)) then
16688          Set_Parent (R, Def_Id);
16689       end if;
16690
16691       --  Reset the kind of the subtype during analysis of the range, to
16692       --  catch possible premature use in the bounds themselves.
16693
16694       Set_Ekind (Def_Id, E_Void);
16695       Process_Range_Expr_In_Decl (R, Subt);
16696       Set_Ekind (Def_Id, Kind);
16697    end Set_Scalar_Range_For_Subtype;
16698
16699    --------------------------------------------------------
16700    -- Set_Stored_Constraint_From_Discriminant_Constraint --
16701    --------------------------------------------------------
16702
16703    procedure Set_Stored_Constraint_From_Discriminant_Constraint
16704      (E : Entity_Id)
16705    is
16706    begin
16707       --  Make sure set if encountered during Expand_To_Stored_Constraint
16708
16709       Set_Stored_Constraint (E, No_Elist);
16710
16711       --  Give it the right value
16712
16713       if Is_Constrained (E) and then Has_Discriminants (E) then
16714          Set_Stored_Constraint (E,
16715            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
16716       end if;
16717    end Set_Stored_Constraint_From_Discriminant_Constraint;
16718
16719    -------------------------------------
16720    -- Signed_Integer_Type_Declaration --
16721    -------------------------------------
16722
16723    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16724       Implicit_Base : Entity_Id;
16725       Base_Typ      : Entity_Id;
16726       Lo_Val        : Uint;
16727       Hi_Val        : Uint;
16728       Errs          : Boolean := False;
16729       Lo            : Node_Id;
16730       Hi            : Node_Id;
16731
16732       function Can_Derive_From (E : Entity_Id) return Boolean;
16733       --  Determine whether given bounds allow derivation from specified type
16734
16735       procedure Check_Bound (Expr : Node_Id);
16736       --  Check bound to make sure it is integral and static. If not, post
16737       --  appropriate error message and set Errs flag
16738
16739       ---------------------
16740       -- Can_Derive_From --
16741       ---------------------
16742
16743       --  Note we check both bounds against both end values, to deal with
16744       --  strange types like ones with a range of 0 .. -12341234.
16745
16746       function Can_Derive_From (E : Entity_Id) return Boolean is
16747          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
16748          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
16749       begin
16750          return Lo <= Lo_Val and then Lo_Val <= Hi
16751                   and then
16752                 Lo <= Hi_Val and then Hi_Val <= Hi;
16753       end Can_Derive_From;
16754
16755       -----------------
16756       -- Check_Bound --
16757       -----------------
16758
16759       procedure Check_Bound (Expr : Node_Id) is
16760       begin
16761          --  If a range constraint is used as an integer type definition, each
16762          --  bound of the range must be defined by a static expression of some
16763          --  integer type, but the two bounds need not have the same integer
16764          --  type (Negative bounds are allowed.) (RM 3.5.4)
16765
16766          if not Is_Integer_Type (Etype (Expr)) then
16767             Error_Msg_N
16768               ("integer type definition bounds must be of integer type", Expr);
16769             Errs := True;
16770
16771          elsif not Is_OK_Static_Expression (Expr) then
16772             Flag_Non_Static_Expr
16773               ("non-static expression used for integer type bound!", Expr);
16774             Errs := True;
16775
16776          --  The bounds are folded into literals, and we set their type to be
16777          --  universal, to avoid typing difficulties: we cannot set the type
16778          --  of the literal to the new type, because this would be a forward
16779          --  reference for the back end,  and if the original type is user-
16780          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
16781
16782          else
16783             if Is_Entity_Name (Expr) then
16784                Fold_Uint (Expr, Expr_Value (Expr), True);
16785             end if;
16786
16787             Set_Etype (Expr, Universal_Integer);
16788          end if;
16789       end Check_Bound;
16790
16791    --  Start of processing for Signed_Integer_Type_Declaration
16792
16793    begin
16794       --  Create an anonymous base type
16795
16796       Implicit_Base :=
16797         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
16798
16799       --  Analyze and check the bounds, they can be of any integer type
16800
16801       Lo := Low_Bound (Def);
16802       Hi := High_Bound (Def);
16803
16804       --  Arbitrarily use Integer as the type if either bound had an error
16805
16806       if Hi = Error or else Lo = Error then
16807          Base_Typ := Any_Integer;
16808          Set_Error_Posted (T, True);
16809
16810       --  Here both bounds are OK expressions
16811
16812       else
16813          Analyze_And_Resolve (Lo, Any_Integer);
16814          Analyze_And_Resolve (Hi, Any_Integer);
16815
16816          Check_Bound (Lo);
16817          Check_Bound (Hi);
16818
16819          if Errs then
16820             Hi := Type_High_Bound (Standard_Long_Long_Integer);
16821             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
16822          end if;
16823
16824          --  Find type to derive from
16825
16826          Lo_Val := Expr_Value (Lo);
16827          Hi_Val := Expr_Value (Hi);
16828
16829          if Can_Derive_From (Standard_Short_Short_Integer) then
16830             Base_Typ := Base_Type (Standard_Short_Short_Integer);
16831
16832          elsif Can_Derive_From (Standard_Short_Integer) then
16833             Base_Typ := Base_Type (Standard_Short_Integer);
16834
16835          elsif Can_Derive_From (Standard_Integer) then
16836             Base_Typ := Base_Type (Standard_Integer);
16837
16838          elsif Can_Derive_From (Standard_Long_Integer) then
16839             Base_Typ := Base_Type (Standard_Long_Integer);
16840
16841          elsif Can_Derive_From (Standard_Long_Long_Integer) then
16842             Base_Typ := Base_Type (Standard_Long_Long_Integer);
16843
16844          else
16845             Base_Typ := Base_Type (Standard_Long_Long_Integer);
16846             Error_Msg_N ("integer type definition bounds out of range", Def);
16847             Hi := Type_High_Bound (Standard_Long_Long_Integer);
16848             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
16849          end if;
16850       end if;
16851
16852       --  Complete both implicit base and declared first subtype entities
16853
16854       Set_Etype          (Implicit_Base, Base_Typ);
16855       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
16856       Set_Size_Info      (Implicit_Base,                (Base_Typ));
16857       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
16858       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
16859
16860       Set_Ekind          (T, E_Signed_Integer_Subtype);
16861       Set_Etype          (T, Implicit_Base);
16862
16863       Set_Size_Info      (T,                (Implicit_Base));
16864       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
16865       Set_Scalar_Range   (T, Def);
16866       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
16867       Set_Is_Constrained (T);
16868    end Signed_Integer_Type_Declaration;
16869
16870 end Sem_Ch3;