OSDN Git Service

2011-10-16 Tristan Gingold <gingold@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch3.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 3                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Elists;   use Elists;
30 with Einfo;    use Einfo;
31 with Errout;   use Errout;
32 with Eval_Fat; use Eval_Fat;
33 with Exp_Ch3;  use Exp_Ch3;
34 with Exp_Ch9;  use Exp_Ch9;
35 with Exp_Disp; use Exp_Disp;
36 with Exp_Dist; use Exp_Dist;
37 with Exp_Tss;  use Exp_Tss;
38 with Exp_Util; use Exp_Util;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Layout;   use Layout;
43 with Lib;      use Lib;
44 with Lib.Xref; use Lib.Xref;
45 with Namet;    use Namet;
46 with Nmake;    use Nmake;
47 with Opt;      use Opt;
48 with Restrict; use Restrict;
49 with Rident;   use Rident;
50 with Rtsfind;  use Rtsfind;
51 with Sem;      use Sem;
52 with Sem_Aux;  use Sem_Aux;
53 with Sem_Case; use Sem_Case;
54 with Sem_Cat;  use Sem_Cat;
55 with Sem_Ch6;  use Sem_Ch6;
56 with Sem_Ch7;  use Sem_Ch7;
57 with Sem_Ch8;  use Sem_Ch8;
58 with Sem_Ch13; use Sem_Ch13;
59 with Sem_Disp; use Sem_Disp;
60 with Sem_Dist; use Sem_Dist;
61 with Sem_Elim; use Sem_Elim;
62 with Sem_Eval; use Sem_Eval;
63 with Sem_Mech; use Sem_Mech;
64 with Sem_Prag; use Sem_Prag;
65 with Sem_Res;  use Sem_Res;
66 with Sem_Smem; use Sem_Smem;
67 with Sem_Type; use Sem_Type;
68 with Sem_Util; use Sem_Util;
69 with Sem_Warn; use Sem_Warn;
70 with Stand;    use Stand;
71 with Sinfo;    use Sinfo;
72 with Sinput;   use Sinput;
73 with Snames;   use Snames;
74 with Targparm; use Targparm;
75 with Tbuild;   use Tbuild;
76 with Ttypes;   use Ttypes;
77 with Uintp;    use Uintp;
78 with Urealp;   use Urealp;
79
80 package body Sem_Ch3 is
81
82    -----------------------
83    -- Local Subprograms --
84    -----------------------
85
86    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
87    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
88    --  abstract interface types implemented by a record type or a derived
89    --  record type.
90
91    procedure Build_Derived_Type
92      (N             : Node_Id;
93       Parent_Type   : Entity_Id;
94       Derived_Type  : Entity_Id;
95       Is_Completion : Boolean;
96       Derive_Subps  : Boolean := True);
97    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
98    --  the N_Full_Type_Declaration node containing the derived type definition.
99    --  Parent_Type is the entity for the parent type in the derived type
100    --  definition and Derived_Type the actual derived type. Is_Completion must
101    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
102    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
103    --  completion of a private type declaration. If Is_Completion is set to
104    --  True, N is the completion of a private type declaration and Derived_Type
105    --  is different from the defining identifier inside N (i.e. Derived_Type /=
106    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
107    --  subprograms should be derived. The only case where this parameter is
108    --  False is when Build_Derived_Type is recursively called to process an
109    --  implicit derived full type for a type derived from a private type (in
110    --  that case the subprograms must only be derived for the private view of
111    --  the type).
112    --
113    --  ??? These flags need a bit of re-examination and re-documentation:
114    --  ???  are they both necessary (both seem related to the recursion)?
115
116    procedure Build_Derived_Access_Type
117      (N            : Node_Id;
118       Parent_Type  : Entity_Id;
119       Derived_Type : Entity_Id);
120    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
121    --  create an implicit base if the parent type is constrained or if the
122    --  subtype indication has a constraint.
123
124    procedure Build_Derived_Array_Type
125      (N            : Node_Id;
126       Parent_Type  : Entity_Id;
127       Derived_Type : Entity_Id);
128    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
129    --  create an implicit base if the parent type is constrained or if the
130    --  subtype indication has a constraint.
131
132    procedure Build_Derived_Concurrent_Type
133      (N            : Node_Id;
134       Parent_Type  : Entity_Id;
135       Derived_Type : Entity_Id);
136    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
137    --  protected type, inherit entries and protected subprograms, check
138    --  legality of discriminant constraints if any.
139
140    procedure Build_Derived_Enumeration_Type
141      (N            : Node_Id;
142       Parent_Type  : Entity_Id;
143       Derived_Type : Entity_Id);
144    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
145    --  type, we must create a new list of literals. Types derived from
146    --  Character and [Wide_]Wide_Character are special-cased.
147
148    procedure Build_Derived_Numeric_Type
149      (N            : Node_Id;
150       Parent_Type  : Entity_Id;
151       Derived_Type : Entity_Id);
152    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
153    --  an anonymous base type, and propagate constraint to subtype if needed.
154
155    procedure Build_Derived_Private_Type
156      (N             : Node_Id;
157       Parent_Type   : Entity_Id;
158       Derived_Type  : Entity_Id;
159       Is_Completion : Boolean;
160       Derive_Subps  : Boolean := True);
161    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
162    --  because the parent may or may not have a completion, and the derivation
163    --  may itself be a completion.
164
165    procedure Build_Derived_Record_Type
166      (N            : Node_Id;
167       Parent_Type  : Entity_Id;
168       Derived_Type : Entity_Id;
169       Derive_Subps : Boolean := True);
170    --  Subsidiary procedure for Build_Derived_Type and
171    --  Analyze_Private_Extension_Declaration used for tagged and untagged
172    --  record types. All parameters are as in Build_Derived_Type except that
173    --  N, in addition to being an N_Full_Type_Declaration node, can also be an
174    --  N_Private_Extension_Declaration node. See the definition of this routine
175    --  for much more info. Derive_Subps indicates whether subprograms should
176    --  be derived from the parent type. The only case where Derive_Subps is
177    --  False is for an implicit derived full type for a type derived from a
178    --  private type (see Build_Derived_Type).
179
180    procedure Build_Discriminal (Discrim : Entity_Id);
181    --  Create the discriminal corresponding to discriminant Discrim, that is
182    --  the parameter corresponding to Discrim to be used in initialization
183    --  procedures for the type where Discrim is a discriminant. Discriminals
184    --  are not used during semantic analysis, and are not fully defined
185    --  entities until expansion. Thus they are not given a scope until
186    --  initialization procedures are built.
187
188    function Build_Discriminant_Constraints
189      (T           : Entity_Id;
190       Def         : Node_Id;
191       Derived_Def : Boolean := False) return Elist_Id;
192    --  Validate discriminant constraints and return the list of the constraints
193    --  in order of discriminant declarations, where T is the discriminated
194    --  unconstrained type. Def is the N_Subtype_Indication node where the
195    --  discriminants constraints for T are specified. Derived_Def is True
196    --  when building the discriminant constraints in a derived type definition
197    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
198    --  type and Def is the constraint "(xxx)" on T and this routine sets the
199    --  Corresponding_Discriminant field of the discriminants in the derived
200    --  type D to point to the corresponding discriminants in the parent type T.
201
202    procedure Build_Discriminated_Subtype
203      (T           : Entity_Id;
204       Def_Id      : Entity_Id;
205       Elist       : Elist_Id;
206       Related_Nod : Node_Id;
207       For_Access  : Boolean := False);
208    --  Subsidiary procedure to Constrain_Discriminated_Type and to
209    --  Process_Incomplete_Dependents. Given
210    --
211    --     T (a possibly discriminated base type)
212    --     Def_Id (a very partially built subtype for T),
213    --
214    --  the call completes Def_Id to be the appropriate E_*_Subtype.
215    --
216    --  The Elist is the list of discriminant constraints if any (it is set
217    --  to No_Elist if T is not a discriminated type, and to an empty list if
218    --  T has discriminants but there are no discriminant constraints). The
219    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
220    --  The For_Access says whether or not this subtype is really constraining
221    --  an access type. That is its sole purpose is the designated type of an
222    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
223    --  is built to avoid freezing T when the access subtype is frozen.
224
225    function Build_Scalar_Bound
226      (Bound : Node_Id;
227       Par_T : Entity_Id;
228       Der_T : Entity_Id) return Node_Id;
229    --  The bounds of a derived scalar type are conversions of the bounds of
230    --  the parent type. Optimize the representation if the bounds are literals.
231    --  Needs a more complete spec--what are the parameters exactly, and what
232    --  exactly is the returned value, and how is Bound affected???
233
234    procedure Build_Underlying_Full_View
235      (N   : Node_Id;
236       Typ : Entity_Id;
237       Par : Entity_Id);
238    --  If the completion of a private type is itself derived from a private
239    --  type, or if the full view of a private subtype is itself private, the
240    --  back-end has no way to compute the actual size of this type. We build
241    --  an internal subtype declaration of the proper parent type to convey
242    --  this information. This extra mechanism is needed because a full
243    --  view cannot itself have a full view (it would get clobbered during
244    --  view exchanges).
245
246    procedure Check_Access_Discriminant_Requires_Limited
247      (D   : Node_Id;
248       Loc : Node_Id);
249    --  Check the restriction that the type to which an access discriminant
250    --  belongs must be a concurrent type or a descendant of a type with
251    --  the reserved word 'limited' in its declaration.
252
253    procedure Check_Anonymous_Access_Components
254       (Typ_Decl  : Node_Id;
255        Typ       : Entity_Id;
256        Prev      : Entity_Id;
257        Comp_List : Node_Id);
258    --  Ada 2005 AI-382: an access component in a record definition can refer to
259    --  the enclosing record, in which case it denotes the type itself, and not
260    --  the current instance of the type. We create an anonymous access type for
261    --  the component, and flag it as an access to a component, so accessibility
262    --  checks are properly performed on it. The declaration of the access type
263    --  is placed ahead of that of the record to prevent order-of-elaboration
264    --  circularity issues in Gigi. We create an incomplete type for the record
265    --  declaration, which is the designated type of the anonymous access.
266
267    procedure Check_Delta_Expression (E : Node_Id);
268    --  Check that the expression represented by E is suitable for use as a
269    --  delta expression, i.e. it is of real type and is static.
270
271    procedure Check_Digits_Expression (E : Node_Id);
272    --  Check that the expression represented by E is suitable for use as a
273    --  digits expression, i.e. it is of integer type, positive and static.
274
275    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
276    --  Validate the initialization of an object declaration. T is the required
277    --  type, and Exp is the initialization expression.
278
279    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
280    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
281
282    procedure Check_Or_Process_Discriminants
283      (N    : Node_Id;
284       T    : Entity_Id;
285       Prev : Entity_Id := Empty);
286    --  If N is the full declaration of the completion T of an incomplete or
287    --  private type, check its discriminants (which are already known to be
288    --  conformant with those of the partial view, see Find_Type_Name),
289    --  otherwise process them. Prev is the entity of the partial declaration,
290    --  if any.
291
292    procedure Check_Real_Bound (Bound : Node_Id);
293    --  Check given bound for being of real type and static. If not, post an
294    --  appropriate message, and rewrite the bound with the real literal zero.
295
296    procedure Constant_Redeclaration
297      (Id : Entity_Id;
298       N  : Node_Id;
299       T  : out Entity_Id);
300    --  Various checks on legality of full declaration of deferred constant.
301    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
302    --  node. The caller has not yet set any attributes of this entity.
303
304    function Contain_Interface
305      (Iface  : Entity_Id;
306       Ifaces : Elist_Id) return Boolean;
307    --  Ada 2005: Determine whether Iface is present in the list Ifaces
308
309    procedure Convert_Scalar_Bounds
310      (N            : Node_Id;
311       Parent_Type  : Entity_Id;
312       Derived_Type : Entity_Id;
313       Loc          : Source_Ptr);
314    --  For derived scalar types, convert the bounds in the type definition to
315    --  the derived type, and complete their analysis. Given a constraint of the
316    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
317    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
318    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
319    --  subtype are conversions of those bounds to the derived_type, so that
320    --  their typing is consistent.
321
322    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
323    --  Copies attributes from array base type T2 to array base type T1. Copies
324    --  only attributes that apply to base types, but not subtypes.
325
326    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
327    --  Copies attributes from array subtype T2 to array subtype T1. Copies
328    --  attributes that apply to both subtypes and base types.
329
330    procedure Create_Constrained_Components
331      (Subt        : Entity_Id;
332       Decl_Node   : Node_Id;
333       Typ         : Entity_Id;
334       Constraints : Elist_Id);
335    --  Build the list of entities for a constrained discriminated record
336    --  subtype. If a component depends on a discriminant, replace its subtype
337    --  using the discriminant values in the discriminant constraint. Subt
338    --  is the defining identifier for the subtype whose list of constrained
339    --  entities we will create. Decl_Node is the type declaration node where
340    --  we will attach all the itypes created. Typ is the base discriminated
341    --  type for the subtype Subt. Constraints is the list of discriminant
342    --  constraints for Typ.
343
344    function Constrain_Component_Type
345      (Comp            : Entity_Id;
346       Constrained_Typ : Entity_Id;
347       Related_Node    : Node_Id;
348       Typ             : Entity_Id;
349       Constraints     : Elist_Id) return Entity_Id;
350    --  Given a discriminated base type Typ, a list of discriminant constraint
351    --  Constraints for Typ and a component of Typ, with type Compon_Type,
352    --  create and return the type corresponding to Compon_type where all
353    --  discriminant references are replaced with the corresponding constraint.
354    --  If no discriminant references occur in Compon_Typ then return it as is.
355    --  Constrained_Typ is the final constrained subtype to which the
356    --  constrained Compon_Type belongs. Related_Node is the node where we will
357    --  attach all the itypes created.
358    --
359    --  Above description is confused, what is Compon_Type???
360
361    procedure Constrain_Access
362      (Def_Id      : in out Entity_Id;
363       S           : Node_Id;
364       Related_Nod : Node_Id);
365    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
366    --  an anonymous type created for a subtype indication. In that case it is
367    --  created in the procedure and attached to Related_Nod.
368
369    procedure Constrain_Array
370      (Def_Id      : in out Entity_Id;
371       SI          : Node_Id;
372       Related_Nod : Node_Id;
373       Related_Id  : Entity_Id;
374       Suffix      : Character);
375    --  Apply a list of index constraints to an unconstrained array type. The
376    --  first parameter is the entity for the resulting subtype. A value of
377    --  Empty for Def_Id indicates that an implicit type must be created, but
378    --  creation is delayed (and must be done by this procedure) because other
379    --  subsidiary implicit types must be created first (which is why Def_Id
380    --  is an in/out parameter). The second parameter is a subtype indication
381    --  node for the constrained array to be created (e.g. something of the
382    --  form string (1 .. 10)). Related_Nod gives the place where this type
383    --  has to be inserted in the tree. The Related_Id and Suffix parameters
384    --  are used to build the associated Implicit type name.
385
386    procedure Constrain_Concurrent
387      (Def_Id      : in out Entity_Id;
388       SI          : Node_Id;
389       Related_Nod : Node_Id;
390       Related_Id  : Entity_Id;
391       Suffix      : Character);
392    --  Apply list of discriminant constraints to an unconstrained concurrent
393    --  type.
394    --
395    --    SI is the N_Subtype_Indication node containing the constraint and
396    --    the unconstrained type to constrain.
397    --
398    --    Def_Id is the entity for the resulting constrained subtype. A value
399    --    of Empty for Def_Id indicates that an implicit type must be created,
400    --    but creation is delayed (and must be done by this procedure) because
401    --    other subsidiary implicit types must be created first (which is why
402    --    Def_Id is an in/out parameter).
403    --
404    --    Related_Nod gives the place where this type has to be inserted
405    --    in the tree
406    --
407    --  The last two arguments are used to create its external name if needed.
408
409    function Constrain_Corresponding_Record
410      (Prot_Subt   : Entity_Id;
411       Corr_Rec    : Entity_Id;
412       Related_Nod : Node_Id;
413       Related_Id  : Entity_Id) return Entity_Id;
414    --  When constraining a protected type or task type with discriminants,
415    --  constrain the corresponding record with the same discriminant values.
416
417    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
418    --  Constrain a decimal fixed point type with a digits constraint and/or a
419    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
420
421    procedure Constrain_Discriminated_Type
422      (Def_Id      : Entity_Id;
423       S           : Node_Id;
424       Related_Nod : Node_Id;
425       For_Access  : Boolean := False);
426    --  Process discriminant constraints of composite type. Verify that values
427    --  have been provided for all discriminants, that the original type is
428    --  unconstrained, and that the types of the supplied expressions match
429    --  the discriminant types. The first three parameters are like in routine
430    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
431    --  of For_Access.
432
433    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
434    --  Constrain an enumeration type with a range constraint. This is identical
435    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
436
437    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
438    --  Constrain a floating point type with either a digits constraint
439    --  and/or a range constraint, building a E_Floating_Point_Subtype.
440
441    procedure Constrain_Index
442      (Index        : Node_Id;
443       S            : Node_Id;
444       Related_Nod  : Node_Id;
445       Related_Id   : Entity_Id;
446       Suffix       : Character;
447       Suffix_Index : Nat);
448    --  Process an index constraint S in a constrained array declaration. The
449    --  constraint can be a subtype name, or a range with or without an explicit
450    --  subtype mark. The index is the corresponding index of the unconstrained
451    --  array. The Related_Id and Suffix parameters are used to build the
452    --  associated Implicit type name.
453
454    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
455    --  Build subtype of a signed or modular integer type
456
457    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
458    --  Constrain an ordinary fixed point type with a range constraint, and
459    --  build an E_Ordinary_Fixed_Point_Subtype entity.
460
461    procedure Copy_And_Swap (Priv, Full : Entity_Id);
462    --  Copy the Priv entity into the entity of its full declaration then swap
463    --  the two entities in such a manner that the former private type is now
464    --  seen as a full type.
465
466    procedure Decimal_Fixed_Point_Type_Declaration
467      (T   : Entity_Id;
468       Def : Node_Id);
469    --  Create a new decimal fixed point type, and apply the constraint to
470    --  obtain a subtype of this new type.
471
472    procedure Complete_Private_Subtype
473      (Priv        : Entity_Id;
474       Full        : Entity_Id;
475       Full_Base   : Entity_Id;
476       Related_Nod : Node_Id);
477    --  Complete the implicit full view of a private subtype by setting the
478    --  appropriate semantic fields. If the full view of the parent is a record
479    --  type, build constrained components of subtype.
480
481    procedure Derive_Progenitor_Subprograms
482      (Parent_Type : Entity_Id;
483       Tagged_Type : Entity_Id);
484    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
485    --  operations of progenitors of Tagged_Type, and replace the subsidiary
486    --  subtypes with Tagged_Type, to build the specs of the inherited interface
487    --  primitives. The derived primitives are aliased to those of the
488    --  interface. This routine takes care also of transferring to the full view
489    --  subprograms associated with the partial view of Tagged_Type that cover
490    --  interface primitives.
491
492    procedure Derived_Standard_Character
493      (N             : Node_Id;
494       Parent_Type   : Entity_Id;
495       Derived_Type  : Entity_Id);
496    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
497    --  derivations from types Standard.Character and Standard.Wide_Character.
498
499    procedure Derived_Type_Declaration
500      (T             : Entity_Id;
501       N             : Node_Id;
502       Is_Completion : Boolean);
503    --  Process a derived type declaration. Build_Derived_Type is invoked
504    --  to process the actual derived type definition. Parameters N and
505    --  Is_Completion have the same meaning as in Build_Derived_Type.
506    --  T is the N_Defining_Identifier for the entity defined in the
507    --  N_Full_Type_Declaration node N, that is T is the derived type.
508
509    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
510    --  Insert each literal in symbol table, as an overloadable identifier. Each
511    --  enumeration type is mapped into a sequence of integers, and each literal
512    --  is defined as a constant with integer value. If any of the literals are
513    --  character literals, the type is a character type, which means that
514    --  strings are legal aggregates for arrays of components of the type.
515
516    function Expand_To_Stored_Constraint
517      (Typ        : Entity_Id;
518       Constraint : Elist_Id) return Elist_Id;
519    --  Given a constraint (i.e. a list of expressions) on the discriminants of
520    --  Typ, expand it into a constraint on the stored discriminants and return
521    --  the new list of expressions constraining the stored discriminants.
522
523    function Find_Type_Of_Object
524      (Obj_Def     : Node_Id;
525       Related_Nod : Node_Id) return Entity_Id;
526    --  Get type entity for object referenced by Obj_Def, attaching the
527    --  implicit types generated to Related_Nod
528
529    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
530    --  Create a new float and apply the constraint to obtain subtype of it
531
532    function Has_Range_Constraint (N : Node_Id) return Boolean;
533    --  Given an N_Subtype_Indication node N, return True if a range constraint
534    --  is present, either directly, or as part of a digits or delta constraint.
535    --  In addition, a digits constraint in the decimal case returns True, since
536    --  it establishes a default range if no explicit range is present.
537
538    function Inherit_Components
539      (N             : Node_Id;
540       Parent_Base   : Entity_Id;
541       Derived_Base  : Entity_Id;
542       Is_Tagged     : Boolean;
543       Inherit_Discr : Boolean;
544       Discs         : Elist_Id) return Elist_Id;
545    --  Called from Build_Derived_Record_Type to inherit the components of
546    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
547    --  For more information on derived types and component inheritance please
548    --  consult the comment above the body of Build_Derived_Record_Type.
549    --
550    --    N is the original derived type declaration
551    --
552    --    Is_Tagged is set if we are dealing with tagged types
553    --
554    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
555    --    Parent_Base, otherwise no discriminants are inherited.
556    --
557    --    Discs gives the list of constraints that apply to Parent_Base in the
558    --    derived type declaration. If Discs is set to No_Elist, then we have
559    --    the following situation:
560    --
561    --      type Parent (D1..Dn : ..) is [tagged] record ...;
562    --      type Derived is new Parent [with ...];
563    --
564    --    which gets treated as
565    --
566    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
567    --
568    --  For untagged types the returned value is an association list. The list
569    --  starts from the association (Parent_Base => Derived_Base), and then it
570    --  contains a sequence of the associations of the form
571    --
572    --    (Old_Component => New_Component),
573    --
574    --  where Old_Component is the Entity_Id of a component in Parent_Base and
575    --  New_Component is the Entity_Id of the corresponding component in
576    --  Derived_Base. For untagged records, this association list is needed when
577    --  copying the record declaration for the derived base. In the tagged case
578    --  the value returned is irrelevant.
579
580    function Is_Valid_Constraint_Kind
581      (T_Kind          : Type_Kind;
582       Constraint_Kind : Node_Kind) return Boolean;
583    --  Returns True if it is legal to apply the given kind of constraint to the
584    --  given kind of type (index constraint to an array type, for example).
585
586    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
587    --  Create new modular type. Verify that modulus is in bounds
588
589    procedure New_Concatenation_Op (Typ : Entity_Id);
590    --  Create an abbreviated declaration for an operator in order to
591    --  materialize concatenation on array types.
592
593    procedure Ordinary_Fixed_Point_Type_Declaration
594      (T   : Entity_Id;
595       Def : Node_Id);
596    --  Create a new ordinary fixed point type, and apply the constraint to
597    --  obtain subtype of it.
598
599    procedure Prepare_Private_Subtype_Completion
600      (Id          : Entity_Id;
601       Related_Nod : Node_Id);
602    --  Id is a subtype of some private type. Creates the full declaration
603    --  associated with Id whenever possible, i.e. when the full declaration
604    --  of the base type is already known. Records each subtype into
605    --  Private_Dependents of the base type.
606
607    procedure Process_Incomplete_Dependents
608      (N      : Node_Id;
609       Full_T : Entity_Id;
610       Inc_T  : Entity_Id);
611    --  Process all entities that depend on an incomplete type. There include
612    --  subtypes, subprogram types that mention the incomplete type in their
613    --  profiles, and subprogram with access parameters that designate the
614    --  incomplete type.
615
616    --  Inc_T is the defining identifier of an incomplete type declaration, its
617    --  Ekind is E_Incomplete_Type.
618    --
619    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
620    --
621    --    Full_T is N's defining identifier.
622    --
623    --  Subtypes of incomplete types with discriminants are completed when the
624    --  parent type is. This is simpler than private subtypes, because they can
625    --  only appear in the same scope, and there is no need to exchange views.
626    --  Similarly, access_to_subprogram types may have a parameter or a return
627    --  type that is an incomplete type, and that must be replaced with the
628    --  full type.
629    --
630    --  If the full type is tagged, subprogram with access parameters that
631    --  designated the incomplete may be primitive operations of the full type,
632    --  and have to be processed accordingly.
633
634    procedure Process_Real_Range_Specification (Def : Node_Id);
635    --  Given the type definition for a real type, this procedure processes and
636    --  checks the real range specification of this type definition if one is
637    --  present. If errors are found, error messages are posted, and the
638    --  Real_Range_Specification of Def is reset to Empty.
639
640    procedure Record_Type_Declaration
641      (T    : Entity_Id;
642       N    : Node_Id;
643       Prev : Entity_Id);
644    --  Process a record type declaration (for both untagged and tagged
645    --  records). Parameters T and N are exactly like in procedure
646    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
647    --  for this routine. If this is the completion of an incomplete type
648    --  declaration, Prev is the entity of the incomplete declaration, used for
649    --  cross-referencing. Otherwise Prev = T.
650
651    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
652    --  This routine is used to process the actual record type definition (both
653    --  for untagged and tagged records). Def is a record type definition node.
654    --  This procedure analyzes the components in this record type definition.
655    --  Prev_T is the entity for the enclosing record type. It is provided so
656    --  that its Has_Task flag can be set if any of the component have Has_Task
657    --  set. If the declaration is the completion of an incomplete type
658    --  declaration, Prev_T is the original incomplete type, whose full view is
659    --  the record type.
660
661    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
662    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
663    --  build a copy of the declaration tree of the parent, and we create
664    --  independently the list of components for the derived type. Semantic
665    --  information uses the component entities, but record representation
666    --  clauses are validated on the declaration tree. This procedure replaces
667    --  discriminants and components in the declaration with those that have
668    --  been created by Inherit_Components.
669
670    procedure Set_Fixed_Range
671      (E   : Entity_Id;
672       Loc : Source_Ptr;
673       Lo  : Ureal;
674       Hi  : Ureal);
675    --  Build a range node with the given bounds and set it as the Scalar_Range
676    --  of the given fixed-point type entity. Loc is the source location used
677    --  for the constructed range. See body for further details.
678
679    procedure Set_Scalar_Range_For_Subtype
680      (Def_Id : Entity_Id;
681       R      : Node_Id;
682       Subt   : Entity_Id);
683    --  This routine is used to set the scalar range field for a subtype given
684    --  Def_Id, the entity for the subtype, and R, the range expression for the
685    --  scalar range. Subt provides the parent subtype to be used to analyze,
686    --  resolve, and check the given range.
687
688    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
689    --  Create a new signed integer entity, and apply the constraint to obtain
690    --  the required first named subtype of this type.
691
692    procedure Set_Stored_Constraint_From_Discriminant_Constraint
693      (E : Entity_Id);
694    --  E is some record type. This routine computes E's Stored_Constraint
695    --  from its Discriminant_Constraint.
696
697    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
698    --  Check that an entity in a list of progenitors is an interface,
699    --  emit error otherwise.
700
701    -----------------------
702    -- Access_Definition --
703    -----------------------
704
705    function Access_Definition
706      (Related_Nod : Node_Id;
707       N           : Node_Id) return Entity_Id
708    is
709       Anon_Type           : Entity_Id;
710       Anon_Scope          : Entity_Id;
711       Desig_Type          : Entity_Id;
712       Enclosing_Prot_Type : Entity_Id := Empty;
713
714    begin
715       Check_SPARK_Restriction ("access type is not allowed", N);
716
717       if Is_Entry (Current_Scope)
718         and then Is_Task_Type (Etype (Scope (Current_Scope)))
719       then
720          Error_Msg_N ("task entries cannot have access parameters", N);
721          return Empty;
722       end if;
723
724       --  Ada 2005: for an object declaration the corresponding anonymous
725       --  type is declared in the current scope.
726
727       --  If the access definition is the return type of another access to
728       --  function, scope is the current one, because it is the one of the
729       --  current type declaration.
730
731       if Nkind_In (Related_Nod, N_Object_Declaration,
732                                 N_Access_Function_Definition)
733       then
734          Anon_Scope := Current_Scope;
735
736       --  For the anonymous function result case, retrieve the scope of the
737       --  function specification's associated entity rather than using the
738       --  current scope. The current scope will be the function itself if the
739       --  formal part is currently being analyzed, but will be the parent scope
740       --  in the case of a parameterless function, and we always want to use
741       --  the function's parent scope. Finally, if the function is a child
742       --  unit, we must traverse the tree to retrieve the proper entity.
743
744       elsif Nkind (Related_Nod) = N_Function_Specification
745         and then Nkind (Parent (N)) /= N_Parameter_Specification
746       then
747          --  If the current scope is a protected type, the anonymous access
748          --  is associated with one of the protected operations, and must
749          --  be available in the scope that encloses the protected declaration.
750          --  Otherwise the type is in the scope enclosing the subprogram.
751
752          --  If the function has formals, The return type of a subprogram
753          --  declaration is analyzed in the scope of the subprogram (see
754          --  Process_Formals) and thus the protected type, if present, is
755          --  the scope of the current function scope.
756
757          if Ekind (Current_Scope) = E_Protected_Type then
758             Enclosing_Prot_Type := Current_Scope;
759
760          elsif Ekind (Current_Scope) = E_Function
761            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
762          then
763             Enclosing_Prot_Type := Scope (Current_Scope);
764          end if;
765
766          if Present (Enclosing_Prot_Type) then
767             Anon_Scope := Scope (Enclosing_Prot_Type);
768
769          else
770             Anon_Scope := Scope (Defining_Entity (Related_Nod));
771          end if;
772
773       --  For an access type definition, if the current scope is a child
774       --  unit it is the scope of the type.
775
776       elsif Is_Compilation_Unit (Current_Scope) then
777          Anon_Scope := Current_Scope;
778
779       --  For access formals, access components, and access discriminants, the
780       --  scope is that of the enclosing declaration,
781
782       else
783          Anon_Scope := Scope (Current_Scope);
784       end if;
785
786       Anon_Type :=
787         Create_Itype
788           (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
789
790       if All_Present (N)
791         and then Ada_Version >= Ada_2005
792       then
793          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
794       end if;
795
796       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
797       --  the corresponding semantic routine
798
799       if Present (Access_To_Subprogram_Definition (N)) then
800
801          --  Compiler runtime units are compiled in Ada 2005 mode when building
802          --  the runtime library but must also be compilable in Ada 95 mode
803          --  (when bootstrapping the compiler).
804
805          Check_Compiler_Unit (N);
806
807          Access_Subprogram_Declaration
808            (T_Name => Anon_Type,
809             T_Def  => Access_To_Subprogram_Definition (N));
810
811          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
812             Set_Ekind
813               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
814          else
815             Set_Ekind
816               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
817          end if;
818
819          Set_Can_Use_Internal_Rep
820            (Anon_Type, not Always_Compatible_Rep_On_Target);
821
822          --  If the anonymous access is associated with a protected operation,
823          --  create a reference to it after the enclosing protected definition
824          --  because the itype will be used in the subsequent bodies.
825
826          if Ekind (Current_Scope) = E_Protected_Type then
827             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
828          end if;
829
830          return Anon_Type;
831       end if;
832
833       Find_Type (Subtype_Mark (N));
834       Desig_Type := Entity (Subtype_Mark (N));
835
836       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
837       Set_Etype (Anon_Type, Anon_Type);
838
839       --  Make sure the anonymous access type has size and alignment fields
840       --  set, as required by gigi. This is necessary in the case of the
841       --  Task_Body_Procedure.
842
843       if not Has_Private_Component (Desig_Type) then
844          Layout_Type (Anon_Type);
845       end if;
846
847       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
848       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
849       --  the null value is allowed. In Ada 95 the null value is never allowed.
850
851       if Ada_Version >= Ada_2005 then
852          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
853       else
854          Set_Can_Never_Be_Null (Anon_Type, True);
855       end if;
856
857       --  The anonymous access type is as public as the discriminated type or
858       --  subprogram that defines it. It is imported (for back-end purposes)
859       --  if the designated type is.
860
861       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
862
863       --  Ada 2005 (AI-231): Propagate the access-constant attribute
864
865       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
866
867       --  The context is either a subprogram declaration, object declaration,
868       --  or an access discriminant, in a private or a full type declaration.
869       --  In the case of a subprogram, if the designated type is incomplete,
870       --  the operation will be a primitive operation of the full type, to be
871       --  updated subsequently. If the type is imported through a limited_with
872       --  clause, the subprogram is not a primitive operation of the type
873       --  (which is declared elsewhere in some other scope).
874
875       if Ekind (Desig_Type) = E_Incomplete_Type
876         and then not From_With_Type (Desig_Type)
877         and then Is_Overloadable (Current_Scope)
878       then
879          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
880          Set_Has_Delayed_Freeze (Current_Scope);
881       end if;
882
883       --  Ada 2005: if the designated type is an interface that may contain
884       --  tasks, create a Master entity for the declaration. This must be done
885       --  before expansion of the full declaration, because the declaration may
886       --  include an expression that is an allocator, whose expansion needs the
887       --  proper Master for the created tasks.
888
889       if Nkind (Related_Nod) = N_Object_Declaration
890         and then Expander_Active
891       then
892          if Is_Interface (Desig_Type)
893            and then Is_Limited_Record (Desig_Type)
894          then
895             Build_Class_Wide_Master (Anon_Type);
896
897          --  Similarly, if the type is an anonymous access that designates
898          --  tasks, create a master entity for it in the current context.
899
900          elsif Has_Task (Desig_Type)
901            and then Comes_From_Source (Related_Nod)
902          then
903             Build_Master_Entity (Defining_Identifier (Related_Nod));
904             Build_Master_Renaming (Anon_Type);
905          end if;
906       end if;
907
908       --  For a private component of a protected type, it is imperative that
909       --  the back-end elaborate the type immediately after the protected
910       --  declaration, because this type will be used in the declarations
911       --  created for the component within each protected body, so we must
912       --  create an itype reference for it now.
913
914       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
915          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
916
917       --  Similarly, if the access definition is the return result of a
918       --  function, create an itype reference for it because it will be used
919       --  within the function body. For a regular function that is not a
920       --  compilation unit, insert reference after the declaration. For a
921       --  protected operation, insert it after the enclosing protected type
922       --  declaration. In either case, do not create a reference for a type
923       --  obtained through a limited_with clause, because this would introduce
924       --  semantic dependencies.
925
926       --  Similarly, do not create a reference if the designated type is a
927       --  generic formal, because no use of it will reach the backend.
928
929       elsif Nkind (Related_Nod) = N_Function_Specification
930         and then not From_With_Type (Desig_Type)
931         and then not Is_Generic_Type (Desig_Type)
932       then
933          if Present (Enclosing_Prot_Type) then
934             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
935
936          elsif Is_List_Member (Parent (Related_Nod))
937            and then Nkind (Parent (N)) /= N_Parameter_Specification
938          then
939             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
940          end if;
941
942       --  Finally, create an itype reference for an object declaration of an
943       --  anonymous access type. This is strictly necessary only for deferred
944       --  constants, but in any case will avoid out-of-scope problems in the
945       --  back-end.
946
947       elsif Nkind (Related_Nod) = N_Object_Declaration then
948          Build_Itype_Reference (Anon_Type, Related_Nod);
949       end if;
950
951       return Anon_Type;
952    end Access_Definition;
953
954    -----------------------------------
955    -- Access_Subprogram_Declaration --
956    -----------------------------------
957
958    procedure Access_Subprogram_Declaration
959      (T_Name : Entity_Id;
960       T_Def  : Node_Id)
961    is
962
963       procedure Check_For_Premature_Usage (Def : Node_Id);
964       --  Check that type T_Name is not used, directly or recursively, as a
965       --  parameter or a return type in Def. Def is either a subtype, an
966       --  access_definition, or an access_to_subprogram_definition.
967
968       -------------------------------
969       -- Check_For_Premature_Usage --
970       -------------------------------
971
972       procedure Check_For_Premature_Usage (Def : Node_Id) is
973          Param : Node_Id;
974
975       begin
976          --  Check for a subtype mark
977
978          if Nkind (Def) in N_Has_Etype then
979             if Etype (Def) = T_Name then
980                Error_Msg_N
981                  ("type& cannot be used before end of its declaration", Def);
982             end if;
983
984          --  If this is not a subtype, then this is an access_definition
985
986          elsif Nkind (Def) = N_Access_Definition then
987             if Present (Access_To_Subprogram_Definition (Def)) then
988                Check_For_Premature_Usage
989                  (Access_To_Subprogram_Definition (Def));
990             else
991                Check_For_Premature_Usage (Subtype_Mark (Def));
992             end if;
993
994          --  The only cases left are N_Access_Function_Definition and
995          --  N_Access_Procedure_Definition.
996
997          else
998             if Present (Parameter_Specifications (Def)) then
999                Param := First (Parameter_Specifications (Def));
1000                while Present (Param) loop
1001                   Check_For_Premature_Usage (Parameter_Type (Param));
1002                   Param := Next (Param);
1003                end loop;
1004             end if;
1005
1006             if Nkind (Def) = N_Access_Function_Definition then
1007                Check_For_Premature_Usage (Result_Definition (Def));
1008             end if;
1009          end if;
1010       end Check_For_Premature_Usage;
1011
1012       --  Local variables
1013
1014       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1015       Formal     : Entity_Id;
1016       D_Ityp     : Node_Id;
1017       Desig_Type : constant Entity_Id :=
1018                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1019
1020    --  Start of processing for Access_Subprogram_Declaration
1021
1022    begin
1023       Check_SPARK_Restriction ("access type is not allowed", T_Def);
1024
1025       --  Associate the Itype node with the inner full-type declaration or
1026       --  subprogram spec or entry body. This is required to handle nested
1027       --  anonymous declarations. For example:
1028
1029       --      procedure P
1030       --       (X : access procedure
1031       --                     (Y : access procedure
1032       --                                   (Z : access T)))
1033
1034       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1035       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1036                                    N_Private_Type_Declaration,
1037                                    N_Private_Extension_Declaration,
1038                                    N_Procedure_Specification,
1039                                    N_Function_Specification,
1040                                    N_Entry_Body)
1041
1042                    or else
1043                  Nkind_In (D_Ityp, N_Object_Declaration,
1044                                    N_Object_Renaming_Declaration,
1045                                    N_Formal_Object_Declaration,
1046                                    N_Formal_Type_Declaration,
1047                                    N_Task_Type_Declaration,
1048                                    N_Protected_Type_Declaration))
1049       loop
1050          D_Ityp := Parent (D_Ityp);
1051          pragma Assert (D_Ityp /= Empty);
1052       end loop;
1053
1054       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1055
1056       if Nkind_In (D_Ityp, N_Procedure_Specification,
1057                            N_Function_Specification)
1058       then
1059          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1060
1061       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1062                               N_Object_Declaration,
1063                               N_Object_Renaming_Declaration,
1064                               N_Formal_Type_Declaration)
1065       then
1066          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1067       end if;
1068
1069       if Nkind (T_Def) = N_Access_Function_Definition then
1070          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1071             declare
1072                Acc : constant Node_Id := Result_Definition (T_Def);
1073
1074             begin
1075                if Present (Access_To_Subprogram_Definition (Acc))
1076                  and then
1077                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1078                then
1079                   Set_Etype
1080                     (Desig_Type,
1081                        Replace_Anonymous_Access_To_Protected_Subprogram
1082                          (T_Def));
1083
1084                else
1085                   Set_Etype
1086                     (Desig_Type,
1087                        Access_Definition (T_Def, Result_Definition (T_Def)));
1088                end if;
1089             end;
1090
1091          else
1092             Analyze (Result_Definition (T_Def));
1093
1094             declare
1095                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1096
1097             begin
1098                --  If a null exclusion is imposed on the result type, then
1099                --  create a null-excluding itype (an access subtype) and use
1100                --  it as the function's Etype.
1101
1102                if Is_Access_Type (Typ)
1103                  and then Null_Exclusion_In_Return_Present (T_Def)
1104                then
1105                   Set_Etype  (Desig_Type,
1106                     Create_Null_Excluding_Itype
1107                       (T           => Typ,
1108                        Related_Nod => T_Def,
1109                        Scope_Id    => Current_Scope));
1110
1111                else
1112                   if From_With_Type (Typ) then
1113
1114                      --  AI05-151: Incomplete types are allowed in all basic
1115                      --  declarations, including access to subprograms.
1116
1117                      if Ada_Version >= Ada_2012 then
1118                         null;
1119
1120                      else
1121                         Error_Msg_NE
1122                          ("illegal use of incomplete type&",
1123                             Result_Definition (T_Def), Typ);
1124                      end if;
1125
1126                   elsif Ekind (Current_Scope) = E_Package
1127                     and then In_Private_Part (Current_Scope)
1128                   then
1129                      if Ekind (Typ) = E_Incomplete_Type then
1130                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1131
1132                      elsif Is_Class_Wide_Type (Typ)
1133                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1134                      then
1135                         Append_Elmt
1136                           (Desig_Type, Private_Dependents (Etype (Typ)));
1137                      end if;
1138                   end if;
1139
1140                   Set_Etype (Desig_Type, Typ);
1141                end if;
1142             end;
1143          end if;
1144
1145          if not (Is_Type (Etype (Desig_Type))) then
1146             Error_Msg_N
1147               ("expect type in function specification",
1148                Result_Definition (T_Def));
1149          end if;
1150
1151       else
1152          Set_Etype (Desig_Type, Standard_Void_Type);
1153       end if;
1154
1155       if Present (Formals) then
1156          Push_Scope (Desig_Type);
1157
1158          --  A bit of a kludge here. These kludges will be removed when Itypes
1159          --  have proper parent pointers to their declarations???
1160
1161          --  Kludge 1) Link defining_identifier of formals. Required by
1162          --  First_Formal to provide its functionality.
1163
1164          declare
1165             F : Node_Id;
1166
1167          begin
1168             F := First (Formals);
1169
1170             --  In ASIS mode, the access_to_subprogram may be analyzed twice,
1171             --  when it is part of an unconstrained type and subtype expansion
1172             --  is disabled. To avoid back-end problems with shared profiles,
1173             --  use previous subprogram type as the designated type.
1174
1175             if ASIS_Mode
1176               and then Present (Scope (Defining_Identifier (F)))
1177             then
1178                Set_Etype                    (T_Name, T_Name);
1179                Init_Size_Align              (T_Name);
1180                Set_Directly_Designated_Type (T_Name,
1181                  Scope (Defining_Identifier (F)));
1182                return;
1183             end if;
1184
1185             while Present (F) loop
1186                if No (Parent (Defining_Identifier (F))) then
1187                   Set_Parent (Defining_Identifier (F), F);
1188                end if;
1189
1190                Next (F);
1191             end loop;
1192          end;
1193
1194          Process_Formals (Formals, Parent (T_Def));
1195
1196          --  Kludge 2) End_Scope requires that the parent pointer be set to
1197          --  something reasonable, but Itypes don't have parent pointers. So
1198          --  we set it and then unset it ???
1199
1200          Set_Parent (Desig_Type, T_Name);
1201          End_Scope;
1202          Set_Parent (Desig_Type, Empty);
1203       end if;
1204
1205       --  Check for premature usage of the type being defined
1206
1207       Check_For_Premature_Usage (T_Def);
1208
1209       --  The return type and/or any parameter type may be incomplete. Mark
1210       --  the subprogram_type as depending on the incomplete type, so that
1211       --  it can be updated when the full type declaration is seen. This
1212       --  only applies to incomplete types declared in some enclosing scope,
1213       --  not to limited views from other packages.
1214
1215       if Present (Formals) then
1216          Formal := First_Formal (Desig_Type);
1217          while Present (Formal) loop
1218             if Ekind (Formal) /= E_In_Parameter
1219               and then Nkind (T_Def) = N_Access_Function_Definition
1220             then
1221                Error_Msg_N ("functions can only have IN parameters", Formal);
1222             end if;
1223
1224             if Ekind (Etype (Formal)) = E_Incomplete_Type
1225               and then In_Open_Scopes (Scope (Etype (Formal)))
1226             then
1227                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1228                Set_Has_Delayed_Freeze (Desig_Type);
1229             end if;
1230
1231             Next_Formal (Formal);
1232          end loop;
1233       end if;
1234
1235       --  If the return type is incomplete, this is legal as long as the
1236       --  type is declared in the current scope and will be completed in
1237       --  it (rather than being part of limited view).
1238
1239       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1240         and then not Has_Delayed_Freeze (Desig_Type)
1241         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1242       then
1243          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1244          Set_Has_Delayed_Freeze (Desig_Type);
1245       end if;
1246
1247       Check_Delayed_Subprogram (Desig_Type);
1248
1249       if Protected_Present (T_Def) then
1250          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1251          Set_Convention (Desig_Type, Convention_Protected);
1252       else
1253          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1254       end if;
1255
1256       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1257
1258       Set_Etype                    (T_Name, T_Name);
1259       Init_Size_Align              (T_Name);
1260       Set_Directly_Designated_Type (T_Name, Desig_Type);
1261
1262       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1263
1264       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1265
1266       Check_Restriction (No_Access_Subprograms, T_Def);
1267    end Access_Subprogram_Declaration;
1268
1269    ----------------------------
1270    -- Access_Type_Declaration --
1271    ----------------------------
1272
1273    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1274       P : constant Node_Id := Parent (Def);
1275       S : constant Node_Id := Subtype_Indication (Def);
1276
1277       Full_Desig : Entity_Id;
1278
1279    begin
1280       Check_SPARK_Restriction ("access type is not allowed", Def);
1281
1282       --  Check for permissible use of incomplete type
1283
1284       if Nkind (S) /= N_Subtype_Indication then
1285          Analyze (S);
1286
1287          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1288             Set_Directly_Designated_Type (T, Entity (S));
1289          else
1290             Set_Directly_Designated_Type (T,
1291               Process_Subtype (S, P, T, 'P'));
1292          end if;
1293
1294       else
1295          Set_Directly_Designated_Type (T,
1296            Process_Subtype (S, P, T, 'P'));
1297       end if;
1298
1299       if All_Present (Def) or Constant_Present (Def) then
1300          Set_Ekind (T, E_General_Access_Type);
1301       else
1302          Set_Ekind (T, E_Access_Type);
1303       end if;
1304
1305       Full_Desig := Designated_Type (T);
1306
1307       if Base_Type (Full_Desig) = T then
1308          Error_Msg_N ("access type cannot designate itself", S);
1309
1310       --  In Ada 2005, the type may have a limited view through some unit
1311       --  in its own context, allowing the following circularity that cannot
1312       --  be detected earlier
1313
1314       elsif Is_Class_Wide_Type (Full_Desig)
1315         and then Etype (Full_Desig) = T
1316       then
1317          Error_Msg_N
1318            ("access type cannot designate its own classwide type", S);
1319
1320          --  Clean up indication of tagged status to prevent cascaded errors
1321
1322          Set_Is_Tagged_Type (T, False);
1323       end if;
1324
1325       Set_Etype (T, T);
1326
1327       --  If the type has appeared already in a with_type clause, it is
1328       --  frozen and the pointer size is already set. Else, initialize.
1329
1330       if not From_With_Type (T) then
1331          Init_Size_Align (T);
1332       end if;
1333
1334       --  Note that Has_Task is always false, since the access type itself
1335       --  is not a task type. See Einfo for more description on this point.
1336       --  Exactly the same consideration applies to Has_Controlled_Component.
1337
1338       Set_Has_Task (T, False);
1339       Set_Has_Controlled_Component (T, False);
1340
1341       --  Initialize field Finalization_Master explicitly to Empty, to avoid
1342       --  problems where an incomplete view of this entity has been previously
1343       --  established by a limited with and an overlaid version of this field
1344       --  (Stored_Constraint) was initialized for the incomplete view.
1345
1346       --  This reset is performed in most cases except where the access type
1347       --  has been created for the purposes of allocating or deallocating a
1348       --  build-in-place object. Such access types have explicitly set pools
1349       --  and finalization masters.
1350
1351       if No (Associated_Storage_Pool (T)) then
1352          Set_Finalization_Master (T, Empty);
1353       end if;
1354
1355       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1356       --  attributes
1357
1358       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1359       Set_Is_Access_Constant (T, Constant_Present (Def));
1360    end Access_Type_Declaration;
1361
1362    ----------------------------------
1363    -- Add_Interface_Tag_Components --
1364    ----------------------------------
1365
1366    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1367       Loc      : constant Source_Ptr := Sloc (N);
1368       L        : List_Id;
1369       Last_Tag : Node_Id;
1370
1371       procedure Add_Tag (Iface : Entity_Id);
1372       --  Add tag for one of the progenitor interfaces
1373
1374       -------------
1375       -- Add_Tag --
1376       -------------
1377
1378       procedure Add_Tag (Iface : Entity_Id) is
1379          Decl   : Node_Id;
1380          Def    : Node_Id;
1381          Tag    : Entity_Id;
1382          Offset : Entity_Id;
1383
1384       begin
1385          pragma Assert (Is_Tagged_Type (Iface)
1386            and then Is_Interface (Iface));
1387
1388          --  This is a reasonable place to propagate predicates
1389
1390          if Has_Predicates (Iface) then
1391             Set_Has_Predicates (Typ);
1392          end if;
1393
1394          Def :=
1395            Make_Component_Definition (Loc,
1396              Aliased_Present    => True,
1397              Subtype_Indication =>
1398                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1399
1400          Tag := Make_Temporary (Loc, 'V');
1401
1402          Decl :=
1403            Make_Component_Declaration (Loc,
1404              Defining_Identifier  => Tag,
1405              Component_Definition => Def);
1406
1407          Analyze_Component_Declaration (Decl);
1408
1409          Set_Analyzed (Decl);
1410          Set_Ekind               (Tag, E_Component);
1411          Set_Is_Tag              (Tag);
1412          Set_Is_Aliased          (Tag);
1413          Set_Related_Type        (Tag, Iface);
1414          Init_Component_Location (Tag);
1415
1416          pragma Assert (Is_Frozen (Iface));
1417
1418          Set_DT_Entry_Count    (Tag,
1419            DT_Entry_Count (First_Entity (Iface)));
1420
1421          if No (Last_Tag) then
1422             Prepend (Decl, L);
1423          else
1424             Insert_After (Last_Tag, Decl);
1425          end if;
1426
1427          Last_Tag := Decl;
1428
1429          --  If the ancestor has discriminants we need to give special support
1430          --  to store the offset_to_top value of the secondary dispatch tables.
1431          --  For this purpose we add a supplementary component just after the
1432          --  field that contains the tag associated with each secondary DT.
1433
1434          if Typ /= Etype (Typ)
1435            and then Has_Discriminants (Etype (Typ))
1436          then
1437             Def :=
1438               Make_Component_Definition (Loc,
1439                 Subtype_Indication =>
1440                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1441
1442             Offset := Make_Temporary (Loc, 'V');
1443
1444             Decl :=
1445               Make_Component_Declaration (Loc,
1446                 Defining_Identifier  => Offset,
1447                 Component_Definition => Def);
1448
1449             Analyze_Component_Declaration (Decl);
1450
1451             Set_Analyzed (Decl);
1452             Set_Ekind               (Offset, E_Component);
1453             Set_Is_Aliased          (Offset);
1454             Set_Related_Type        (Offset, Iface);
1455             Init_Component_Location (Offset);
1456             Insert_After (Last_Tag, Decl);
1457             Last_Tag := Decl;
1458          end if;
1459       end Add_Tag;
1460
1461       --  Local variables
1462
1463       Elmt : Elmt_Id;
1464       Ext  : Node_Id;
1465       Comp : Node_Id;
1466
1467    --  Start of processing for Add_Interface_Tag_Components
1468
1469    begin
1470       if not RTE_Available (RE_Interface_Tag) then
1471          Error_Msg
1472            ("(Ada 2005) interface types not supported by this run-time!",
1473             Sloc (N));
1474          return;
1475       end if;
1476
1477       if Ekind (Typ) /= E_Record_Type
1478         or else (Is_Concurrent_Record_Type (Typ)
1479                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1480         or else (not Is_Concurrent_Record_Type (Typ)
1481                   and then No (Interfaces (Typ))
1482                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1483       then
1484          return;
1485       end if;
1486
1487       --  Find the current last tag
1488
1489       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1490          Ext := Record_Extension_Part (Type_Definition (N));
1491       else
1492          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1493          Ext := Type_Definition (N);
1494       end if;
1495
1496       Last_Tag := Empty;
1497
1498       if not (Present (Component_List (Ext))) then
1499          Set_Null_Present (Ext, False);
1500          L := New_List;
1501          Set_Component_List (Ext,
1502            Make_Component_List (Loc,
1503              Component_Items => L,
1504              Null_Present => False));
1505       else
1506          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1507             L := Component_Items
1508                    (Component_List
1509                      (Record_Extension_Part
1510                        (Type_Definition (N))));
1511          else
1512             L := Component_Items
1513                    (Component_List
1514                      (Type_Definition (N)));
1515          end if;
1516
1517          --  Find the last tag component
1518
1519          Comp := First (L);
1520          while Present (Comp) loop
1521             if Nkind (Comp) = N_Component_Declaration
1522               and then Is_Tag (Defining_Identifier (Comp))
1523             then
1524                Last_Tag := Comp;
1525             end if;
1526
1527             Next (Comp);
1528          end loop;
1529       end if;
1530
1531       --  At this point L references the list of components and Last_Tag
1532       --  references the current last tag (if any). Now we add the tag
1533       --  corresponding with all the interfaces that are not implemented
1534       --  by the parent.
1535
1536       if Present (Interfaces (Typ)) then
1537          Elmt := First_Elmt (Interfaces (Typ));
1538          while Present (Elmt) loop
1539             Add_Tag (Node (Elmt));
1540             Next_Elmt (Elmt);
1541          end loop;
1542       end if;
1543    end Add_Interface_Tag_Components;
1544
1545    -------------------------------------
1546    -- Add_Internal_Interface_Entities --
1547    -------------------------------------
1548
1549    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1550       Elmt          : Elmt_Id;
1551       Iface         : Entity_Id;
1552       Iface_Elmt    : Elmt_Id;
1553       Iface_Prim    : Entity_Id;
1554       Ifaces_List   : Elist_Id;
1555       New_Subp      : Entity_Id := Empty;
1556       Prim          : Entity_Id;
1557       Restore_Scope : Boolean := False;
1558
1559    begin
1560       pragma Assert (Ada_Version >= Ada_2005
1561         and then Is_Record_Type (Tagged_Type)
1562         and then Is_Tagged_Type (Tagged_Type)
1563         and then Has_Interfaces (Tagged_Type)
1564         and then not Is_Interface (Tagged_Type));
1565
1566       --  Ensure that the internal entities are added to the scope of the type
1567
1568       if Scope (Tagged_Type) /= Current_Scope then
1569          Push_Scope (Scope (Tagged_Type));
1570          Restore_Scope := True;
1571       end if;
1572
1573       Collect_Interfaces (Tagged_Type, Ifaces_List);
1574
1575       Iface_Elmt := First_Elmt (Ifaces_List);
1576       while Present (Iface_Elmt) loop
1577          Iface := Node (Iface_Elmt);
1578
1579          --  Originally we excluded here from this processing interfaces that
1580          --  are parents of Tagged_Type because their primitives are located
1581          --  in the primary dispatch table (and hence no auxiliary internal
1582          --  entities are required to handle secondary dispatch tables in such
1583          --  case). However, these auxiliary entities are also required to
1584          --  handle derivations of interfaces in formals of generics (see
1585          --  Derive_Subprograms).
1586
1587          Elmt := First_Elmt (Primitive_Operations (Iface));
1588          while Present (Elmt) loop
1589             Iface_Prim := Node (Elmt);
1590
1591             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1592                Prim :=
1593                  Find_Primitive_Covering_Interface
1594                    (Tagged_Type => Tagged_Type,
1595                     Iface_Prim  => Iface_Prim);
1596
1597                if No (Prim) and then Serious_Errors_Detected > 0 then
1598                   goto Continue;
1599                end if;
1600
1601                pragma Assert (Present (Prim));
1602
1603                --  Ada 2012 (AI05-0197): If the name of the covering primitive
1604                --  differs from the name of the interface primitive then it is
1605                --  a private primitive inherited from a parent type. In such
1606                --  case, given that Tagged_Type covers the interface, the
1607                --  inherited private primitive becomes visible. For such
1608                --  purpose we add a new entity that renames the inherited
1609                --  private primitive.
1610
1611                if Chars (Prim) /= Chars (Iface_Prim) then
1612                   pragma Assert (Has_Suffix (Prim, 'P'));
1613                   Derive_Subprogram
1614                     (New_Subp     => New_Subp,
1615                      Parent_Subp  => Iface_Prim,
1616                      Derived_Type => Tagged_Type,
1617                      Parent_Type  => Iface);
1618                   Set_Alias (New_Subp, Prim);
1619                   Set_Is_Abstract_Subprogram
1620                     (New_Subp, Is_Abstract_Subprogram (Prim));
1621                end if;
1622
1623                Derive_Subprogram
1624                  (New_Subp     => New_Subp,
1625                   Parent_Subp  => Iface_Prim,
1626                   Derived_Type => Tagged_Type,
1627                   Parent_Type  => Iface);
1628
1629                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1630                --  associated with interface types. These entities are
1631                --  only registered in the list of primitives of its
1632                --  corresponding tagged type because they are only used
1633                --  to fill the contents of the secondary dispatch tables.
1634                --  Therefore they are removed from the homonym chains.
1635
1636                Set_Is_Hidden (New_Subp);
1637                Set_Is_Internal (New_Subp);
1638                Set_Alias (New_Subp, Prim);
1639                Set_Is_Abstract_Subprogram
1640                  (New_Subp, Is_Abstract_Subprogram (Prim));
1641                Set_Interface_Alias (New_Subp, Iface_Prim);
1642
1643                --  Internal entities associated with interface types are
1644                --  only registered in the list of primitives of the tagged
1645                --  type. They are only used to fill the contents of the
1646                --  secondary dispatch tables. Therefore they are not needed
1647                --  in the homonym chains.
1648
1649                Remove_Homonym (New_Subp);
1650
1651                --  Hidden entities associated with interfaces must have set
1652                --  the Has_Delay_Freeze attribute to ensure that, in case of
1653                --  locally defined tagged types (or compiling with static
1654                --  dispatch tables generation disabled) the corresponding
1655                --  entry of the secondary dispatch table is filled when
1656                --  such an entity is frozen.
1657
1658                Set_Has_Delayed_Freeze (New_Subp);
1659             end if;
1660
1661             <<Continue>>
1662             Next_Elmt (Elmt);
1663          end loop;
1664
1665          Next_Elmt (Iface_Elmt);
1666       end loop;
1667
1668       if Restore_Scope then
1669          Pop_Scope;
1670       end if;
1671    end Add_Internal_Interface_Entities;
1672
1673    -----------------------------------
1674    -- Analyze_Component_Declaration --
1675    -----------------------------------
1676
1677    procedure Analyze_Component_Declaration (N : Node_Id) is
1678       Id  : constant Entity_Id := Defining_Identifier (N);
1679       E   : constant Node_Id   := Expression (N);
1680       Typ : constant Node_Id   :=
1681               Subtype_Indication (Component_Definition (N));
1682       T   : Entity_Id;
1683       P   : Entity_Id;
1684
1685       function Contains_POC (Constr : Node_Id) return Boolean;
1686       --  Determines whether a constraint uses the discriminant of a record
1687       --  type thus becoming a per-object constraint (POC).
1688
1689       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1690       --  Typ is the type of the current component, check whether this type is
1691       --  a limited type. Used to validate declaration against that of
1692       --  enclosing record.
1693
1694       ------------------
1695       -- Contains_POC --
1696       ------------------
1697
1698       function Contains_POC (Constr : Node_Id) return Boolean is
1699       begin
1700          --  Prevent cascaded errors
1701
1702          if Error_Posted (Constr) then
1703             return False;
1704          end if;
1705
1706          case Nkind (Constr) is
1707             when N_Attribute_Reference =>
1708                return
1709                  Attribute_Name (Constr) = Name_Access
1710                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1711
1712             when N_Discriminant_Association =>
1713                return Denotes_Discriminant (Expression (Constr));
1714
1715             when N_Identifier =>
1716                return Denotes_Discriminant (Constr);
1717
1718             when N_Index_Or_Discriminant_Constraint =>
1719                declare
1720                   IDC : Node_Id;
1721
1722                begin
1723                   IDC := First (Constraints (Constr));
1724                   while Present (IDC) loop
1725
1726                      --  One per-object constraint is sufficient
1727
1728                      if Contains_POC (IDC) then
1729                         return True;
1730                      end if;
1731
1732                      Next (IDC);
1733                   end loop;
1734
1735                   return False;
1736                end;
1737
1738             when N_Range =>
1739                return Denotes_Discriminant (Low_Bound (Constr))
1740                         or else
1741                       Denotes_Discriminant (High_Bound (Constr));
1742
1743             when N_Range_Constraint =>
1744                return Denotes_Discriminant (Range_Expression (Constr));
1745
1746             when others =>
1747                return False;
1748
1749          end case;
1750       end Contains_POC;
1751
1752       ----------------------
1753       -- Is_Known_Limited --
1754       ----------------------
1755
1756       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1757          P : constant Entity_Id := Etype (Typ);
1758          R : constant Entity_Id := Root_Type (Typ);
1759
1760       begin
1761          if Is_Limited_Record (Typ) then
1762             return True;
1763
1764          --  If the root type is limited (and not a limited interface)
1765          --  so is the current type
1766
1767          elsif Is_Limited_Record (R)
1768            and then
1769              (not Is_Interface (R)
1770                or else not Is_Limited_Interface (R))
1771          then
1772             return True;
1773
1774          --  Else the type may have a limited interface progenitor, but a
1775          --  limited record parent.
1776
1777          elsif R /= P
1778            and then Is_Limited_Record (P)
1779          then
1780             return True;
1781
1782          else
1783             return False;
1784          end if;
1785       end Is_Known_Limited;
1786
1787    --  Start of processing for Analyze_Component_Declaration
1788
1789    begin
1790       Generate_Definition (Id);
1791       Enter_Name (Id);
1792
1793       if Present (Typ) then
1794          T := Find_Type_Of_Object
1795                 (Subtype_Indication (Component_Definition (N)), N);
1796
1797          if not Nkind_In (Typ, N_Identifier, N_Expanded_Name) then
1798             Check_SPARK_Restriction ("subtype mark required", Typ);
1799          end if;
1800
1801       --  Ada 2005 (AI-230): Access Definition case
1802
1803       else
1804          pragma Assert (Present
1805                           (Access_Definition (Component_Definition (N))));
1806
1807          T := Access_Definition
1808                 (Related_Nod => N,
1809                  N => Access_Definition (Component_Definition (N)));
1810          Set_Is_Local_Anonymous_Access (T);
1811
1812          --  Ada 2005 (AI-254)
1813
1814          if Present (Access_To_Subprogram_Definition
1815                       (Access_Definition (Component_Definition (N))))
1816            and then Protected_Present (Access_To_Subprogram_Definition
1817                                         (Access_Definition
1818                                           (Component_Definition (N))))
1819          then
1820             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1821          end if;
1822       end if;
1823
1824       --  If the subtype is a constrained subtype of the enclosing record,
1825       --  (which must have a partial view) the back-end does not properly
1826       --  handle the recursion. Rewrite the component declaration with an
1827       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1828       --  the tree directly because side effects have already been removed from
1829       --  discriminant constraints.
1830
1831       if Ekind (T) = E_Access_Subtype
1832         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1833         and then Comes_From_Source (T)
1834         and then Nkind (Parent (T)) = N_Subtype_Declaration
1835         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1836       then
1837          Rewrite
1838            (Subtype_Indication (Component_Definition (N)),
1839              New_Copy_Tree (Subtype_Indication (Parent (T))));
1840          T := Find_Type_Of_Object
1841                  (Subtype_Indication (Component_Definition (N)), N);
1842       end if;
1843
1844       --  If the component declaration includes a default expression, then we
1845       --  check that the component is not of a limited type (RM 3.7(5)),
1846       --  and do the special preanalysis of the expression (see section on
1847       --  "Handling of Default and Per-Object Expressions" in the spec of
1848       --  package Sem).
1849
1850       if Present (E) then
1851          Check_SPARK_Restriction ("default expression is not allowed", E);
1852          Preanalyze_Spec_Expression (E, T);
1853          Check_Initialization (T, E);
1854
1855          if Ada_Version >= Ada_2005
1856            and then Ekind (T) = E_Anonymous_Access_Type
1857            and then Etype (E) /= Any_Type
1858          then
1859             --  Check RM 3.9.2(9): "if the expected type for an expression is
1860             --  an anonymous access-to-specific tagged type, then the object
1861             --  designated by the expression shall not be dynamically tagged
1862             --  unless it is a controlling operand in a call on a dispatching
1863             --  operation"
1864
1865             if Is_Tagged_Type (Directly_Designated_Type (T))
1866               and then
1867                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1868               and then
1869                 Ekind (Directly_Designated_Type (Etype (E))) =
1870                   E_Class_Wide_Type
1871             then
1872                Error_Msg_N
1873                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1874             end if;
1875
1876             --  (Ada 2005: AI-230): Accessibility check for anonymous
1877             --  components
1878
1879             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1880                Error_Msg_N
1881                  ("expression has deeper access level than component " &
1882                   "(RM 3.10.2 (12.2))", E);
1883             end if;
1884
1885             --  The initialization expression is a reference to an access
1886             --  discriminant. The type of the discriminant is always deeper
1887             --  than any access type.
1888
1889             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1890               and then Is_Entity_Name (E)
1891               and then Ekind (Entity (E)) = E_In_Parameter
1892               and then Present (Discriminal_Link (Entity (E)))
1893             then
1894                Error_Msg_N
1895                  ("discriminant has deeper accessibility level than target",
1896                   E);
1897             end if;
1898          end if;
1899       end if;
1900
1901       --  The parent type may be a private view with unknown discriminants,
1902       --  and thus unconstrained. Regular components must be constrained.
1903
1904       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1905          if Is_Class_Wide_Type (T) then
1906             Error_Msg_N
1907                ("class-wide subtype with unknown discriminants" &
1908                  " in component declaration",
1909                  Subtype_Indication (Component_Definition (N)));
1910          else
1911             Error_Msg_N
1912               ("unconstrained subtype in component declaration",
1913                Subtype_Indication (Component_Definition (N)));
1914          end if;
1915
1916       --  Components cannot be abstract, except for the special case of
1917       --  the _Parent field (case of extending an abstract tagged type)
1918
1919       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1920          Error_Msg_N ("type of a component cannot be abstract", N);
1921       end if;
1922
1923       Set_Etype (Id, T);
1924       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1925
1926       --  The component declaration may have a per-object constraint, set
1927       --  the appropriate flag in the defining identifier of the subtype.
1928
1929       if Present (Subtype_Indication (Component_Definition (N))) then
1930          declare
1931             Sindic : constant Node_Id :=
1932                        Subtype_Indication (Component_Definition (N));
1933          begin
1934             if Nkind (Sindic) = N_Subtype_Indication
1935               and then Present (Constraint (Sindic))
1936               and then Contains_POC (Constraint (Sindic))
1937             then
1938                Set_Has_Per_Object_Constraint (Id);
1939             end if;
1940          end;
1941       end if;
1942
1943       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1944       --  out some static checks.
1945
1946       if Ada_Version >= Ada_2005
1947         and then Can_Never_Be_Null (T)
1948       then
1949          Null_Exclusion_Static_Checks (N);
1950       end if;
1951
1952       --  If this component is private (or depends on a private type), flag the
1953       --  record type to indicate that some operations are not available.
1954
1955       P := Private_Component (T);
1956
1957       if Present (P) then
1958
1959          --  Check for circular definitions
1960
1961          if P = Any_Type then
1962             Set_Etype (Id, Any_Type);
1963
1964          --  There is a gap in the visibility of operations only if the
1965          --  component type is not defined in the scope of the record type.
1966
1967          elsif Scope (P) = Scope (Current_Scope) then
1968             null;
1969
1970          elsif Is_Limited_Type (P) then
1971             Set_Is_Limited_Composite (Current_Scope);
1972
1973          else
1974             Set_Is_Private_Composite (Current_Scope);
1975          end if;
1976       end if;
1977
1978       if P /= Any_Type
1979         and then Is_Limited_Type (T)
1980         and then Chars (Id) /= Name_uParent
1981         and then Is_Tagged_Type (Current_Scope)
1982       then
1983          if Is_Derived_Type (Current_Scope)
1984            and then not Is_Known_Limited (Current_Scope)
1985          then
1986             Error_Msg_N
1987               ("extension of nonlimited type cannot have limited components",
1988                N);
1989
1990             if Is_Interface (Root_Type (Current_Scope)) then
1991                Error_Msg_N
1992                  ("\limitedness is not inherited from limited interface", N);
1993                Error_Msg_N ("\add LIMITED to type indication", N);
1994             end if;
1995
1996             Explain_Limited_Type (T, N);
1997             Set_Etype (Id, Any_Type);
1998             Set_Is_Limited_Composite (Current_Scope, False);
1999
2000          elsif not Is_Derived_Type (Current_Scope)
2001            and then not Is_Limited_Record (Current_Scope)
2002            and then not Is_Concurrent_Type (Current_Scope)
2003          then
2004             Error_Msg_N
2005               ("nonlimited tagged type cannot have limited components", N);
2006             Explain_Limited_Type (T, N);
2007             Set_Etype (Id, Any_Type);
2008             Set_Is_Limited_Composite (Current_Scope, False);
2009          end if;
2010       end if;
2011
2012       Set_Original_Record_Component (Id, Id);
2013
2014       if Has_Aspects (N) then
2015          Analyze_Aspect_Specifications (N, Id);
2016       end if;
2017    end Analyze_Component_Declaration;
2018
2019    --------------------------
2020    -- Analyze_Declarations --
2021    --------------------------
2022
2023    procedure Analyze_Declarations (L : List_Id) is
2024       D           : Node_Id;
2025       Freeze_From : Entity_Id := Empty;
2026       Next_Node   : Node_Id;
2027
2028       procedure Adjust_D;
2029       --  Adjust D not to include implicit label declarations, since these
2030       --  have strange Sloc values that result in elaboration check problems.
2031       --  (They have the sloc of the label as found in the source, and that
2032       --  is ahead of the current declarative part).
2033
2034       --------------
2035       -- Adjust_D --
2036       --------------
2037
2038       procedure Adjust_D is
2039       begin
2040          while Present (Prev (D))
2041            and then Nkind (D) = N_Implicit_Label_Declaration
2042          loop
2043             Prev (D);
2044          end loop;
2045       end Adjust_D;
2046
2047    --  Start of processing for Analyze_Declarations
2048
2049    begin
2050       if Restriction_Check_Required (SPARK) then
2051          Check_Later_Vs_Basic_Declarations (L, During_Parsing => False);
2052       end if;
2053
2054       D := First (L);
2055       while Present (D) loop
2056
2057          --  Package spec cannot contain a package declaration in SPARK
2058
2059          if Nkind (D) = N_Package_Declaration
2060            and then Nkind (Parent (L)) = N_Package_Specification
2061          then
2062             Check_SPARK_Restriction
2063               ("package specification cannot contain a package declaration",
2064                D);
2065          end if;
2066
2067          --  Complete analysis of declaration
2068
2069          Analyze (D);
2070          Next_Node := Next (D);
2071
2072          if No (Freeze_From) then
2073             Freeze_From := First_Entity (Current_Scope);
2074          end if;
2075
2076          --  At the end of a declarative part, freeze remaining entities
2077          --  declared in it. The end of the visible declarations of package
2078          --  specification is not the end of a declarative part if private
2079          --  declarations are present. The end of a package declaration is a
2080          --  freezing point only if it a library package. A task definition or
2081          --  protected type definition is not a freeze point either. Finally,
2082          --  we do not freeze entities in generic scopes, because there is no
2083          --  code generated for them and freeze nodes will be generated for
2084          --  the instance.
2085
2086          --  The end of a package instantiation is not a freeze point, but
2087          --  for now we make it one, because the generic body is inserted
2088          --  (currently) immediately after. Generic instantiations will not
2089          --  be a freeze point once delayed freezing of bodies is implemented.
2090          --  (This is needed in any case for early instantiations ???).
2091
2092          if No (Next_Node) then
2093             if Nkind_In (Parent (L), N_Component_List,
2094                                      N_Task_Definition,
2095                                      N_Protected_Definition)
2096             then
2097                null;
2098
2099             elsif Nkind (Parent (L)) /= N_Package_Specification then
2100                if Nkind (Parent (L)) = N_Package_Body then
2101                   Freeze_From := First_Entity (Current_Scope);
2102                end if;
2103
2104                Adjust_D;
2105                Freeze_All (Freeze_From, D);
2106                Freeze_From := Last_Entity (Current_Scope);
2107
2108             elsif Scope (Current_Scope) /= Standard_Standard
2109               and then not Is_Child_Unit (Current_Scope)
2110               and then No (Generic_Parent (Parent (L)))
2111             then
2112                null;
2113
2114             elsif L /= Visible_Declarations (Parent (L))
2115                or else No (Private_Declarations (Parent (L)))
2116                or else Is_Empty_List (Private_Declarations (Parent (L)))
2117             then
2118                Adjust_D;
2119                Freeze_All (Freeze_From, D);
2120                Freeze_From := Last_Entity (Current_Scope);
2121             end if;
2122
2123          --  If next node is a body then freeze all types before the body.
2124          --  An exception occurs for some expander-generated bodies. If these
2125          --  are generated at places where in general language rules would not
2126          --  allow a freeze point, then we assume that the expander has
2127          --  explicitly checked that all required types are properly frozen,
2128          --  and we do not cause general freezing here. This special circuit
2129          --  is used when the encountered body is marked as having already
2130          --  been analyzed.
2131
2132          --  In all other cases (bodies that come from source, and expander
2133          --  generated bodies that have not been analyzed yet), freeze all
2134          --  types now. Note that in the latter case, the expander must take
2135          --  care to attach the bodies at a proper place in the tree so as to
2136          --  not cause unwanted freezing at that point.
2137
2138          elsif not Analyzed (Next_Node)
2139            and then (Nkind_In (Next_Node, N_Subprogram_Body,
2140                                           N_Entry_Body,
2141                                           N_Package_Body,
2142                                           N_Protected_Body,
2143                                           N_Task_Body)
2144                        or else
2145                      Nkind (Next_Node) in N_Body_Stub)
2146          then
2147             Adjust_D;
2148             Freeze_All (Freeze_From, D);
2149             Freeze_From := Last_Entity (Current_Scope);
2150          end if;
2151
2152          D := Next_Node;
2153       end loop;
2154
2155       --  One more thing to do, we need to scan the declarations to check
2156       --  for any precondition/postcondition pragmas (Pre/Post aspects have
2157       --  by this stage been converted into corresponding pragmas). It is
2158       --  at this point that we analyze the expressions in such pragmas,
2159       --  to implement the delayed visibility requirement.
2160
2161       declare
2162          Decl : Node_Id;
2163          Spec : Node_Id;
2164          Sent : Entity_Id;
2165          Prag : Node_Id;
2166
2167       begin
2168          Decl := First (L);
2169          while Present (Decl) loop
2170             if Nkind (Original_Node (Decl)) = N_Subprogram_Declaration then
2171                Spec := Specification (Original_Node (Decl));
2172                Sent := Defining_Unit_Name (Spec);
2173
2174                Prag := Spec_PPC_List (Contract (Sent));
2175                while Present (Prag) loop
2176                   Analyze_PPC_In_Decl_Part (Prag, Sent);
2177                   Prag := Next_Pragma (Prag);
2178                end loop;
2179
2180                Check_Subprogram_Contract (Sent);
2181
2182                Prag := Spec_TC_List (Contract (Sent));
2183                while Present (Prag) loop
2184                   Analyze_TC_In_Decl_Part (Prag, Sent);
2185                   Prag := Next_Pragma (Prag);
2186                end loop;
2187             end if;
2188
2189             Next (Decl);
2190          end loop;
2191       end;
2192    end Analyze_Declarations;
2193
2194    -----------------------------------
2195    -- Analyze_Full_Type_Declaration --
2196    -----------------------------------
2197
2198    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2199       Def    : constant Node_Id   := Type_Definition (N);
2200       Def_Id : constant Entity_Id := Defining_Identifier (N);
2201       T      : Entity_Id;
2202       Prev   : Entity_Id;
2203
2204       Is_Remote : constant Boolean :=
2205                     (Is_Remote_Types (Current_Scope)
2206                        or else Is_Remote_Call_Interface (Current_Scope))
2207                     and then not (In_Private_Part (Current_Scope)
2208                                     or else In_Package_Body (Current_Scope));
2209
2210       procedure Check_Ops_From_Incomplete_Type;
2211       --  If there is a tagged incomplete partial view of the type, traverse
2212       --  the primitives of the incomplete view and change the type of any
2213       --  controlling formals and result to indicate the full view. The
2214       --  primitives will be added to the full type's primitive operations
2215       --  list later in Sem_Disp.Check_Operation_From_Incomplete_Type (which
2216       --  is called from Process_Incomplete_Dependents).
2217
2218       ------------------------------------
2219       -- Check_Ops_From_Incomplete_Type --
2220       ------------------------------------
2221
2222       procedure Check_Ops_From_Incomplete_Type is
2223          Elmt   : Elmt_Id;
2224          Formal : Entity_Id;
2225          Op     : Entity_Id;
2226
2227       begin
2228          if Prev /= T
2229            and then Ekind (Prev) = E_Incomplete_Type
2230            and then Is_Tagged_Type (Prev)
2231            and then Is_Tagged_Type (T)
2232          then
2233             Elmt := First_Elmt (Primitive_Operations (Prev));
2234             while Present (Elmt) loop
2235                Op := Node (Elmt);
2236
2237                Formal := First_Formal (Op);
2238                while Present (Formal) loop
2239                   if Etype (Formal) = Prev then
2240                      Set_Etype (Formal, T);
2241                   end if;
2242
2243                   Next_Formal (Formal);
2244                end loop;
2245
2246                if Etype (Op) = Prev then
2247                   Set_Etype (Op, T);
2248                end if;
2249
2250                Next_Elmt (Elmt);
2251             end loop;
2252          end if;
2253       end Check_Ops_From_Incomplete_Type;
2254
2255    --  Start of processing for Analyze_Full_Type_Declaration
2256
2257    begin
2258       Prev := Find_Type_Name (N);
2259
2260       --  The full view, if present, now points to the current type
2261
2262       --  Ada 2005 (AI-50217): If the type was previously decorated when
2263       --  imported through a LIMITED WITH clause, it appears as incomplete
2264       --  but has no full view.
2265
2266       if Ekind (Prev) = E_Incomplete_Type
2267         and then Present (Full_View (Prev))
2268       then
2269          T := Full_View (Prev);
2270       else
2271          T := Prev;
2272       end if;
2273
2274       Set_Is_Pure (T, Is_Pure (Current_Scope));
2275
2276       --  We set the flag Is_First_Subtype here. It is needed to set the
2277       --  corresponding flag for the Implicit class-wide-type created
2278       --  during tagged types processing.
2279
2280       Set_Is_First_Subtype (T, True);
2281
2282       --  Only composite types other than array types are allowed to have
2283       --  discriminants.
2284
2285       case Nkind (Def) is
2286
2287          --  For derived types, the rule will be checked once we've figured
2288          --  out the parent type.
2289
2290          when N_Derived_Type_Definition =>
2291             null;
2292
2293          --  For record types, discriminants are allowed, unless we are in
2294          --  SPARK.
2295
2296          when N_Record_Definition =>
2297             if Present (Discriminant_Specifications (N)) then
2298                Check_SPARK_Restriction
2299                  ("discriminant type is not allowed",
2300                   Defining_Identifier
2301                     (First (Discriminant_Specifications (N))));
2302             end if;
2303
2304          when others =>
2305             if Present (Discriminant_Specifications (N)) then
2306                Error_Msg_N
2307                  ("elementary or array type cannot have discriminants",
2308                   Defining_Identifier
2309                     (First (Discriminant_Specifications (N))));
2310             end if;
2311       end case;
2312
2313       --  Elaborate the type definition according to kind, and generate
2314       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2315       --  already done (this happens during the reanalysis that follows a call
2316       --  to the high level optimizer).
2317
2318       if not Analyzed (T) then
2319          Set_Analyzed (T);
2320
2321          case Nkind (Def) is
2322
2323             when N_Access_To_Subprogram_Definition =>
2324                Access_Subprogram_Declaration (T, Def);
2325
2326                --  If this is a remote access to subprogram, we must create the
2327                --  equivalent fat pointer type, and related subprograms.
2328
2329                if Is_Remote then
2330                   Process_Remote_AST_Declaration (N);
2331                end if;
2332
2333                --  Validate categorization rule against access type declaration
2334                --  usually a violation in Pure unit, Shared_Passive unit.
2335
2336                Validate_Access_Type_Declaration (T, N);
2337
2338             when N_Access_To_Object_Definition =>
2339                Access_Type_Declaration (T, Def);
2340
2341                --  Validate categorization rule against access type declaration
2342                --  usually a violation in Pure unit, Shared_Passive unit.
2343
2344                Validate_Access_Type_Declaration (T, N);
2345
2346                --  If we are in a Remote_Call_Interface package and define a
2347                --  RACW, then calling stubs and specific stream attributes
2348                --  must be added.
2349
2350                if Is_Remote
2351                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2352                then
2353                   Add_RACW_Features (Def_Id);
2354                end if;
2355
2356                --  Set no strict aliasing flag if config pragma seen
2357
2358                if Opt.No_Strict_Aliasing then
2359                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
2360                end if;
2361
2362             when N_Array_Type_Definition =>
2363                Array_Type_Declaration (T, Def);
2364
2365             when N_Derived_Type_Definition =>
2366                Derived_Type_Declaration (T, N, T /= Def_Id);
2367
2368             when N_Enumeration_Type_Definition =>
2369                Enumeration_Type_Declaration (T, Def);
2370
2371             when N_Floating_Point_Definition =>
2372                Floating_Point_Type_Declaration (T, Def);
2373
2374             when N_Decimal_Fixed_Point_Definition =>
2375                Decimal_Fixed_Point_Type_Declaration (T, Def);
2376
2377             when N_Ordinary_Fixed_Point_Definition =>
2378                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2379
2380             when N_Signed_Integer_Type_Definition =>
2381                Signed_Integer_Type_Declaration (T, Def);
2382
2383             when N_Modular_Type_Definition =>
2384                Modular_Type_Declaration (T, Def);
2385
2386             when N_Record_Definition =>
2387                Record_Type_Declaration (T, N, Prev);
2388
2389             --  If declaration has a parse error, nothing to elaborate.
2390
2391             when N_Error =>
2392                null;
2393
2394             when others =>
2395                raise Program_Error;
2396
2397          end case;
2398       end if;
2399
2400       if Etype (T) = Any_Type then
2401          return;
2402       end if;
2403
2404       --  Controlled type is not allowed in SPARK
2405
2406       if Is_Visibly_Controlled (T) then
2407          Check_SPARK_Restriction ("controlled type is not allowed", N);
2408       end if;
2409
2410       --  Some common processing for all types
2411
2412       Set_Depends_On_Private (T, Has_Private_Component (T));
2413       Check_Ops_From_Incomplete_Type;
2414
2415       --  Both the declared entity, and its anonymous base type if one
2416       --  was created, need freeze nodes allocated.
2417
2418       declare
2419          B : constant Entity_Id := Base_Type (T);
2420
2421       begin
2422          --  In the case where the base type differs from the first subtype, we
2423          --  pre-allocate a freeze node, and set the proper link to the first
2424          --  subtype. Freeze_Entity will use this preallocated freeze node when
2425          --  it freezes the entity.
2426
2427          --  This does not apply if the base type is a generic type, whose
2428          --  declaration is independent of the current derived definition.
2429
2430          if B /= T and then not Is_Generic_Type (B) then
2431             Ensure_Freeze_Node (B);
2432             Set_First_Subtype_Link (Freeze_Node (B), T);
2433          end if;
2434
2435          --  A type that is imported through a limited_with clause cannot
2436          --  generate any code, and thus need not be frozen. However, an access
2437          --  type with an imported designated type needs a finalization list,
2438          --  which may be referenced in some other package that has non-limited
2439          --  visibility on the designated type. Thus we must create the
2440          --  finalization list at the point the access type is frozen, to
2441          --  prevent unsatisfied references at link time.
2442
2443          if not From_With_Type (T) or else Is_Access_Type (T) then
2444             Set_Has_Delayed_Freeze (T);
2445          end if;
2446       end;
2447
2448       --  Case where T is the full declaration of some private type which has
2449       --  been swapped in Defining_Identifier (N).
2450
2451       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2452          Process_Full_View (N, T, Def_Id);
2453
2454          --  Record the reference. The form of this is a little strange, since
2455          --  the full declaration has been swapped in. So the first parameter
2456          --  here represents the entity to which a reference is made which is
2457          --  the "real" entity, i.e. the one swapped in, and the second
2458          --  parameter provides the reference location.
2459
2460          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2461          --  since we don't want a complaint about the full type being an
2462          --  unwanted reference to the private type
2463
2464          declare
2465             B : constant Boolean := Has_Pragma_Unreferenced (T);
2466          begin
2467             Set_Has_Pragma_Unreferenced (T, False);
2468             Generate_Reference (T, T, 'c');
2469             Set_Has_Pragma_Unreferenced (T, B);
2470          end;
2471
2472          Set_Completion_Referenced (Def_Id);
2473
2474       --  For completion of incomplete type, process incomplete dependents
2475       --  and always mark the full type as referenced (it is the incomplete
2476       --  type that we get for any real reference).
2477
2478       elsif Ekind (Prev) = E_Incomplete_Type then
2479          Process_Incomplete_Dependents (N, T, Prev);
2480          Generate_Reference (Prev, Def_Id, 'c');
2481          Set_Completion_Referenced (Def_Id);
2482
2483       --  If not private type or incomplete type completion, this is a real
2484       --  definition of a new entity, so record it.
2485
2486       else
2487          Generate_Definition (Def_Id);
2488       end if;
2489
2490       if Chars (Scope (Def_Id)) = Name_System
2491         and then Chars (Def_Id) = Name_Address
2492         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2493       then
2494          Set_Is_Descendent_Of_Address (Def_Id);
2495          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2496          Set_Is_Descendent_Of_Address (Prev);
2497       end if;
2498
2499       Set_Optimize_Alignment_Flags (Def_Id);
2500       Check_Eliminated (Def_Id);
2501
2502       --  If the declaration is a completion and aspects are present, apply
2503       --  them to the entity for the type which is currently the partial
2504       --  view, but which is the one that will be frozen.
2505
2506       if Has_Aspects (N) then
2507          if Prev /= Def_Id then
2508             Analyze_Aspect_Specifications (N, Prev);
2509          else
2510             Analyze_Aspect_Specifications (N, Def_Id);
2511          end if;
2512       end if;
2513    end Analyze_Full_Type_Declaration;
2514
2515    ----------------------------------
2516    -- Analyze_Incomplete_Type_Decl --
2517    ----------------------------------
2518
2519    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2520       F : constant Boolean := Is_Pure (Current_Scope);
2521       T : Entity_Id;
2522
2523    begin
2524       Check_SPARK_Restriction ("incomplete type is not allowed", N);
2525
2526       Generate_Definition (Defining_Identifier (N));
2527
2528       --  Process an incomplete declaration. The identifier must not have been
2529       --  declared already in the scope. However, an incomplete declaration may
2530       --  appear in the private part of a package, for a private type that has
2531       --  already been declared.
2532
2533       --  In this case, the discriminants (if any) must match
2534
2535       T := Find_Type_Name (N);
2536
2537       Set_Ekind (T, E_Incomplete_Type);
2538       Init_Size_Align (T);
2539       Set_Is_First_Subtype (T, True);
2540       Set_Etype (T, T);
2541
2542       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2543       --  incomplete types.
2544
2545       if Tagged_Present (N) then
2546          Set_Is_Tagged_Type (T);
2547          Make_Class_Wide_Type (T);
2548          Set_Direct_Primitive_Operations (T, New_Elmt_List);
2549       end if;
2550
2551       Push_Scope (T);
2552
2553       Set_Stored_Constraint (T, No_Elist);
2554
2555       if Present (Discriminant_Specifications (N)) then
2556          Process_Discriminants (N);
2557       end if;
2558
2559       End_Scope;
2560
2561       --  If the type has discriminants, non-trivial subtypes may be
2562       --  declared before the full view of the type. The full views of those
2563       --  subtypes will be built after the full view of the type.
2564
2565       Set_Private_Dependents (T, New_Elmt_List);
2566       Set_Is_Pure            (T, F);
2567    end Analyze_Incomplete_Type_Decl;
2568
2569    -----------------------------------
2570    -- Analyze_Interface_Declaration --
2571    -----------------------------------
2572
2573    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2574       CW : constant Entity_Id := Class_Wide_Type (T);
2575
2576    begin
2577       Set_Is_Tagged_Type (T);
2578
2579       Set_Is_Limited_Record (T, Limited_Present (Def)
2580                                   or else Task_Present (Def)
2581                                   or else Protected_Present (Def)
2582                                   or else Synchronized_Present (Def));
2583
2584       --  Type is abstract if full declaration carries keyword, or if previous
2585       --  partial view did.
2586
2587       Set_Is_Abstract_Type (T);
2588       Set_Is_Interface (T);
2589
2590       --  Type is a limited interface if it includes the keyword limited, task,
2591       --  protected, or synchronized.
2592
2593       Set_Is_Limited_Interface
2594         (T, Limited_Present (Def)
2595               or else Protected_Present (Def)
2596               or else Synchronized_Present (Def)
2597               or else Task_Present (Def));
2598
2599       Set_Interfaces (T, New_Elmt_List);
2600       Set_Direct_Primitive_Operations (T, New_Elmt_List);
2601
2602       --  Complete the decoration of the class-wide entity if it was already
2603       --  built (i.e. during the creation of the limited view)
2604
2605       if Present (CW) then
2606          Set_Is_Interface (CW);
2607          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2608       end if;
2609
2610       --  Check runtime support for synchronized interfaces
2611
2612       if VM_Target = No_VM
2613         and then (Is_Task_Interface (T)
2614                     or else Is_Protected_Interface (T)
2615                     or else Is_Synchronized_Interface (T))
2616         and then not RTE_Available (RE_Select_Specific_Data)
2617       then
2618          Error_Msg_CRT ("synchronized interfaces", T);
2619       end if;
2620    end Analyze_Interface_Declaration;
2621
2622    -----------------------------
2623    -- Analyze_Itype_Reference --
2624    -----------------------------
2625
2626    --  Nothing to do. This node is placed in the tree only for the benefit of
2627    --  back end processing, and has no effect on the semantic processing.
2628
2629    procedure Analyze_Itype_Reference (N : Node_Id) is
2630    begin
2631       pragma Assert (Is_Itype (Itype (N)));
2632       null;
2633    end Analyze_Itype_Reference;
2634
2635    --------------------------------
2636    -- Analyze_Number_Declaration --
2637    --------------------------------
2638
2639    procedure Analyze_Number_Declaration (N : Node_Id) is
2640       Id    : constant Entity_Id := Defining_Identifier (N);
2641       E     : constant Node_Id   := Expression (N);
2642       T     : Entity_Id;
2643       Index : Interp_Index;
2644       It    : Interp;
2645
2646    begin
2647       Generate_Definition (Id);
2648       Enter_Name (Id);
2649
2650       --  This is an optimization of a common case of an integer literal
2651
2652       if Nkind (E) = N_Integer_Literal then
2653          Set_Is_Static_Expression (E, True);
2654          Set_Etype                (E, Universal_Integer);
2655
2656          Set_Etype     (Id, Universal_Integer);
2657          Set_Ekind     (Id, E_Named_Integer);
2658          Set_Is_Frozen (Id, True);
2659          return;
2660       end if;
2661
2662       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2663
2664       --  Process expression, replacing error by integer zero, to avoid
2665       --  cascaded errors or aborts further along in the processing
2666
2667       --  Replace Error by integer zero, which seems least likely to
2668       --  cause cascaded errors.
2669
2670       if E = Error then
2671          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2672          Set_Error_Posted (E);
2673       end if;
2674
2675       Analyze (E);
2676
2677       --  Verify that the expression is static and numeric. If
2678       --  the expression is overloaded, we apply the preference
2679       --  rule that favors root numeric types.
2680
2681       if not Is_Overloaded (E) then
2682          T := Etype (E);
2683
2684       else
2685          T := Any_Type;
2686
2687          Get_First_Interp (E, Index, It);
2688          while Present (It.Typ) loop
2689             if (Is_Integer_Type (It.Typ)
2690                  or else Is_Real_Type (It.Typ))
2691               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2692             then
2693                if T = Any_Type then
2694                   T := It.Typ;
2695
2696                elsif It.Typ = Universal_Real
2697                  or else It.Typ = Universal_Integer
2698                then
2699                   --  Choose universal interpretation over any other
2700
2701                   T := It.Typ;
2702                   exit;
2703                end if;
2704             end if;
2705
2706             Get_Next_Interp (Index, It);
2707          end loop;
2708       end if;
2709
2710       if Is_Integer_Type (T)  then
2711          Resolve (E, T);
2712          Set_Etype (Id, Universal_Integer);
2713          Set_Ekind (Id, E_Named_Integer);
2714
2715       elsif Is_Real_Type (T) then
2716
2717          --  Because the real value is converted to universal_real, this is a
2718          --  legal context for a universal fixed expression.
2719
2720          if T = Universal_Fixed then
2721             declare
2722                Loc  : constant Source_Ptr := Sloc (N);
2723                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2724                         Subtype_Mark =>
2725                           New_Occurrence_Of (Universal_Real, Loc),
2726                         Expression => Relocate_Node (E));
2727
2728             begin
2729                Rewrite (E, Conv);
2730                Analyze (E);
2731             end;
2732
2733          elsif T = Any_Fixed then
2734             Error_Msg_N ("illegal context for mixed mode operation", E);
2735
2736             --  Expression is of the form : universal_fixed * integer. Try to
2737             --  resolve as universal_real.
2738
2739             T := Universal_Real;
2740             Set_Etype (E, T);
2741          end if;
2742
2743          Resolve (E, T);
2744          Set_Etype (Id, Universal_Real);
2745          Set_Ekind (Id, E_Named_Real);
2746
2747       else
2748          Wrong_Type (E, Any_Numeric);
2749          Resolve (E, T);
2750
2751          Set_Etype               (Id, T);
2752          Set_Ekind               (Id, E_Constant);
2753          Set_Never_Set_In_Source (Id, True);
2754          Set_Is_True_Constant    (Id, True);
2755          return;
2756       end if;
2757
2758       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2759          Set_Etype (E, Etype (Id));
2760       end if;
2761
2762       if not Is_OK_Static_Expression (E) then
2763          Flag_Non_Static_Expr
2764            ("non-static expression used in number declaration!", E);
2765          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2766          Set_Etype (E, Any_Type);
2767       end if;
2768    end Analyze_Number_Declaration;
2769
2770    --------------------------------
2771    -- Analyze_Object_Declaration --
2772    --------------------------------
2773
2774    procedure Analyze_Object_Declaration (N : Node_Id) is
2775       Loc   : constant Source_Ptr := Sloc (N);
2776       Id    : constant Entity_Id  := Defining_Identifier (N);
2777       T     : Entity_Id;
2778       Act_T : Entity_Id;
2779
2780       E : Node_Id := Expression (N);
2781       --  E is set to Expression (N) throughout this routine. When
2782       --  Expression (N) is modified, E is changed accordingly.
2783
2784       Prev_Entity : Entity_Id := Empty;
2785
2786       function Count_Tasks (T : Entity_Id) return Uint;
2787       --  This function is called when a non-generic library level object of a
2788       --  task type is declared. Its function is to count the static number of
2789       --  tasks declared within the type (it is only called if Has_Tasks is set
2790       --  for T). As a side effect, if an array of tasks with non-static bounds
2791       --  or a variant record type is encountered, Check_Restrictions is called
2792       --  indicating the count is unknown.
2793
2794       -----------------
2795       -- Count_Tasks --
2796       -----------------
2797
2798       function Count_Tasks (T : Entity_Id) return Uint is
2799          C : Entity_Id;
2800          X : Node_Id;
2801          V : Uint;
2802
2803       begin
2804          if Is_Task_Type (T) then
2805             return Uint_1;
2806
2807          elsif Is_Record_Type (T) then
2808             if Has_Discriminants (T) then
2809                Check_Restriction (Max_Tasks, N);
2810                return Uint_0;
2811
2812             else
2813                V := Uint_0;
2814                C := First_Component (T);
2815                while Present (C) loop
2816                   V := V + Count_Tasks (Etype (C));
2817                   Next_Component (C);
2818                end loop;
2819
2820                return V;
2821             end if;
2822
2823          elsif Is_Array_Type (T) then
2824             X := First_Index (T);
2825             V := Count_Tasks (Component_Type (T));
2826             while Present (X) loop
2827                C := Etype (X);
2828
2829                if not Is_Static_Subtype (C) then
2830                   Check_Restriction (Max_Tasks, N);
2831                   return Uint_0;
2832                else
2833                   V := V * (UI_Max (Uint_0,
2834                                     Expr_Value (Type_High_Bound (C)) -
2835                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2836                end if;
2837
2838                Next_Index (X);
2839             end loop;
2840
2841             return V;
2842
2843          else
2844             return Uint_0;
2845          end if;
2846       end Count_Tasks;
2847
2848    --  Start of processing for Analyze_Object_Declaration
2849
2850    begin
2851       --  There are three kinds of implicit types generated by an
2852       --  object declaration:
2853
2854       --   1. Those generated by the original Object Definition
2855
2856       --   2. Those generated by the Expression
2857
2858       --   3. Those used to constrain the Object Definition with the
2859       --      expression constraints when the definition is unconstrained.
2860
2861       --  They must be generated in this order to avoid order of elaboration
2862       --  issues. Thus the first step (after entering the name) is to analyze
2863       --  the object definition.
2864
2865       if Constant_Present (N) then
2866          Prev_Entity := Current_Entity_In_Scope (Id);
2867
2868          if Present (Prev_Entity)
2869            and then
2870
2871              --  If the homograph is an implicit subprogram, it is overridden
2872              --  by the current declaration.
2873
2874              ((Is_Overloadable (Prev_Entity)
2875                 and then Is_Inherited_Operation (Prev_Entity))
2876
2877                --  The current object is a discriminal generated for an entry
2878                --  family index. Even though the index is a constant, in this
2879                --  particular context there is no true constant redeclaration.
2880                --  Enter_Name will handle the visibility.
2881
2882                or else
2883                 (Is_Discriminal (Id)
2884                    and then Ekind (Discriminal_Link (Id)) =
2885                               E_Entry_Index_Parameter)
2886
2887                --  The current object is the renaming for a generic declared
2888                --  within the instance.
2889
2890                or else
2891                 (Ekind (Prev_Entity) = E_Package
2892                   and then Nkind (Parent (Prev_Entity)) =
2893                                          N_Package_Renaming_Declaration
2894                   and then not Comes_From_Source (Prev_Entity)
2895                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
2896          then
2897             Prev_Entity := Empty;
2898          end if;
2899       end if;
2900
2901       if Present (Prev_Entity) then
2902          Constant_Redeclaration (Id, N, T);
2903
2904          Generate_Reference (Prev_Entity, Id, 'c');
2905          Set_Completion_Referenced (Id);
2906
2907          if Error_Posted (N) then
2908
2909             --  Type mismatch or illegal redeclaration, Do not analyze
2910             --  expression to avoid cascaded errors.
2911
2912             T := Find_Type_Of_Object (Object_Definition (N), N);
2913             Set_Etype (Id, T);
2914             Set_Ekind (Id, E_Variable);
2915             goto Leave;
2916          end if;
2917
2918       --  In the normal case, enter identifier at the start to catch premature
2919       --  usage in the initialization expression.
2920
2921       else
2922          Generate_Definition (Id);
2923          Enter_Name (Id);
2924
2925          Mark_Coextensions (N, Object_Definition (N));
2926
2927          T := Find_Type_Of_Object (Object_Definition (N), N);
2928
2929          if Nkind (Object_Definition (N)) = N_Access_Definition
2930            and then Present
2931              (Access_To_Subprogram_Definition (Object_Definition (N)))
2932            and then Protected_Present
2933              (Access_To_Subprogram_Definition (Object_Definition (N)))
2934          then
2935             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2936          end if;
2937
2938          if Error_Posted (Id) then
2939             Set_Etype (Id, T);
2940             Set_Ekind (Id, E_Variable);
2941             goto Leave;
2942          end if;
2943       end if;
2944
2945       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2946       --  out some static checks
2947
2948       if Ada_Version >= Ada_2005
2949         and then Can_Never_Be_Null (T)
2950       then
2951          --  In case of aggregates we must also take care of the correct
2952          --  initialization of nested aggregates bug this is done at the
2953          --  point of the analysis of the aggregate (see sem_aggr.adb)
2954
2955          if Present (Expression (N))
2956            and then Nkind (Expression (N)) = N_Aggregate
2957          then
2958             null;
2959
2960          else
2961             declare
2962                Save_Typ : constant Entity_Id := Etype (Id);
2963             begin
2964                Set_Etype (Id, T); --  Temp. decoration for static checks
2965                Null_Exclusion_Static_Checks (N);
2966                Set_Etype (Id, Save_Typ);
2967             end;
2968          end if;
2969       end if;
2970
2971       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2972
2973       --  If deferred constant, make sure context is appropriate. We detect
2974       --  a deferred constant as a constant declaration with no expression.
2975       --  A deferred constant can appear in a package body if its completion
2976       --  is by means of an interface pragma.
2977
2978       if Constant_Present (N)
2979         and then No (E)
2980       then
2981          --  A deferred constant may appear in the declarative part of the
2982          --  following constructs:
2983
2984          --     blocks
2985          --     entry bodies
2986          --     extended return statements
2987          --     package specs
2988          --     package bodies
2989          --     subprogram bodies
2990          --     task bodies
2991
2992          --  When declared inside a package spec, a deferred constant must be
2993          --  completed by a full constant declaration or pragma Import. In all
2994          --  other cases, the only proper completion is pragma Import. Extended
2995          --  return statements are flagged as invalid contexts because they do
2996          --  not have a declarative part and so cannot accommodate the pragma.
2997
2998          if Ekind (Current_Scope) = E_Return_Statement then
2999             Error_Msg_N
3000               ("invalid context for deferred constant declaration (RM 7.4)",
3001                N);
3002             Error_Msg_N
3003               ("\declaration requires an initialization expression",
3004                 N);
3005             Set_Constant_Present (N, False);
3006
3007          --  In Ada 83, deferred constant must be of private type
3008
3009          elsif not Is_Private_Type (T) then
3010             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
3011                Error_Msg_N
3012                  ("(Ada 83) deferred constant must be private type", N);
3013             end if;
3014          end if;
3015
3016       --  If not a deferred constant, then object declaration freezes its type
3017
3018       else
3019          Check_Fully_Declared (T, N);
3020          Freeze_Before (N, T);
3021       end if;
3022
3023       --  If the object was created by a constrained array definition, then
3024       --  set the link in both the anonymous base type and anonymous subtype
3025       --  that are built to represent the array type to point to the object.
3026
3027       if Nkind (Object_Definition (Declaration_Node (Id))) =
3028                         N_Constrained_Array_Definition
3029       then
3030          Set_Related_Array_Object (T, Id);
3031          Set_Related_Array_Object (Base_Type (T), Id);
3032       end if;
3033
3034       --  Special checks for protected objects not at library level
3035
3036       if Is_Protected_Type (T)
3037         and then not Is_Library_Level_Entity (Id)
3038       then
3039          Check_Restriction (No_Local_Protected_Objects, Id);
3040
3041          --  Protected objects with interrupt handlers must be at library level
3042
3043          --  Ada 2005: this test is not needed (and the corresponding clause
3044          --  in the RM is removed) because accessibility checks are sufficient
3045          --  to make handlers not at the library level illegal.
3046
3047          if Has_Interrupt_Handler (T)
3048            and then Ada_Version < Ada_2005
3049          then
3050             Error_Msg_N
3051               ("interrupt object can only be declared at library level", Id);
3052          end if;
3053       end if;
3054
3055       --  The actual subtype of the object is the nominal subtype, unless
3056       --  the nominal one is unconstrained and obtained from the expression.
3057
3058       Act_T := T;
3059
3060       --  These checks should be performed before the initialization expression
3061       --  is considered, so that the Object_Definition node is still the same
3062       --  as in source code.
3063
3064       --  In SPARK, the nominal subtype shall be given by a subtype mark and
3065       --  shall not be unconstrained. (The only exception to this is the
3066       --  admission of declarations of constants of type String.)
3067
3068       if not
3069         Nkind_In (Object_Definition (N), N_Identifier, N_Expanded_Name)
3070       then
3071          Check_SPARK_Restriction
3072            ("subtype mark required", Object_Definition (N));
3073
3074       elsif Is_Array_Type (T)
3075         and then not Is_Constrained (T)
3076         and then T /= Standard_String
3077       then
3078          Check_SPARK_Restriction
3079            ("subtype mark of constrained type expected",
3080             Object_Definition (N));
3081       end if;
3082
3083       --  There are no aliased objects in SPARK
3084
3085       if Aliased_Present (N) then
3086          Check_SPARK_Restriction ("aliased object is not allowed", N);
3087       end if;
3088
3089       --  Process initialization expression if present and not in error
3090
3091       if Present (E) and then E /= Error then
3092
3093          --  Generate an error in case of CPP class-wide object initialization.
3094          --  Required because otherwise the expansion of the class-wide
3095          --  assignment would try to use 'size to initialize the object
3096          --  (primitive that is not available in CPP tagged types).
3097
3098          if Is_Class_Wide_Type (Act_T)
3099            and then
3100              (Is_CPP_Class (Root_Type (Etype (Act_T)))
3101                or else
3102                  (Present (Full_View (Root_Type (Etype (Act_T))))
3103                    and then
3104                      Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
3105          then
3106             Error_Msg_N
3107               ("predefined assignment not available for 'C'P'P tagged types",
3108                E);
3109          end if;
3110
3111          Mark_Coextensions (N, E);
3112          Analyze (E);
3113
3114          --  In case of errors detected in the analysis of the expression,
3115          --  decorate it with the expected type to avoid cascaded errors
3116
3117          if No (Etype (E)) then
3118             Set_Etype (E, T);
3119          end if;
3120
3121          --  If an initialization expression is present, then we set the
3122          --  Is_True_Constant flag. It will be reset if this is a variable
3123          --  and it is indeed modified.
3124
3125          Set_Is_True_Constant (Id, True);
3126
3127          --  If we are analyzing a constant declaration, set its completion
3128          --  flag after analyzing and resolving the expression.
3129
3130          if Constant_Present (N) then
3131             Set_Has_Completion (Id);
3132          end if;
3133
3134          --  Set type and resolve (type may be overridden later on)
3135
3136          Set_Etype (Id, T);
3137          Resolve (E, T);
3138
3139          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3140          --  node (which was marked already-analyzed), we need to set the type
3141          --  to something other than Any_Access in order to keep gigi happy.
3142
3143          if Etype (E) = Any_Access then
3144             Set_Etype (E, T);
3145          end if;
3146
3147          --  If the object is an access to variable, the initialization
3148          --  expression cannot be an access to constant.
3149
3150          if Is_Access_Type (T)
3151            and then not Is_Access_Constant (T)
3152            and then Is_Access_Type (Etype (E))
3153            and then Is_Access_Constant (Etype (E))
3154          then
3155             Error_Msg_N
3156               ("access to variable cannot be initialized "
3157                & "with an access-to-constant expression", E);
3158          end if;
3159
3160          if not Assignment_OK (N) then
3161             Check_Initialization (T, E);
3162          end if;
3163
3164          Check_Unset_Reference (E);
3165
3166          --  If this is a variable, then set current value. If this is a
3167          --  declared constant of a scalar type with a static expression,
3168          --  indicate that it is always valid.
3169
3170          if not Constant_Present (N) then
3171             if Compile_Time_Known_Value (E) then
3172                Set_Current_Value (Id, E);
3173             end if;
3174
3175          elsif Is_Scalar_Type (T)
3176            and then Is_OK_Static_Expression (E)
3177          then
3178             Set_Is_Known_Valid (Id);
3179          end if;
3180
3181          --  Deal with setting of null flags
3182
3183          if Is_Access_Type (T) then
3184             if Known_Non_Null (E) then
3185                Set_Is_Known_Non_Null (Id, True);
3186             elsif Known_Null (E)
3187               and then not Can_Never_Be_Null (Id)
3188             then
3189                Set_Is_Known_Null (Id, True);
3190             end if;
3191          end if;
3192
3193          --  Check incorrect use of dynamically tagged expressions.
3194
3195          if Is_Tagged_Type (T) then
3196             Check_Dynamically_Tagged_Expression
3197               (Expr        => E,
3198                Typ         => T,
3199                Related_Nod => N);
3200          end if;
3201
3202          Apply_Scalar_Range_Check (E, T);
3203          Apply_Static_Length_Check (E, T);
3204
3205          if Nkind (Original_Node (N)) = N_Object_Declaration
3206            and then Comes_From_Source (Original_Node (N))
3207
3208            --  Only call test if needed
3209
3210            and then Restriction_Check_Required (SPARK)
3211            and then not Is_SPARK_Initialization_Expr (E)
3212          then
3213             Check_SPARK_Restriction
3214               ("initialization expression is not appropriate", E);
3215          end if;
3216       end if;
3217
3218       --  If the No_Streams restriction is set, check that the type of the
3219       --  object is not, and does not contain, any subtype derived from
3220       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3221       --  Has_Stream just for efficiency reasons. There is no point in
3222       --  spending time on a Has_Stream check if the restriction is not set.
3223
3224       if Restriction_Check_Required (No_Streams) then
3225          if Has_Stream (T) then
3226             Check_Restriction (No_Streams, N);
3227          end if;
3228       end if;
3229
3230       --  Deal with predicate check before we start to do major rewriting.
3231       --  it is OK to initialize and then check the initialized value, since
3232       --  the object goes out of scope if we get a predicate failure. Note
3233       --  that we do this in the analyzer and not the expander because the
3234       --  analyzer does some substantial rewriting in some cases.
3235
3236       --  We need a predicate check if the type has predicates, and if either
3237       --  there is an initializing expression, or for default initialization
3238       --  when we have at least one case of an explicit default initial value.
3239
3240       if not Suppress_Assignment_Checks (N)
3241         and then Present (Predicate_Function (T))
3242         and then
3243           (Present (E)
3244             or else
3245               Is_Partially_Initialized_Type (T, Include_Implicit => False))
3246       then
3247          Insert_After (N,
3248            Make_Predicate_Check (T, New_Occurrence_Of (Id, Loc)));
3249       end if;
3250
3251       --  Case of unconstrained type
3252
3253       if Is_Indefinite_Subtype (T) then
3254
3255          --  In SPARK, a declaration of unconstrained type is allowed
3256          --  only for constants of type string.
3257
3258          if Is_String_Type (T) and then not Constant_Present (N) then
3259             Check_SPARK_Restriction
3260               ("declaration of object of unconstrained type not allowed",
3261                N);
3262          end if;
3263
3264          --  Nothing to do in deferred constant case
3265
3266          if Constant_Present (N) and then No (E) then
3267             null;
3268
3269          --  Case of no initialization present
3270
3271          elsif No (E) then
3272             if No_Initialization (N) then
3273                null;
3274
3275             elsif Is_Class_Wide_Type (T) then
3276                Error_Msg_N
3277                  ("initialization required in class-wide declaration ", N);
3278
3279             else
3280                Error_Msg_N
3281                  ("unconstrained subtype not allowed (need initialization)",
3282                   Object_Definition (N));
3283
3284                if Is_Record_Type (T) and then Has_Discriminants (T) then
3285                   Error_Msg_N
3286                     ("\provide initial value or explicit discriminant values",
3287                      Object_Definition (N));
3288
3289                   Error_Msg_NE
3290                     ("\or give default discriminant values for type&",
3291                      Object_Definition (N), T);
3292
3293                elsif Is_Array_Type (T) then
3294                   Error_Msg_N
3295                     ("\provide initial value or explicit array bounds",
3296                      Object_Definition (N));
3297                end if;
3298             end if;
3299
3300          --  Case of initialization present but in error. Set initial
3301          --  expression as absent (but do not make above complaints)
3302
3303          elsif E = Error then
3304             Set_Expression (N, Empty);
3305             E := Empty;
3306
3307          --  Case of initialization present
3308
3309          else
3310             --  Check restrictions in Ada 83
3311
3312             if not Constant_Present (N) then
3313
3314                --  Unconstrained variables not allowed in Ada 83 mode
3315
3316                if Ada_Version = Ada_83
3317                  and then Comes_From_Source (Object_Definition (N))
3318                then
3319                   Error_Msg_N
3320                     ("(Ada 83) unconstrained variable not allowed",
3321                      Object_Definition (N));
3322                end if;
3323             end if;
3324
3325             --  Now we constrain the variable from the initializing expression
3326
3327             --  If the expression is an aggregate, it has been expanded into
3328             --  individual assignments. Retrieve the actual type from the
3329             --  expanded construct.
3330
3331             if Is_Array_Type (T)
3332               and then No_Initialization (N)
3333               and then Nkind (Original_Node (E)) = N_Aggregate
3334             then
3335                Act_T := Etype (E);
3336
3337             --  In case of class-wide interface object declarations we delay
3338             --  the generation of the equivalent record type declarations until
3339             --  its expansion because there are cases in they are not required.
3340
3341             elsif Is_Interface (T) then
3342                null;
3343
3344             else
3345                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3346                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3347             end if;
3348
3349             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3350
3351             if Aliased_Present (N) then
3352                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3353             end if;
3354
3355             Freeze_Before (N, Act_T);
3356             Freeze_Before (N, T);
3357          end if;
3358
3359       elsif Is_Array_Type (T)
3360         and then No_Initialization (N)
3361         and then Nkind (Original_Node (E)) = N_Aggregate
3362       then
3363          if not Is_Entity_Name (Object_Definition (N)) then
3364             Act_T := Etype (E);
3365             Check_Compile_Time_Size (Act_T);
3366
3367             if Aliased_Present (N) then
3368                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3369             end if;
3370          end if;
3371
3372          --  When the given object definition and the aggregate are specified
3373          --  independently, and their lengths might differ do a length check.
3374          --  This cannot happen if the aggregate is of the form (others =>...)
3375
3376          if not Is_Constrained (T) then
3377             null;
3378
3379          elsif Nkind (E) = N_Raise_Constraint_Error then
3380
3381             --  Aggregate is statically illegal. Place back in declaration
3382
3383             Set_Expression (N, E);
3384             Set_No_Initialization (N, False);
3385
3386          elsif T = Etype (E) then
3387             null;
3388
3389          elsif Nkind (E) = N_Aggregate
3390            and then Present (Component_Associations (E))
3391            and then Present (Choices (First (Component_Associations (E))))
3392            and then Nkind (First
3393             (Choices (First (Component_Associations (E))))) = N_Others_Choice
3394          then
3395             null;
3396
3397          else
3398             Apply_Length_Check (E, T);
3399          end if;
3400
3401       --  If the type is limited unconstrained with defaulted discriminants and
3402       --  there is no expression, then the object is constrained by the
3403       --  defaults, so it is worthwhile building the corresponding subtype.
3404
3405       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
3406         and then not Is_Constrained (T)
3407         and then Has_Discriminants (T)
3408       then
3409          if No (E) then
3410             Act_T := Build_Default_Subtype (T, N);
3411          else
3412             --  Ada 2005:  a limited object may be initialized by means of an
3413             --  aggregate. If the type has default discriminants it has an
3414             --  unconstrained nominal type, Its actual subtype will be obtained
3415             --  from the aggregate, and not from the default discriminants.
3416
3417             Act_T := Etype (E);
3418          end if;
3419
3420          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
3421
3422       elsif Present (Underlying_Type (T))
3423         and then not Is_Constrained (Underlying_Type (T))
3424         and then Has_Discriminants (Underlying_Type (T))
3425         and then Nkind (E) = N_Function_Call
3426         and then Constant_Present (N)
3427       then
3428          --  The back-end has problems with constants of a discriminated type
3429          --  with defaults, if the initial value is a function call. We
3430          --  generate an intermediate temporary for the result of the call.
3431          --  It is unclear why this should make it acceptable to gcc. ???
3432
3433          Remove_Side_Effects (E);
3434
3435       --  If this is a constant declaration of an unconstrained type and
3436       --  the initialization is an aggregate, we can use the subtype of the
3437       --  aggregate for the declared entity because it is immutable.
3438
3439       elsif not Is_Constrained (T)
3440         and then Has_Discriminants (T)
3441         and then Constant_Present (N)
3442         and then not Has_Unchecked_Union (T)
3443         and then Nkind (E) = N_Aggregate
3444       then
3445          Act_T := Etype (E);
3446       end if;
3447
3448       --  Check No_Wide_Characters restriction
3449
3450       Check_Wide_Character_Restriction (T, Object_Definition (N));
3451
3452       --  Indicate this is not set in source. Certainly true for constants, and
3453       --  true for variables so far (will be reset for a variable if and when
3454       --  we encounter a modification in the source).
3455
3456       Set_Never_Set_In_Source (Id, True);
3457
3458       --  Now establish the proper kind and type of the object
3459
3460       if Constant_Present (N) then
3461          Set_Ekind            (Id, E_Constant);
3462          Set_Is_True_Constant (Id, True);
3463
3464       else
3465          Set_Ekind (Id, E_Variable);
3466
3467          --  A variable is set as shared passive if it appears in a shared
3468          --  passive package, and is at the outer level. This is not done for
3469          --  entities generated during expansion, because those are always
3470          --  manipulated locally.
3471
3472          if Is_Shared_Passive (Current_Scope)
3473            and then Is_Library_Level_Entity (Id)
3474            and then Comes_From_Source (Id)
3475          then
3476             Set_Is_Shared_Passive (Id);
3477             Check_Shared_Var (Id, T, N);
3478          end if;
3479
3480          --  Set Has_Initial_Value if initializing expression present. Note
3481          --  that if there is no initializing expression, we leave the state
3482          --  of this flag unchanged (usually it will be False, but notably in
3483          --  the case of exception choice variables, it will already be true).
3484
3485          if Present (E) then
3486             Set_Has_Initial_Value (Id, True);
3487          end if;
3488       end if;
3489
3490       --  Initialize alignment and size and capture alignment setting
3491
3492       Init_Alignment               (Id);
3493       Init_Esize                   (Id);
3494       Set_Optimize_Alignment_Flags (Id);
3495
3496       --  Deal with aliased case
3497
3498       if Aliased_Present (N) then
3499          Set_Is_Aliased (Id);
3500
3501          --  If the object is aliased and the type is unconstrained with
3502          --  defaulted discriminants and there is no expression, then the
3503          --  object is constrained by the defaults, so it is worthwhile
3504          --  building the corresponding subtype.
3505
3506          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3507          --  unconstrained, then only establish an actual subtype if the
3508          --  nominal subtype is indefinite. In definite cases the object is
3509          --  unconstrained in Ada 2005.
3510
3511          if No (E)
3512            and then Is_Record_Type (T)
3513            and then not Is_Constrained (T)
3514            and then Has_Discriminants (T)
3515            and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
3516          then
3517             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3518          end if;
3519       end if;
3520
3521       --  Now we can set the type of the object
3522
3523       Set_Etype (Id, Act_T);
3524
3525       --  Deal with controlled types
3526
3527       if Has_Controlled_Component (Etype (Id))
3528         or else Is_Controlled (Etype (Id))
3529       then
3530          if not Is_Library_Level_Entity (Id) then
3531             Check_Restriction (No_Nested_Finalization, N);
3532          else
3533             Validate_Controlled_Object (Id);
3534          end if;
3535
3536          --  Generate a warning when an initialization causes an obvious ABE
3537          --  violation. If the init expression is a simple aggregate there
3538          --  shouldn't be any initialize/adjust call generated. This will be
3539          --  true as soon as aggregates are built in place when possible.
3540
3541          --  ??? at the moment we do not generate warnings for temporaries
3542          --  created for those aggregates although Program_Error might be
3543          --  generated if compiled with -gnato.
3544
3545          if Is_Controlled (Etype (Id))
3546             and then Comes_From_Source (Id)
3547          then
3548             declare
3549                BT : constant Entity_Id := Base_Type (Etype (Id));
3550
3551                Implicit_Call : Entity_Id;
3552                pragma Warnings (Off, Implicit_Call);
3553                --  ??? what is this for (never referenced!)
3554
3555                function Is_Aggr (N : Node_Id) return Boolean;
3556                --  Check that N is an aggregate
3557
3558                -------------
3559                -- Is_Aggr --
3560                -------------
3561
3562                function Is_Aggr (N : Node_Id) return Boolean is
3563                begin
3564                   case Nkind (Original_Node (N)) is
3565                      when N_Aggregate | N_Extension_Aggregate =>
3566                         return True;
3567
3568                      when N_Qualified_Expression |
3569                           N_Type_Conversion      |
3570                           N_Unchecked_Type_Conversion =>
3571                         return Is_Aggr (Expression (Original_Node (N)));
3572
3573                      when others =>
3574                         return False;
3575                   end case;
3576                end Is_Aggr;
3577
3578             begin
3579                --  If no underlying type, we already are in an error situation.
3580                --  Do not try to add a warning since we do not have access to
3581                --  prim-op list.
3582
3583                if No (Underlying_Type (BT)) then
3584                   Implicit_Call := Empty;
3585
3586                --  A generic type does not have usable primitive operators.
3587                --  Initialization calls are built for instances.
3588
3589                elsif Is_Generic_Type (BT) then
3590                   Implicit_Call := Empty;
3591
3592                --  If the init expression is not an aggregate, an adjust call
3593                --  will be generated
3594
3595                elsif Present (E) and then not Is_Aggr (E) then
3596                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
3597
3598                --  If no init expression and we are not in the deferred
3599                --  constant case, an Initialize call will be generated
3600
3601                elsif No (E) and then not Constant_Present (N) then
3602                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
3603
3604                else
3605                   Implicit_Call := Empty;
3606                end if;
3607             end;
3608          end if;
3609       end if;
3610
3611       if Has_Task (Etype (Id)) then
3612          Check_Restriction (No_Tasking, N);
3613
3614          --  Deal with counting max tasks
3615
3616          --  Nothing to do if inside a generic
3617
3618          if Inside_A_Generic then
3619             null;
3620
3621          --  If library level entity, then count tasks
3622
3623          elsif Is_Library_Level_Entity (Id) then
3624             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3625
3626          --  If not library level entity, then indicate we don't know max
3627          --  tasks and also check task hierarchy restriction and blocking
3628          --  operation (since starting a task is definitely blocking!)
3629
3630          else
3631             Check_Restriction (Max_Tasks, N);
3632             Check_Restriction (No_Task_Hierarchy, N);
3633             Check_Potentially_Blocking_Operation (N);
3634          end if;
3635
3636          --  A rather specialized test. If we see two tasks being declared
3637          --  of the same type in the same object declaration, and the task
3638          --  has an entry with an address clause, we know that program error
3639          --  will be raised at run time since we can't have two tasks with
3640          --  entries at the same address.
3641
3642          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3643             declare
3644                E : Entity_Id;
3645
3646             begin
3647                E := First_Entity (Etype (Id));
3648                while Present (E) loop
3649                   if Ekind (E) = E_Entry
3650                     and then Present (Get_Attribute_Definition_Clause
3651                                         (E, Attribute_Address))
3652                   then
3653                      Error_Msg_N
3654                        ("?more than one task with same entry address", N);
3655                      Error_Msg_N
3656                        ("\?Program_Error will be raised at run time", N);
3657                      Insert_Action (N,
3658                        Make_Raise_Program_Error (Loc,
3659                          Reason => PE_Duplicated_Entry_Address));
3660                      exit;
3661                   end if;
3662
3663                   Next_Entity (E);
3664                end loop;
3665             end;
3666          end if;
3667       end if;
3668
3669       --  Some simple constant-propagation: if the expression is a constant
3670       --  string initialized with a literal, share the literal. This avoids
3671       --  a run-time copy.
3672
3673       if Present (E)
3674         and then Is_Entity_Name (E)
3675         and then Ekind (Entity (E)) = E_Constant
3676         and then Base_Type (Etype (E)) = Standard_String
3677       then
3678          declare
3679             Val : constant Node_Id := Constant_Value (Entity (E));
3680          begin
3681             if Present (Val)
3682               and then Nkind (Val) = N_String_Literal
3683             then
3684                Rewrite (E, New_Copy (Val));
3685             end if;
3686          end;
3687       end if;
3688
3689       --  Another optimization: if the nominal subtype is unconstrained and
3690       --  the expression is a function call that returns an unconstrained
3691       --  type, rewrite the declaration as a renaming of the result of the
3692       --  call. The exceptions below are cases where the copy is expected,
3693       --  either by the back end (Aliased case) or by the semantics, as for
3694       --  initializing controlled types or copying tags for classwide types.
3695
3696       if Present (E)
3697         and then Nkind (E) = N_Explicit_Dereference
3698         and then Nkind (Original_Node (E)) = N_Function_Call
3699         and then not Is_Library_Level_Entity (Id)
3700         and then not Is_Constrained (Underlying_Type (T))
3701         and then not Is_Aliased (Id)
3702         and then not Is_Class_Wide_Type (T)
3703         and then not Is_Controlled (T)
3704         and then not Has_Controlled_Component (Base_Type (T))
3705         and then Expander_Active
3706       then
3707          Rewrite (N,
3708            Make_Object_Renaming_Declaration (Loc,
3709              Defining_Identifier => Id,
3710              Access_Definition   => Empty,
3711              Subtype_Mark        => New_Occurrence_Of
3712                                       (Base_Type (Etype (Id)), Loc),
3713              Name                => E));
3714
3715          Set_Renamed_Object (Id, E);
3716
3717          --  Force generation of debugging information for the constant and for
3718          --  the renamed function call.
3719
3720          Set_Debug_Info_Needed (Id);
3721          Set_Debug_Info_Needed (Entity (Prefix (E)));
3722       end if;
3723
3724       if Present (Prev_Entity)
3725         and then Is_Frozen (Prev_Entity)
3726         and then not Error_Posted (Id)
3727       then
3728          Error_Msg_N ("full constant declaration appears too late", N);
3729       end if;
3730
3731       Check_Eliminated (Id);
3732
3733       --  Deal with setting In_Private_Part flag if in private part
3734
3735       if Ekind (Scope (Id)) = E_Package
3736         and then In_Private_Part (Scope (Id))
3737       then
3738          Set_In_Private_Part (Id);
3739       end if;
3740
3741       --  Check for violation of No_Local_Timing_Events
3742
3743       if Restriction_Check_Required (No_Local_Timing_Events)
3744         and then not Is_Library_Level_Entity (Id)
3745         and then Is_RTE (Etype (Id), RE_Timing_Event)
3746       then
3747          Check_Restriction (No_Local_Timing_Events, N);
3748       end if;
3749
3750    <<Leave>>
3751       if Has_Aspects (N) then
3752          Analyze_Aspect_Specifications (N, Id);
3753       end if;
3754    end Analyze_Object_Declaration;
3755
3756    ---------------------------
3757    -- Analyze_Others_Choice --
3758    ---------------------------
3759
3760    --  Nothing to do for the others choice node itself, the semantic analysis
3761    --  of the others choice will occur as part of the processing of the parent
3762
3763    procedure Analyze_Others_Choice (N : Node_Id) is
3764       pragma Warnings (Off, N);
3765    begin
3766       null;
3767    end Analyze_Others_Choice;
3768
3769    -------------------------------------------
3770    -- Analyze_Private_Extension_Declaration --
3771    -------------------------------------------
3772
3773    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3774       T           : constant Entity_Id := Defining_Identifier (N);
3775       Indic       : constant Node_Id   := Subtype_Indication (N);
3776       Parent_Type : Entity_Id;
3777       Parent_Base : Entity_Id;
3778
3779    begin
3780       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3781
3782       if Is_Non_Empty_List (Interface_List (N)) then
3783          declare
3784             Intf : Node_Id;
3785             T    : Entity_Id;
3786
3787          begin
3788             Intf := First (Interface_List (N));
3789             while Present (Intf) loop
3790                T := Find_Type_Of_Subtype_Indic (Intf);
3791
3792                Diagnose_Interface (Intf, T);
3793                Next (Intf);
3794             end loop;
3795          end;
3796       end if;
3797
3798       Generate_Definition (T);
3799
3800       --  For other than Ada 2012, just enter the name in the current scope
3801
3802       if Ada_Version < Ada_2012 then
3803          Enter_Name (T);
3804
3805       --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
3806       --  case of private type that completes an incomplete type.
3807
3808       else
3809          declare
3810             Prev : Entity_Id;
3811
3812          begin
3813             Prev := Find_Type_Name (N);
3814
3815             pragma Assert (Prev = T
3816               or else (Ekind (Prev) = E_Incomplete_Type
3817                          and then Present (Full_View (Prev))
3818                          and then Full_View (Prev) = T));
3819          end;
3820       end if;
3821
3822       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3823       Parent_Base := Base_Type (Parent_Type);
3824
3825       if Parent_Type = Any_Type
3826         or else Etype (Parent_Type) = Any_Type
3827       then
3828          Set_Ekind (T, Ekind (Parent_Type));
3829          Set_Etype (T, Any_Type);
3830          goto Leave;
3831
3832       elsif not Is_Tagged_Type (Parent_Type) then
3833          Error_Msg_N
3834            ("parent of type extension must be a tagged type ", Indic);
3835          goto Leave;
3836
3837       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3838          Error_Msg_N ("premature derivation of incomplete type", Indic);
3839          goto Leave;
3840
3841       elsif Is_Concurrent_Type (Parent_Type) then
3842          Error_Msg_N
3843            ("parent type of a private extension cannot be "
3844             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3845
3846          Set_Etype              (T, Any_Type);
3847          Set_Ekind              (T, E_Limited_Private_Type);
3848          Set_Private_Dependents (T, New_Elmt_List);
3849          Set_Error_Posted       (T);
3850          goto Leave;
3851       end if;
3852
3853       --  Perhaps the parent type should be changed to the class-wide type's
3854       --  specific type in this case to prevent cascading errors ???
3855
3856       if Is_Class_Wide_Type (Parent_Type) then
3857          Error_Msg_N
3858            ("parent of type extension must not be a class-wide type", Indic);
3859          goto Leave;
3860       end if;
3861
3862       if (not Is_Package_Or_Generic_Package (Current_Scope)
3863            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3864         or else In_Private_Part (Current_Scope)
3865
3866       then
3867          Error_Msg_N ("invalid context for private extension", N);
3868       end if;
3869
3870       --  Set common attributes
3871
3872       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3873       Set_Scope            (T, Current_Scope);
3874       Set_Ekind            (T, E_Record_Type_With_Private);
3875       Init_Size_Align      (T);
3876
3877       Set_Etype            (T,            Parent_Base);
3878       Set_Has_Task         (T, Has_Task  (Parent_Base));
3879
3880       Set_Convention       (T, Convention     (Parent_Type));
3881       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3882       Set_Is_First_Subtype (T);
3883       Make_Class_Wide_Type (T);
3884
3885       if Unknown_Discriminants_Present (N) then
3886          Set_Discriminant_Constraint (T, No_Elist);
3887       end if;
3888
3889       Build_Derived_Record_Type (N, Parent_Type, T);
3890
3891       --  Propagate inherited invariant information. The new type has
3892       --  invariants, if the parent type has inheritable invariants,
3893       --  and these invariants can in turn be inherited.
3894
3895       if Has_Inheritable_Invariants (Parent_Type) then
3896          Set_Has_Inheritable_Invariants (T);
3897          Set_Has_Invariants (T);
3898       end if;
3899
3900       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3901       --  synchronized formal derived type.
3902
3903       if Ada_Version >= Ada_2005
3904         and then Synchronized_Present (N)
3905       then
3906          Set_Is_Limited_Record (T);
3907
3908          --  Formal derived type case
3909
3910          if Is_Generic_Type (T) then
3911
3912             --  The parent must be a tagged limited type or a synchronized
3913             --  interface.
3914
3915             if (not Is_Tagged_Type (Parent_Type)
3916                   or else not Is_Limited_Type (Parent_Type))
3917               and then
3918                (not Is_Interface (Parent_Type)
3919                   or else not Is_Synchronized_Interface (Parent_Type))
3920             then
3921                Error_Msg_NE ("parent type of & must be tagged limited " &
3922                              "or synchronized", N, T);
3923             end if;
3924
3925             --  The progenitors (if any) must be limited or synchronized
3926             --  interfaces.
3927
3928             if Present (Interfaces (T)) then
3929                declare
3930                   Iface      : Entity_Id;
3931                   Iface_Elmt : Elmt_Id;
3932
3933                begin
3934                   Iface_Elmt := First_Elmt (Interfaces (T));
3935                   while Present (Iface_Elmt) loop
3936                      Iface := Node (Iface_Elmt);
3937
3938                      if not Is_Limited_Interface (Iface)
3939                        and then not Is_Synchronized_Interface (Iface)
3940                      then
3941                         Error_Msg_NE ("progenitor & must be limited " &
3942                                       "or synchronized", N, Iface);
3943                      end if;
3944
3945                      Next_Elmt (Iface_Elmt);
3946                   end loop;
3947                end;
3948             end if;
3949
3950          --  Regular derived extension, the parent must be a limited or
3951          --  synchronized interface.
3952
3953          else
3954             if not Is_Interface (Parent_Type)
3955               or else (not Is_Limited_Interface (Parent_Type)
3956                          and then
3957                        not Is_Synchronized_Interface (Parent_Type))
3958             then
3959                Error_Msg_NE
3960                  ("parent type of & must be limited interface", N, T);
3961             end if;
3962          end if;
3963
3964       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
3965       --  extension with a synchronized parent must be explicitly declared
3966       --  synchronized, because the full view will be a synchronized type.
3967       --  This must be checked before the check for limited types below,
3968       --  to ensure that types declared limited are not allowed to extend
3969       --  synchronized interfaces.
3970
3971       elsif Is_Interface (Parent_Type)
3972         and then Is_Synchronized_Interface (Parent_Type)
3973         and then not Synchronized_Present (N)
3974       then
3975          Error_Msg_NE
3976            ("private extension of& must be explicitly synchronized",
3977              N, Parent_Type);
3978
3979       elsif Limited_Present (N) then
3980          Set_Is_Limited_Record (T);
3981
3982          if not Is_Limited_Type (Parent_Type)
3983            and then
3984              (not Is_Interface (Parent_Type)
3985                or else not Is_Limited_Interface (Parent_Type))
3986          then
3987             Error_Msg_NE ("parent type& of limited extension must be limited",
3988               N, Parent_Type);
3989          end if;
3990       end if;
3991
3992    <<Leave>>
3993       if Has_Aspects (N) then
3994          Analyze_Aspect_Specifications (N, T);
3995       end if;
3996    end Analyze_Private_Extension_Declaration;
3997
3998    ---------------------------------
3999    -- Analyze_Subtype_Declaration --
4000    ---------------------------------
4001
4002    procedure Analyze_Subtype_Declaration
4003      (N    : Node_Id;
4004       Skip : Boolean := False)
4005    is
4006       Id       : constant Entity_Id := Defining_Identifier (N);
4007       T        : Entity_Id;
4008       R_Checks : Check_Result;
4009
4010    begin
4011       Generate_Definition (Id);
4012       Set_Is_Pure (Id, Is_Pure (Current_Scope));
4013       Init_Size_Align (Id);
4014
4015       --  The following guard condition on Enter_Name is to handle cases where
4016       --  the defining identifier has already been entered into the scope but
4017       --  the declaration as a whole needs to be analyzed.
4018
4019       --  This case in particular happens for derived enumeration types. The
4020       --  derived enumeration type is processed as an inserted enumeration type
4021       --  declaration followed by a rewritten subtype declaration. The defining
4022       --  identifier, however, is entered into the name scope very early in the
4023       --  processing of the original type declaration and therefore needs to be
4024       --  avoided here, when the created subtype declaration is analyzed. (See
4025       --  Build_Derived_Types)
4026
4027       --  This also happens when the full view of a private type is derived
4028       --  type with constraints. In this case the entity has been introduced
4029       --  in the private declaration.
4030
4031       if Skip
4032         or else (Present (Etype (Id))
4033                   and then (Is_Private_Type (Etype (Id))
4034                              or else Is_Task_Type (Etype (Id))
4035                              or else Is_Rewrite_Substitution (N)))
4036       then
4037          null;
4038
4039       else
4040          Enter_Name (Id);
4041       end if;
4042
4043       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
4044
4045       --  Inherit common attributes
4046
4047       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
4048       Set_Is_Volatile       (Id, Is_Volatile       (T));
4049       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
4050       Set_Is_Atomic         (Id, Is_Atomic         (T));
4051       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
4052       Set_Is_Ada_2012_Only  (Id, Is_Ada_2012_Only  (T));
4053       Set_Convention        (Id, Convention        (T));
4054
4055       --  If ancestor has predicates then so does the subtype, and in addition
4056       --  we must delay the freeze to properly arrange predicate inheritance.
4057
4058       --  The Ancestor_Type test is a big kludge, there seem to be cases in
4059       --  which T = ID, so the above tests and assignments do nothing???
4060
4061       if Has_Predicates (T)
4062         or else (Present (Ancestor_Subtype (T))
4063                   and then Has_Predicates (Ancestor_Subtype (T)))
4064       then
4065          Set_Has_Predicates (Id);
4066          Set_Has_Delayed_Freeze (Id);
4067       end if;
4068
4069       --  Subtype of Boolean cannot have a constraint in SPARK
4070
4071       if Is_Boolean_Type (T)
4072         and then Nkind (Subtype_Indication (N)) = N_Subtype_Indication
4073       then
4074          Check_SPARK_Restriction
4075            ("subtype of Boolean cannot have constraint", N);
4076       end if;
4077
4078       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4079          declare
4080             Cstr     : constant Node_Id := Constraint (Subtype_Indication (N));
4081             One_Cstr : Node_Id;
4082             Low      : Node_Id;
4083             High     : Node_Id;
4084
4085          begin
4086             if Nkind (Cstr) = N_Index_Or_Discriminant_Constraint then
4087                One_Cstr := First (Constraints (Cstr));
4088                while Present (One_Cstr) loop
4089
4090                   --  Index or discriminant constraint in SPARK must be a
4091                   --  subtype mark.
4092
4093                   if not
4094                     Nkind_In (One_Cstr, N_Identifier, N_Expanded_Name)
4095                   then
4096                      Check_SPARK_Restriction
4097                        ("subtype mark required", One_Cstr);
4098
4099                   --  String subtype must have a lower bound of 1 in SPARK.
4100                   --  Note that we do not need to test for the non-static case
4101                   --  here, since that was already taken care of in
4102                   --  Process_Range_Expr_In_Decl.
4103
4104                   elsif Base_Type (T) = Standard_String then
4105                      Get_Index_Bounds (One_Cstr, Low, High);
4106
4107                      if Is_OK_Static_Expression (Low)
4108                        and then Expr_Value (Low) /= 1
4109                      then
4110                         Check_SPARK_Restriction
4111                           ("String subtype must have lower bound of 1", N);
4112                      end if;
4113                   end if;
4114
4115                   Next (One_Cstr);
4116                end loop;
4117             end if;
4118          end;
4119       end if;
4120
4121       --  In the case where there is no constraint given in the subtype
4122       --  indication, Process_Subtype just returns the Subtype_Mark, so its
4123       --  semantic attributes must be established here.
4124
4125       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
4126          Set_Etype (Id, Base_Type (T));
4127
4128          --  Subtype of unconstrained array without constraint is not allowed
4129          --  in SPARK.
4130
4131          if Is_Array_Type (T)
4132            and then not Is_Constrained (T)
4133          then
4134             Check_SPARK_Restriction
4135               ("subtype of unconstrained array must have constraint", N);
4136          end if;
4137
4138          case Ekind (T) is
4139             when Array_Kind =>
4140                Set_Ekind                       (Id, E_Array_Subtype);
4141                Copy_Array_Subtype_Attributes   (Id, T);
4142
4143             when Decimal_Fixed_Point_Kind =>
4144                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
4145                Set_Digits_Value         (Id, Digits_Value       (T));
4146                Set_Delta_Value          (Id, Delta_Value        (T));
4147                Set_Scale_Value          (Id, Scale_Value        (T));
4148                Set_Small_Value          (Id, Small_Value        (T));
4149                Set_Scalar_Range         (Id, Scalar_Range       (T));
4150                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
4151                Set_Is_Constrained       (Id, Is_Constrained     (T));
4152                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4153                Set_RM_Size              (Id, RM_Size            (T));
4154
4155             when Enumeration_Kind =>
4156                Set_Ekind                (Id, E_Enumeration_Subtype);
4157                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
4158                Set_Scalar_Range         (Id, Scalar_Range       (T));
4159                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
4160                Set_Is_Constrained       (Id, Is_Constrained     (T));
4161                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4162                Set_RM_Size              (Id, RM_Size            (T));
4163
4164             when Ordinary_Fixed_Point_Kind =>
4165                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
4166                Set_Scalar_Range         (Id, Scalar_Range       (T));
4167                Set_Small_Value          (Id, Small_Value        (T));
4168                Set_Delta_Value          (Id, Delta_Value        (T));
4169                Set_Is_Constrained       (Id, Is_Constrained     (T));
4170                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4171                Set_RM_Size              (Id, RM_Size            (T));
4172
4173             when Float_Kind =>
4174                Set_Ekind                (Id, E_Floating_Point_Subtype);
4175                Set_Scalar_Range         (Id, Scalar_Range       (T));
4176                Set_Digits_Value         (Id, Digits_Value       (T));
4177                Set_Is_Constrained       (Id, Is_Constrained     (T));
4178
4179             when Signed_Integer_Kind =>
4180                Set_Ekind                (Id, E_Signed_Integer_Subtype);
4181                Set_Scalar_Range         (Id, Scalar_Range       (T));
4182                Set_Is_Constrained       (Id, Is_Constrained     (T));
4183                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4184                Set_RM_Size              (Id, RM_Size            (T));
4185
4186             when Modular_Integer_Kind =>
4187                Set_Ekind                (Id, E_Modular_Integer_Subtype);
4188                Set_Scalar_Range         (Id, Scalar_Range       (T));
4189                Set_Is_Constrained       (Id, Is_Constrained     (T));
4190                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4191                Set_RM_Size              (Id, RM_Size            (T));
4192
4193             when Class_Wide_Kind =>
4194                Set_Ekind                (Id, E_Class_Wide_Subtype);
4195                Set_First_Entity         (Id, First_Entity       (T));
4196                Set_Last_Entity          (Id, Last_Entity        (T));
4197                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
4198                Set_Cloned_Subtype       (Id, T);
4199                Set_Is_Tagged_Type       (Id, True);
4200                Set_Has_Unknown_Discriminants
4201                                         (Id, True);
4202
4203                if Ekind (T) = E_Class_Wide_Subtype then
4204                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
4205                end if;
4206
4207             when E_Record_Type | E_Record_Subtype =>
4208                Set_Ekind                (Id, E_Record_Subtype);
4209
4210                if Ekind (T) = E_Record_Subtype
4211                  and then Present (Cloned_Subtype (T))
4212                then
4213                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
4214                else
4215                   Set_Cloned_Subtype    (Id, T);
4216                end if;
4217
4218                Set_First_Entity         (Id, First_Entity       (T));
4219                Set_Last_Entity          (Id, Last_Entity        (T));
4220                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
4221                Set_Is_Constrained       (Id, Is_Constrained     (T));
4222                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
4223                Set_Has_Implicit_Dereference
4224                                         (Id, Has_Implicit_Dereference (T));
4225                Set_Has_Unknown_Discriminants
4226                                         (Id, Has_Unknown_Discriminants (T));
4227
4228                if Has_Discriminants (T) then
4229                   Set_Discriminant_Constraint
4230                                         (Id, Discriminant_Constraint (T));
4231                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4232
4233                elsif Has_Unknown_Discriminants (Id) then
4234                   Set_Discriminant_Constraint (Id, No_Elist);
4235                end if;
4236
4237                if Is_Tagged_Type (T) then
4238                   Set_Is_Tagged_Type    (Id);
4239                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
4240                   Set_Direct_Primitive_Operations
4241                                         (Id, Direct_Primitive_Operations (T));
4242                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
4243
4244                   if Is_Interface (T) then
4245                      Set_Is_Interface (Id);
4246                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
4247                   end if;
4248                end if;
4249
4250             when Private_Kind =>
4251                Set_Ekind              (Id, Subtype_Kind (Ekind        (T)));
4252                Set_Has_Discriminants  (Id, Has_Discriminants          (T));
4253                Set_Is_Constrained     (Id, Is_Constrained             (T));
4254                Set_First_Entity       (Id, First_Entity               (T));
4255                Set_Last_Entity        (Id, Last_Entity                (T));
4256                Set_Private_Dependents (Id, New_Elmt_List);
4257                Set_Is_Limited_Record  (Id, Is_Limited_Record          (T));
4258                Set_Has_Implicit_Dereference
4259                                       (Id, Has_Implicit_Dereference   (T));
4260                Set_Has_Unknown_Discriminants
4261                                       (Id, Has_Unknown_Discriminants  (T));
4262                Set_Known_To_Have_Preelab_Init
4263                                       (Id, Known_To_Have_Preelab_Init (T));
4264
4265                if Is_Tagged_Type (T) then
4266                   Set_Is_Tagged_Type              (Id);
4267                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
4268                   Set_Class_Wide_Type             (Id, Class_Wide_Type  (T));
4269                   Set_Direct_Primitive_Operations (Id,
4270                     Direct_Primitive_Operations (T));
4271                end if;
4272
4273                --  In general the attributes of the subtype of a private type
4274                --  are the attributes of the partial view of parent. However,
4275                --  the full view may be a discriminated type, and the subtype
4276                --  must share the discriminant constraint to generate correct
4277                --  calls to initialization procedures.
4278
4279                if Has_Discriminants (T) then
4280                   Set_Discriminant_Constraint
4281                     (Id, Discriminant_Constraint (T));
4282                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4283
4284                elsif Present (Full_View (T))
4285                  and then Has_Discriminants (Full_View (T))
4286                then
4287                   Set_Discriminant_Constraint
4288                     (Id, Discriminant_Constraint (Full_View (T)));
4289                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4290
4291                   --  This would seem semantically correct, but apparently
4292                   --  confuses the back-end. To be explained and checked with
4293                   --  current version ???
4294
4295                   --  Set_Has_Discriminants (Id);
4296                end if;
4297
4298                Prepare_Private_Subtype_Completion (Id, N);
4299
4300             when Access_Kind =>
4301                Set_Ekind             (Id, E_Access_Subtype);
4302                Set_Is_Constrained    (Id, Is_Constrained        (T));
4303                Set_Is_Access_Constant
4304                                      (Id, Is_Access_Constant    (T));
4305                Set_Directly_Designated_Type
4306                                      (Id, Designated_Type       (T));
4307                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4308
4309                --  A Pure library_item must not contain the declaration of a
4310                --  named access type, except within a subprogram, generic
4311                --  subprogram, task unit, or protected unit, or if it has
4312                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4313
4314                if Comes_From_Source (Id)
4315                  and then In_Pure_Unit
4316                  and then not In_Subprogram_Task_Protected_Unit
4317                  and then not No_Pool_Assigned (Id)
4318                then
4319                   Error_Msg_N
4320                     ("named access types not allowed in pure unit", N);
4321                end if;
4322
4323             when Concurrent_Kind =>
4324                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4325                Set_Corresponding_Record_Type (Id,
4326                                          Corresponding_Record_Type (T));
4327                Set_First_Entity         (Id, First_Entity          (T));
4328                Set_First_Private_Entity (Id, First_Private_Entity  (T));
4329                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4330                Set_Is_Constrained       (Id, Is_Constrained        (T));
4331                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4332                Set_Last_Entity          (Id, Last_Entity           (T));
4333
4334                if Has_Discriminants (T) then
4335                   Set_Discriminant_Constraint (Id,
4336                                            Discriminant_Constraint (T));
4337                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4338                end if;
4339
4340             when E_Incomplete_Type =>
4341                if Ada_Version >= Ada_2005 then
4342                   Set_Ekind (Id, E_Incomplete_Subtype);
4343
4344                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
4345                   --  of an incomplete type visible through a limited
4346                   --  with clause.
4347
4348                   if From_With_Type (T)
4349                     and then Present (Non_Limited_View (T))
4350                   then
4351                      Set_From_With_Type   (Id);
4352                      Set_Non_Limited_View (Id, Non_Limited_View (T));
4353
4354                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
4355                   --  to the private dependents of the original incomplete
4356                   --  type for future transformation.
4357
4358                   else
4359                      Append_Elmt (Id, Private_Dependents (T));
4360                   end if;
4361
4362                --  If the subtype name denotes an incomplete type an error
4363                --  was already reported by Process_Subtype.
4364
4365                else
4366                   Set_Etype (Id, Any_Type);
4367                end if;
4368
4369             when others =>
4370                raise Program_Error;
4371          end case;
4372       end if;
4373
4374       if Etype (Id) = Any_Type then
4375          goto Leave;
4376       end if;
4377
4378       --  Some common processing on all types
4379
4380       Set_Size_Info      (Id,                 T);
4381       Set_First_Rep_Item (Id, First_Rep_Item (T));
4382
4383       T := Etype (Id);
4384
4385       Set_Is_Immediately_Visible   (Id, True);
4386       Set_Depends_On_Private       (Id, Has_Private_Component (T));
4387       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
4388
4389       if Is_Interface (T) then
4390          Set_Is_Interface (Id);
4391       end if;
4392
4393       if Present (Generic_Parent_Type (N))
4394         and then
4395           (Nkind
4396             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
4397             or else Nkind
4398               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
4399                 /= N_Formal_Private_Type_Definition)
4400       then
4401          if Is_Tagged_Type (Id) then
4402
4403             --  If this is a generic actual subtype for a synchronized type,
4404             --  the primitive operations are those of the corresponding record
4405             --  for which there is a separate subtype declaration.
4406
4407             if Is_Concurrent_Type (Id) then
4408                null;
4409             elsif Is_Class_Wide_Type (Id) then
4410                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
4411             else
4412                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
4413             end if;
4414
4415          elsif Scope (Etype (Id)) /= Standard_Standard then
4416             Derive_Subprograms (Generic_Parent_Type (N), Id);
4417          end if;
4418       end if;
4419
4420       if Is_Private_Type (T)
4421         and then Present (Full_View (T))
4422       then
4423          Conditional_Delay (Id, Full_View (T));
4424
4425       --  The subtypes of components or subcomponents of protected types
4426       --  do not need freeze nodes, which would otherwise appear in the
4427       --  wrong scope (before the freeze node for the protected type). The
4428       --  proper subtypes are those of the subcomponents of the corresponding
4429       --  record.
4430
4431       elsif Ekind (Scope (Id)) /= E_Protected_Type
4432         and then Present (Scope (Scope (Id))) -- error defense!
4433         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
4434       then
4435          Conditional_Delay (Id, T);
4436       end if;
4437
4438       --  Check that Constraint_Error is raised for a scalar subtype indication
4439       --  when the lower or upper bound of a non-null range lies outside the
4440       --  range of the type mark.
4441
4442       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4443          if Is_Scalar_Type (Etype (Id))
4444             and then Scalar_Range (Id) /=
4445                      Scalar_Range (Etype (Subtype_Mark
4446                                            (Subtype_Indication (N))))
4447          then
4448             Apply_Range_Check
4449               (Scalar_Range (Id),
4450                Etype (Subtype_Mark (Subtype_Indication (N))));
4451
4452          --  In the array case, check compatibility for each index
4453
4454          elsif Is_Array_Type (Etype (Id))
4455            and then Present (First_Index (Id))
4456          then
4457             --  This really should be a subprogram that finds the indications
4458             --  to check???
4459
4460             declare
4461                Subt_Index   : Node_Id := First_Index (Id);
4462                Target_Index : Node_Id :=
4463                                 First_Index (Etype
4464                                   (Subtype_Mark (Subtype_Indication (N))));
4465                Has_Dyn_Chk  : Boolean := Has_Dynamic_Range_Check (N);
4466
4467             begin
4468                while Present (Subt_Index) loop
4469                   if ((Nkind (Subt_Index) = N_Identifier
4470                          and then Ekind (Entity (Subt_Index)) in Scalar_Kind)
4471                        or else Nkind (Subt_Index) = N_Subtype_Indication)
4472                     and then
4473                       Nkind (Scalar_Range (Etype (Subt_Index))) = N_Range
4474                   then
4475                      declare
4476                         Target_Typ : constant Entity_Id :=
4477                                        Etype (Target_Index);
4478                      begin
4479                         R_Checks :=
4480                           Get_Range_Checks
4481                             (Scalar_Range (Etype (Subt_Index)),
4482                              Target_Typ,
4483                              Etype (Subt_Index),
4484                              Defining_Identifier (N));
4485
4486                         --  Reset Has_Dynamic_Range_Check on the subtype to
4487                         --  prevent elision of the index check due to a dynamic
4488                         --  check generated for a preceding index (needed since
4489                         --  Insert_Range_Checks tries to avoid generating
4490                         --  redundant checks on a given declaration).
4491
4492                         Set_Has_Dynamic_Range_Check (N, False);
4493
4494                         Insert_Range_Checks
4495                           (R_Checks,
4496                            N,
4497                            Target_Typ,
4498                            Sloc (Defining_Identifier (N)));
4499
4500                         --  Record whether this index involved a dynamic check
4501
4502                         Has_Dyn_Chk :=
4503                           Has_Dyn_Chk or else Has_Dynamic_Range_Check (N);
4504                      end;
4505                   end if;
4506
4507                   Next_Index (Subt_Index);
4508                   Next_Index (Target_Index);
4509                end loop;
4510
4511                --  Finally, mark whether the subtype involves dynamic checks
4512
4513                Set_Has_Dynamic_Range_Check (N, Has_Dyn_Chk);
4514             end;
4515          end if;
4516       end if;
4517
4518       --  Make sure that generic actual types are properly frozen. The subtype
4519       --  is marked as a generic actual type when the enclosing instance is
4520       --  analyzed, so here we identify the subtype from the tree structure.
4521
4522       if Expander_Active
4523         and then Is_Generic_Actual_Type (Id)
4524         and then In_Instance
4525         and then not Comes_From_Source (N)
4526         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
4527         and then Is_Frozen (T)
4528       then
4529          Freeze_Before (N, Id);
4530       end if;
4531
4532       Set_Optimize_Alignment_Flags (Id);
4533       Check_Eliminated (Id);
4534
4535    <<Leave>>
4536       if Has_Aspects (N) then
4537          Analyze_Aspect_Specifications (N, Id);
4538       end if;
4539    end Analyze_Subtype_Declaration;
4540
4541    --------------------------------
4542    -- Analyze_Subtype_Indication --
4543    --------------------------------
4544
4545    procedure Analyze_Subtype_Indication (N : Node_Id) is
4546       T : constant Entity_Id := Subtype_Mark (N);
4547       R : constant Node_Id   := Range_Expression (Constraint (N));
4548
4549    begin
4550       Analyze (T);
4551
4552       if R /= Error then
4553          Analyze (R);
4554          Set_Etype (N, Etype (R));
4555          Resolve (R, Entity (T));
4556       else
4557          Set_Error_Posted (R);
4558          Set_Error_Posted (T);
4559       end if;
4560    end Analyze_Subtype_Indication;
4561
4562    --------------------------
4563    -- Analyze_Variant_Part --
4564    --------------------------
4565
4566    procedure Analyze_Variant_Part (N : Node_Id) is
4567
4568       procedure Non_Static_Choice_Error (Choice : Node_Id);
4569       --  Error routine invoked by the generic instantiation below when the
4570       --  variant part has a non static choice.
4571
4572       procedure Process_Declarations (Variant : Node_Id);
4573       --  Analyzes all the declarations associated with a Variant. Needed by
4574       --  the generic instantiation below.
4575
4576       package Variant_Choices_Processing is new
4577         Generic_Choices_Processing
4578           (Get_Alternatives          => Variants,
4579            Get_Choices               => Discrete_Choices,
4580            Process_Empty_Choice      => No_OP,
4581            Process_Non_Static_Choice => Non_Static_Choice_Error,
4582            Process_Associated_Node   => Process_Declarations);
4583       use Variant_Choices_Processing;
4584       --  Instantiation of the generic choice processing package
4585
4586       -----------------------------
4587       -- Non_Static_Choice_Error --
4588       -----------------------------
4589
4590       procedure Non_Static_Choice_Error (Choice : Node_Id) is
4591       begin
4592          Flag_Non_Static_Expr
4593            ("choice given in variant part is not static!", Choice);
4594       end Non_Static_Choice_Error;
4595
4596       --------------------------
4597       -- Process_Declarations --
4598       --------------------------
4599
4600       procedure Process_Declarations (Variant : Node_Id) is
4601       begin
4602          if not Null_Present (Component_List (Variant)) then
4603             Analyze_Declarations (Component_Items (Component_List (Variant)));
4604
4605             if Present (Variant_Part (Component_List (Variant))) then
4606                Analyze (Variant_Part (Component_List (Variant)));
4607             end if;
4608          end if;
4609       end Process_Declarations;
4610
4611       --  Local Variables
4612
4613       Discr_Name : Node_Id;
4614       Discr_Type : Entity_Id;
4615
4616       Dont_Care      : Boolean;
4617       Others_Present : Boolean := False;
4618
4619       pragma Warnings (Off, Dont_Care);
4620       pragma Warnings (Off, Others_Present);
4621       --  We don't care about the assigned values of any of these
4622
4623    --  Start of processing for Analyze_Variant_Part
4624
4625    begin
4626       Discr_Name := Name (N);
4627       Analyze (Discr_Name);
4628
4629       --  If Discr_Name bad, get out (prevent cascaded errors)
4630
4631       if Etype (Discr_Name) = Any_Type then
4632          return;
4633       end if;
4634
4635       --  Check invalid discriminant in variant part
4636
4637       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4638          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4639       end if;
4640
4641       Discr_Type := Etype (Entity (Discr_Name));
4642
4643       if not Is_Discrete_Type (Discr_Type) then
4644          Error_Msg_N
4645            ("discriminant in a variant part must be of a discrete type",
4646              Name (N));
4647          return;
4648       end if;
4649
4650       --  Call the instantiated Analyze_Choices which does the rest of the work
4651
4652       Analyze_Choices (N, Discr_Type, Dont_Care, Others_Present);
4653    end Analyze_Variant_Part;
4654
4655    ----------------------------
4656    -- Array_Type_Declaration --
4657    ----------------------------
4658
4659    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4660       Component_Def : constant Node_Id := Component_Definition (Def);
4661       Component_Typ : constant Node_Id := Subtype_Indication (Component_Def);
4662       Element_Type  : Entity_Id;
4663       Implicit_Base : Entity_Id;
4664       Index         : Node_Id;
4665       Related_Id    : Entity_Id := Empty;
4666       Nb_Index      : Nat;
4667       P             : constant Node_Id := Parent (Def);
4668       Priv          : Entity_Id;
4669
4670    begin
4671       if Nkind (Def) = N_Constrained_Array_Definition then
4672          Index := First (Discrete_Subtype_Definitions (Def));
4673       else
4674          Index := First (Subtype_Marks (Def));
4675       end if;
4676
4677       --  Find proper names for the implicit types which may be public. In case
4678       --  of anonymous arrays we use the name of the first object of that type
4679       --  as prefix.
4680
4681       if No (T) then
4682          Related_Id := Defining_Identifier (P);
4683       else
4684          Related_Id := T;
4685       end if;
4686
4687       Nb_Index := 1;
4688       while Present (Index) loop
4689          Analyze (Index);
4690
4691          if not Nkind_In (Index, N_Identifier, N_Expanded_Name) then
4692             Check_SPARK_Restriction ("subtype mark required", Index);
4693          end if;
4694
4695          --  Add a subtype declaration for each index of private array type
4696          --  declaration whose etype is also private. For example:
4697
4698          --     package Pkg is
4699          --        type Index is private;
4700          --     private
4701          --        type Table is array (Index) of ...
4702          --     end;
4703
4704          --  This is currently required by the expander for the internally
4705          --  generated equality subprogram of records with variant parts in
4706          --  which the etype of some component is such private type.
4707
4708          if Ekind (Current_Scope) = E_Package
4709            and then In_Private_Part (Current_Scope)
4710            and then Has_Private_Declaration (Etype (Index))
4711          then
4712             declare
4713                Loc   : constant Source_Ptr := Sloc (Def);
4714                New_E : Entity_Id;
4715                Decl  : Entity_Id;
4716
4717             begin
4718                New_E := Make_Temporary (Loc, 'T');
4719                Set_Is_Internal (New_E);
4720
4721                Decl :=
4722                  Make_Subtype_Declaration (Loc,
4723                    Defining_Identifier => New_E,
4724                    Subtype_Indication  =>
4725                      New_Occurrence_Of (Etype (Index), Loc));
4726
4727                Insert_Before (Parent (Def), Decl);
4728                Analyze (Decl);
4729                Set_Etype (Index, New_E);
4730
4731                --  If the index is a range the Entity attribute is not
4732                --  available. Example:
4733
4734                --     package Pkg is
4735                --        type T is private;
4736                --     private
4737                --        type T is new Natural;
4738                --        Table : array (T(1) .. T(10)) of Boolean;
4739                --     end Pkg;
4740
4741                if Nkind (Index) /= N_Range then
4742                   Set_Entity (Index, New_E);
4743                end if;
4744             end;
4745          end if;
4746
4747          Make_Index (Index, P, Related_Id, Nb_Index);
4748
4749          --  Check error of subtype with predicate for index type
4750
4751          Bad_Predicated_Subtype_Use
4752            ("subtype& has predicate, not allowed as index subtype",
4753             Index, Etype (Index));
4754
4755          --  Move to next index
4756
4757          Next_Index (Index);
4758          Nb_Index := Nb_Index + 1;
4759       end loop;
4760
4761       --  Process subtype indication if one is present
4762
4763       if Present (Component_Typ) then
4764          Element_Type := Process_Subtype (Component_Typ, P, Related_Id, 'C');
4765
4766          Set_Etype (Component_Typ, Element_Type);
4767
4768          if not Nkind_In (Component_Typ, N_Identifier, N_Expanded_Name) then
4769             Check_SPARK_Restriction ("subtype mark required", Component_Typ);
4770          end if;
4771
4772       --  Ada 2005 (AI-230): Access Definition case
4773
4774       else pragma Assert (Present (Access_Definition (Component_Def)));
4775
4776          --  Indicate that the anonymous access type is created by the
4777          --  array type declaration.
4778
4779          Element_Type := Access_Definition
4780                            (Related_Nod => P,
4781                             N           => Access_Definition (Component_Def));
4782          Set_Is_Local_Anonymous_Access (Element_Type);
4783
4784          --  Propagate the parent. This field is needed if we have to generate
4785          --  the master_id associated with an anonymous access to task type
4786          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4787
4788          Set_Parent (Element_Type, Parent (T));
4789
4790          --  Ada 2005 (AI-230): In case of components that are anonymous access
4791          --  types the level of accessibility depends on the enclosing type
4792          --  declaration
4793
4794          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4795
4796          --  Ada 2005 (AI-254)
4797
4798          declare
4799             CD : constant Node_Id :=
4800                    Access_To_Subprogram_Definition
4801                      (Access_Definition (Component_Def));
4802          begin
4803             if Present (CD) and then Protected_Present (CD) then
4804                Element_Type :=
4805                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4806             end if;
4807          end;
4808       end if;
4809
4810       --  Constrained array case
4811
4812       if No (T) then
4813          T := Create_Itype (E_Void, P, Related_Id, 'T');
4814       end if;
4815
4816       if Nkind (Def) = N_Constrained_Array_Definition then
4817
4818          --  Establish Implicit_Base as unconstrained base type
4819
4820          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4821
4822          Set_Etype              (Implicit_Base, Implicit_Base);
4823          Set_Scope              (Implicit_Base, Current_Scope);
4824          Set_Has_Delayed_Freeze (Implicit_Base);
4825
4826          --  The constrained array type is a subtype of the unconstrained one
4827
4828          Set_Ekind          (T, E_Array_Subtype);
4829          Init_Size_Align    (T);
4830          Set_Etype          (T, Implicit_Base);
4831          Set_Scope          (T, Current_Scope);
4832          Set_Is_Constrained (T, True);
4833          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4834          Set_Has_Delayed_Freeze (T);
4835
4836          --  Complete setup of implicit base type
4837
4838          Set_First_Index       (Implicit_Base, First_Index (T));
4839          Set_Component_Type    (Implicit_Base, Element_Type);
4840          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4841          Set_Component_Size    (Implicit_Base, Uint_0);
4842          Set_Packed_Array_Type (Implicit_Base, Empty);
4843          Set_Has_Controlled_Component
4844                                (Implicit_Base, Has_Controlled_Component
4845                                                         (Element_Type)
4846                                                  or else Is_Controlled
4847                                                         (Element_Type));
4848          Set_Finalize_Storage_Only
4849                                (Implicit_Base, Finalize_Storage_Only
4850                                                         (Element_Type));
4851
4852       --  Unconstrained array case
4853
4854       else
4855          Set_Ekind                    (T, E_Array_Type);
4856          Init_Size_Align              (T);
4857          Set_Etype                    (T, T);
4858          Set_Scope                    (T, Current_Scope);
4859          Set_Component_Size           (T, Uint_0);
4860          Set_Is_Constrained           (T, False);
4861          Set_First_Index              (T, First (Subtype_Marks (Def)));
4862          Set_Has_Delayed_Freeze       (T, True);
4863          Set_Has_Task                 (T, Has_Task      (Element_Type));
4864          Set_Has_Controlled_Component (T, Has_Controlled_Component
4865                                                         (Element_Type)
4866                                             or else
4867                                           Is_Controlled (Element_Type));
4868          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4869                                                         (Element_Type));
4870       end if;
4871
4872       --  Common attributes for both cases
4873
4874       Set_Component_Type (Base_Type (T), Element_Type);
4875       Set_Packed_Array_Type (T, Empty);
4876
4877       if Aliased_Present (Component_Definition (Def)) then
4878          Check_SPARK_Restriction
4879            ("aliased is not allowed", Component_Definition (Def));
4880          Set_Has_Aliased_Components (Etype (T));
4881       end if;
4882
4883       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4884       --  array type to ensure that objects of this type are initialized.
4885
4886       if Ada_Version >= Ada_2005
4887         and then Can_Never_Be_Null (Element_Type)
4888       then
4889          Set_Can_Never_Be_Null (T);
4890
4891          if Null_Exclusion_Present (Component_Definition (Def))
4892
4893             --  No need to check itypes because in their case this check was
4894             --  done at their point of creation
4895
4896            and then not Is_Itype (Element_Type)
4897          then
4898             Error_Msg_N
4899               ("`NOT NULL` not allowed (null already excluded)",
4900                Subtype_Indication (Component_Definition (Def)));
4901          end if;
4902       end if;
4903
4904       Priv := Private_Component (Element_Type);
4905
4906       if Present (Priv) then
4907
4908          --  Check for circular definitions
4909
4910          if Priv = Any_Type then
4911             Set_Component_Type (Etype (T), Any_Type);
4912
4913          --  There is a gap in the visibility of operations on the composite
4914          --  type only if the component type is defined in a different scope.
4915
4916          elsif Scope (Priv) = Current_Scope then
4917             null;
4918
4919          elsif Is_Limited_Type (Priv) then
4920             Set_Is_Limited_Composite (Etype (T));
4921             Set_Is_Limited_Composite (T);
4922          else
4923             Set_Is_Private_Composite (Etype (T));
4924             Set_Is_Private_Composite (T);
4925          end if;
4926       end if;
4927
4928       --  A syntax error in the declaration itself may lead to an empty index
4929       --  list, in which case do a minimal patch.
4930
4931       if No (First_Index (T)) then
4932          Error_Msg_N ("missing index definition in array type declaration", T);
4933
4934          declare
4935             Indexes : constant List_Id :=
4936                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4937          begin
4938             Set_Discrete_Subtype_Definitions (Def, Indexes);
4939             Set_First_Index (T, First (Indexes));
4940             return;
4941          end;
4942       end if;
4943
4944       --  Create a concatenation operator for the new type. Internal array
4945       --  types created for packed entities do not need such, they are
4946       --  compatible with the user-defined type.
4947
4948       if Number_Dimensions (T) = 1
4949          and then not Is_Packed_Array_Type (T)
4950       then
4951          New_Concatenation_Op (T);
4952       end if;
4953
4954       --  In the case of an unconstrained array the parser has already verified
4955       --  that all the indexes are unconstrained but we still need to make sure
4956       --  that the element type is constrained.
4957
4958       if Is_Indefinite_Subtype (Element_Type) then
4959          Error_Msg_N
4960            ("unconstrained element type in array declaration",
4961             Subtype_Indication (Component_Def));
4962
4963       elsif Is_Abstract_Type (Element_Type) then
4964          Error_Msg_N
4965            ("the type of a component cannot be abstract",
4966             Subtype_Indication (Component_Def));
4967       end if;
4968    end Array_Type_Declaration;
4969
4970    ------------------------------------------------------
4971    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4972    ------------------------------------------------------
4973
4974    function Replace_Anonymous_Access_To_Protected_Subprogram
4975      (N : Node_Id) return Entity_Id
4976    is
4977       Loc : constant Source_Ptr := Sloc (N);
4978
4979       Curr_Scope : constant Scope_Stack_Entry :=
4980                      Scope_Stack.Table (Scope_Stack.Last);
4981
4982       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
4983       Acc  : Node_Id;
4984       Comp : Node_Id;
4985       Decl : Node_Id;
4986       P    : Node_Id;
4987
4988    begin
4989       Set_Is_Internal (Anon);
4990
4991       case Nkind (N) is
4992          when N_Component_Declaration       |
4993            N_Unconstrained_Array_Definition |
4994            N_Constrained_Array_Definition   =>
4995             Comp := Component_Definition (N);
4996             Acc  := Access_Definition (Comp);
4997
4998          when N_Discriminant_Specification =>
4999             Comp := Discriminant_Type (N);
5000             Acc  := Comp;
5001
5002          when N_Parameter_Specification =>
5003             Comp := Parameter_Type (N);
5004             Acc  := Comp;
5005
5006          when N_Access_Function_Definition  =>
5007             Comp := Result_Definition (N);
5008             Acc  := Comp;
5009
5010          when N_Object_Declaration  =>
5011             Comp := Object_Definition (N);
5012             Acc  := Comp;
5013
5014          when N_Function_Specification =>
5015             Comp := Result_Definition (N);
5016             Acc  := Comp;
5017
5018          when others =>
5019             raise Program_Error;
5020       end case;
5021
5022       Decl := Make_Full_Type_Declaration (Loc,
5023                 Defining_Identifier => Anon,
5024                 Type_Definition   =>
5025                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
5026
5027       Mark_Rewrite_Insertion (Decl);
5028
5029       --  Insert the new declaration in the nearest enclosing scope. If the
5030       --  node is a body and N is its return type, the declaration belongs in
5031       --  the enclosing scope.
5032
5033       P := Parent (N);
5034
5035       if Nkind (P) = N_Subprogram_Body
5036         and then Nkind (N) = N_Function_Specification
5037       then
5038          P := Parent (P);
5039       end if;
5040
5041       while Present (P) and then not Has_Declarations (P) loop
5042          P := Parent (P);
5043       end loop;
5044
5045       pragma Assert (Present (P));
5046
5047       if Nkind (P) = N_Package_Specification then
5048          Prepend (Decl, Visible_Declarations (P));
5049       else
5050          Prepend (Decl, Declarations (P));
5051       end if;
5052
5053       --  Replace the anonymous type with an occurrence of the new declaration.
5054       --  In all cases the rewritten node does not have the null-exclusion
5055       --  attribute because (if present) it was already inherited by the
5056       --  anonymous entity (Anon). Thus, in case of components we do not
5057       --  inherit this attribute.
5058
5059       if Nkind (N) = N_Parameter_Specification then
5060          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5061          Set_Etype (Defining_Identifier (N), Anon);
5062          Set_Null_Exclusion_Present (N, False);
5063
5064       elsif Nkind (N) = N_Object_Declaration then
5065          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5066          Set_Etype (Defining_Identifier (N), Anon);
5067
5068       elsif Nkind (N) = N_Access_Function_Definition then
5069          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5070
5071       elsif Nkind (N) = N_Function_Specification then
5072          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5073          Set_Etype (Defining_Unit_Name (N), Anon);
5074
5075       else
5076          Rewrite (Comp,
5077            Make_Component_Definition (Loc,
5078              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
5079       end if;
5080
5081       Mark_Rewrite_Insertion (Comp);
5082
5083       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
5084          Analyze (Decl);
5085
5086       else
5087          --  Temporarily remove the current scope (record or subprogram) from
5088          --  the stack to add the new declarations to the enclosing scope.
5089
5090          Scope_Stack.Decrement_Last;
5091          Analyze (Decl);
5092          Set_Is_Itype (Anon);
5093          Scope_Stack.Append (Curr_Scope);
5094       end if;
5095
5096       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
5097       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
5098       return Anon;
5099    end Replace_Anonymous_Access_To_Protected_Subprogram;
5100
5101    -------------------------------
5102    -- Build_Derived_Access_Type --
5103    -------------------------------
5104
5105    procedure Build_Derived_Access_Type
5106      (N            : Node_Id;
5107       Parent_Type  : Entity_Id;
5108       Derived_Type : Entity_Id)
5109    is
5110       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
5111
5112       Desig_Type      : Entity_Id;
5113       Discr           : Entity_Id;
5114       Discr_Con_Elist : Elist_Id;
5115       Discr_Con_El    : Elmt_Id;
5116       Subt            : Entity_Id;
5117
5118    begin
5119       --  Set the designated type so it is available in case this is an access
5120       --  to a self-referential type, e.g. a standard list type with a next
5121       --  pointer. Will be reset after subtype is built.
5122
5123       Set_Directly_Designated_Type
5124         (Derived_Type, Designated_Type (Parent_Type));
5125
5126       Subt := Process_Subtype (S, N);
5127
5128       if Nkind (S) /= N_Subtype_Indication
5129         and then Subt /= Base_Type (Subt)
5130       then
5131          Set_Ekind (Derived_Type, E_Access_Subtype);
5132       end if;
5133
5134       if Ekind (Derived_Type) = E_Access_Subtype then
5135          declare
5136             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
5137             Ibase      : constant Entity_Id :=
5138                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
5139             Svg_Chars  : constant Name_Id   := Chars (Ibase);
5140             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
5141
5142          begin
5143             Copy_Node (Pbase, Ibase);
5144
5145             Set_Chars             (Ibase, Svg_Chars);
5146             Set_Next_Entity       (Ibase, Svg_Next_E);
5147             Set_Sloc              (Ibase, Sloc (Derived_Type));
5148             Set_Scope             (Ibase, Scope (Derived_Type));
5149             Set_Freeze_Node       (Ibase, Empty);
5150             Set_Is_Frozen         (Ibase, False);
5151             Set_Comes_From_Source (Ibase, False);
5152             Set_Is_First_Subtype  (Ibase, False);
5153
5154             Set_Etype (Ibase, Pbase);
5155             Set_Etype (Derived_Type, Ibase);
5156          end;
5157       end if;
5158
5159       Set_Directly_Designated_Type
5160         (Derived_Type, Designated_Type (Subt));
5161
5162       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
5163       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
5164       Set_Size_Info          (Derived_Type,                     Parent_Type);
5165       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
5166       Set_Depends_On_Private (Derived_Type,
5167                               Has_Private_Component (Derived_Type));
5168       Conditional_Delay      (Derived_Type, Subt);
5169
5170       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
5171       --  that it is not redundant.
5172
5173       if Null_Exclusion_Present (Type_Definition (N)) then
5174          Set_Can_Never_Be_Null (Derived_Type);
5175
5176          if Can_Never_Be_Null (Parent_Type)
5177            and then False
5178          then
5179             Error_Msg_NE
5180               ("`NOT NULL` not allowed (& already excludes null)",
5181                 N, Parent_Type);
5182          end if;
5183
5184       elsif Can_Never_Be_Null (Parent_Type) then
5185          Set_Can_Never_Be_Null (Derived_Type);
5186       end if;
5187
5188       --  Note: we do not copy the Storage_Size_Variable, since we always go to
5189       --  the root type for this information.
5190
5191       --  Apply range checks to discriminants for derived record case
5192       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
5193
5194       Desig_Type := Designated_Type (Derived_Type);
5195       if Is_Composite_Type (Desig_Type)
5196         and then (not Is_Array_Type (Desig_Type))
5197         and then Has_Discriminants (Desig_Type)
5198         and then Base_Type (Desig_Type) /= Desig_Type
5199       then
5200          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
5201          Discr_Con_El := First_Elmt (Discr_Con_Elist);
5202
5203          Discr := First_Discriminant (Base_Type (Desig_Type));
5204          while Present (Discr_Con_El) loop
5205             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
5206             Next_Elmt (Discr_Con_El);
5207             Next_Discriminant (Discr);
5208          end loop;
5209       end if;
5210    end Build_Derived_Access_Type;
5211
5212    ------------------------------
5213    -- Build_Derived_Array_Type --
5214    ------------------------------
5215
5216    procedure Build_Derived_Array_Type
5217      (N            : Node_Id;
5218       Parent_Type  : Entity_Id;
5219       Derived_Type : Entity_Id)
5220    is
5221       Loc           : constant Source_Ptr := Sloc (N);
5222       Tdef          : constant Node_Id    := Type_Definition (N);
5223       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5224       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5225       Implicit_Base : Entity_Id;
5226       New_Indic     : Node_Id;
5227
5228       procedure Make_Implicit_Base;
5229       --  If the parent subtype is constrained, the derived type is a subtype
5230       --  of an implicit base type derived from the parent base.
5231
5232       ------------------------
5233       -- Make_Implicit_Base --
5234       ------------------------
5235
5236       procedure Make_Implicit_Base is
5237       begin
5238          Implicit_Base :=
5239            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5240
5241          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
5242          Set_Etype (Implicit_Base, Parent_Base);
5243
5244          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
5245          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
5246
5247          Set_Has_Delayed_Freeze (Implicit_Base, True);
5248       end Make_Implicit_Base;
5249
5250    --  Start of processing for Build_Derived_Array_Type
5251
5252    begin
5253       if not Is_Constrained (Parent_Type) then
5254          if Nkind (Indic) /= N_Subtype_Indication then
5255             Set_Ekind (Derived_Type, E_Array_Type);
5256
5257             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
5258             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
5259
5260             Set_Has_Delayed_Freeze (Derived_Type, True);
5261
5262          else
5263             Make_Implicit_Base;
5264             Set_Etype (Derived_Type, Implicit_Base);
5265
5266             New_Indic :=
5267               Make_Subtype_Declaration (Loc,
5268                 Defining_Identifier => Derived_Type,
5269                 Subtype_Indication  =>
5270                   Make_Subtype_Indication (Loc,
5271                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
5272                     Constraint => Constraint (Indic)));
5273
5274             Rewrite (N, New_Indic);
5275             Analyze (N);
5276          end if;
5277
5278       else
5279          if Nkind (Indic) /= N_Subtype_Indication then
5280             Make_Implicit_Base;
5281
5282             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
5283             Set_Etype             (Derived_Type, Implicit_Base);
5284             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
5285
5286          else
5287             Error_Msg_N ("illegal constraint on constrained type", Indic);
5288          end if;
5289       end if;
5290
5291       --  If parent type is not a derived type itself, and is declared in
5292       --  closed scope (e.g. a subprogram), then we must explicitly introduce
5293       --  the new type's concatenation operator since Derive_Subprograms
5294       --  will not inherit the parent's operator. If the parent type is
5295       --  unconstrained, the operator is of the unconstrained base type.
5296
5297       if Number_Dimensions (Parent_Type) = 1
5298         and then not Is_Limited_Type (Parent_Type)
5299         and then not Is_Derived_Type (Parent_Type)
5300         and then not Is_Package_Or_Generic_Package
5301                        (Scope (Base_Type (Parent_Type)))
5302       then
5303          if not Is_Constrained (Parent_Type)
5304            and then Is_Constrained (Derived_Type)
5305          then
5306             New_Concatenation_Op (Implicit_Base);
5307          else
5308             New_Concatenation_Op (Derived_Type);
5309          end if;
5310       end if;
5311    end Build_Derived_Array_Type;
5312
5313    -----------------------------------
5314    -- Build_Derived_Concurrent_Type --
5315    -----------------------------------
5316
5317    procedure Build_Derived_Concurrent_Type
5318      (N            : Node_Id;
5319       Parent_Type  : Entity_Id;
5320       Derived_Type : Entity_Id)
5321    is
5322       Loc : constant Source_Ptr := Sloc (N);
5323
5324       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
5325       Corr_Decl        : Node_Id;
5326       Corr_Decl_Needed : Boolean;
5327       --  If the derived type has fewer discriminants than its parent, the
5328       --  corresponding record is also a derived type, in order to account for
5329       --  the bound discriminants. We create a full type declaration for it in
5330       --  this case.
5331
5332       Constraint_Present : constant Boolean :=
5333                              Nkind (Subtype_Indication (Type_Definition (N))) =
5334                                                           N_Subtype_Indication;
5335
5336       D_Constraint   : Node_Id;
5337       New_Constraint : Elist_Id;
5338       Old_Disc       : Entity_Id;
5339       New_Disc       : Entity_Id;
5340       New_N          : Node_Id;
5341
5342    begin
5343       Set_Stored_Constraint (Derived_Type, No_Elist);
5344       Corr_Decl_Needed := False;
5345       Old_Disc := Empty;
5346
5347       if Present (Discriminant_Specifications (N))
5348         and then Constraint_Present
5349       then
5350          Old_Disc := First_Discriminant (Parent_Type);
5351          New_Disc := First (Discriminant_Specifications (N));
5352          while Present (New_Disc) and then Present (Old_Disc) loop
5353             Next_Discriminant (Old_Disc);
5354             Next (New_Disc);
5355          end loop;
5356       end if;
5357
5358       if Present (Old_Disc) and then Expander_Active then
5359
5360          --  The new type has fewer discriminants, so we need to create a new
5361          --  corresponding record, which is derived from the corresponding
5362          --  record of the parent, and has a stored constraint that captures
5363          --  the values of the discriminant constraints. The corresponding
5364          --  record is needed only if expander is active and code generation is
5365          --  enabled.
5366
5367          --  The type declaration for the derived corresponding record has the
5368          --  same discriminant part and constraints as the current declaration.
5369          --  Copy the unanalyzed tree to build declaration.
5370
5371          Corr_Decl_Needed := True;
5372          New_N := Copy_Separate_Tree (N);
5373
5374          Corr_Decl :=
5375            Make_Full_Type_Declaration (Loc,
5376              Defining_Identifier         => Corr_Record,
5377              Discriminant_Specifications =>
5378                 Discriminant_Specifications (New_N),
5379              Type_Definition             =>
5380                Make_Derived_Type_Definition (Loc,
5381                  Subtype_Indication =>
5382                    Make_Subtype_Indication (Loc,
5383                      Subtype_Mark =>
5384                         New_Occurrence_Of
5385                           (Corresponding_Record_Type (Parent_Type), Loc),
5386                      Constraint   =>
5387                        Constraint
5388                          (Subtype_Indication (Type_Definition (New_N))))));
5389       end if;
5390
5391       --  Copy Storage_Size and Relative_Deadline variables if task case
5392
5393       if Is_Task_Type (Parent_Type) then
5394          Set_Storage_Size_Variable (Derived_Type,
5395            Storage_Size_Variable (Parent_Type));
5396          Set_Relative_Deadline_Variable (Derived_Type,
5397            Relative_Deadline_Variable (Parent_Type));
5398       end if;
5399
5400       if Present (Discriminant_Specifications (N)) then
5401          Push_Scope (Derived_Type);
5402          Check_Or_Process_Discriminants (N, Derived_Type);
5403
5404          if Constraint_Present then
5405             New_Constraint :=
5406               Expand_To_Stored_Constraint
5407                 (Parent_Type,
5408                  Build_Discriminant_Constraints
5409                    (Parent_Type,
5410                     Subtype_Indication (Type_Definition (N)), True));
5411          end if;
5412
5413          End_Scope;
5414
5415       elsif Constraint_Present then
5416
5417          --  Build constrained subtype and derive from it
5418
5419          declare
5420             Loc  : constant Source_Ptr := Sloc (N);
5421             Anon : constant Entity_Id :=
5422                      Make_Defining_Identifier (Loc,
5423                        Chars => New_External_Name (Chars (Derived_Type), 'T'));
5424             Decl : Node_Id;
5425
5426          begin
5427             Decl :=
5428               Make_Subtype_Declaration (Loc,
5429                 Defining_Identifier => Anon,
5430                 Subtype_Indication =>
5431                   Subtype_Indication (Type_Definition (N)));
5432             Insert_Before (N, Decl);
5433             Analyze (Decl);
5434
5435             Rewrite (Subtype_Indication (Type_Definition (N)),
5436               New_Occurrence_Of (Anon, Loc));
5437             Set_Analyzed (Derived_Type, False);
5438             Analyze (N);
5439             return;
5440          end;
5441       end if;
5442
5443       --  By default, operations and private data are inherited from parent.
5444       --  However, in the presence of bound discriminants, a new corresponding
5445       --  record will be created, see below.
5446
5447       Set_Has_Discriminants
5448         (Derived_Type, Has_Discriminants         (Parent_Type));
5449       Set_Corresponding_Record_Type
5450         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5451
5452       --  Is_Constrained is set according the parent subtype, but is set to
5453       --  False if the derived type is declared with new discriminants.
5454
5455       Set_Is_Constrained
5456         (Derived_Type,
5457          (Is_Constrained (Parent_Type) or else Constraint_Present)
5458            and then not Present (Discriminant_Specifications (N)));
5459
5460       if Constraint_Present then
5461          if not Has_Discriminants (Parent_Type) then
5462             Error_Msg_N ("untagged parent must have discriminants", N);
5463
5464          elsif Present (Discriminant_Specifications (N)) then
5465
5466             --  Verify that new discriminants are used to constrain old ones
5467
5468             D_Constraint :=
5469               First
5470                 (Constraints
5471                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5472
5473             Old_Disc := First_Discriminant (Parent_Type);
5474
5475             while Present (D_Constraint) loop
5476                if Nkind (D_Constraint) /= N_Discriminant_Association then
5477
5478                   --  Positional constraint. If it is a reference to a new
5479                   --  discriminant, it constrains the corresponding old one.
5480
5481                   if Nkind (D_Constraint) = N_Identifier then
5482                      New_Disc := First_Discriminant (Derived_Type);
5483                      while Present (New_Disc) loop
5484                         exit when Chars (New_Disc) = Chars (D_Constraint);
5485                         Next_Discriminant (New_Disc);
5486                      end loop;
5487
5488                      if Present (New_Disc) then
5489                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5490                      end if;
5491                   end if;
5492
5493                   Next_Discriminant (Old_Disc);
5494
5495                   --  if this is a named constraint, search by name for the old
5496                   --  discriminants constrained by the new one.
5497
5498                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5499
5500                   --  Find new discriminant with that name
5501
5502                   New_Disc := First_Discriminant (Derived_Type);
5503                   while Present (New_Disc) loop
5504                      exit when
5505                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5506                      Next_Discriminant (New_Disc);
5507                   end loop;
5508
5509                   if Present (New_Disc) then
5510
5511                      --  Verify that new discriminant renames some discriminant
5512                      --  of the parent type, and associate the new discriminant
5513                      --  with one or more old ones that it renames.
5514
5515                      declare
5516                         Selector : Node_Id;
5517
5518                      begin
5519                         Selector := First (Selector_Names (D_Constraint));
5520                         while Present (Selector) loop
5521                            Old_Disc := First_Discriminant (Parent_Type);
5522                            while Present (Old_Disc) loop
5523                               exit when Chars (Old_Disc) = Chars (Selector);
5524                               Next_Discriminant (Old_Disc);
5525                            end loop;
5526
5527                            if Present (Old_Disc) then
5528                               Set_Corresponding_Discriminant
5529                                 (New_Disc, Old_Disc);
5530                            end if;
5531
5532                            Next (Selector);
5533                         end loop;
5534                      end;
5535                   end if;
5536                end if;
5537
5538                Next (D_Constraint);
5539             end loop;
5540
5541             New_Disc := First_Discriminant (Derived_Type);
5542             while Present (New_Disc) loop
5543                if No (Corresponding_Discriminant (New_Disc)) then
5544                   Error_Msg_NE
5545                     ("new discriminant& must constrain old one", N, New_Disc);
5546
5547                elsif not
5548                  Subtypes_Statically_Compatible
5549                    (Etype (New_Disc),
5550                     Etype (Corresponding_Discriminant (New_Disc)))
5551                then
5552                   Error_Msg_NE
5553                     ("& not statically compatible with parent discriminant",
5554                       N, New_Disc);
5555                end if;
5556
5557                Next_Discriminant (New_Disc);
5558             end loop;
5559          end if;
5560
5561       elsif Present (Discriminant_Specifications (N)) then
5562          Error_Msg_N
5563            ("missing discriminant constraint in untagged derivation", N);
5564       end if;
5565
5566       --  The entity chain of the derived type includes the new discriminants
5567       --  but shares operations with the parent.
5568
5569       if Present (Discriminant_Specifications (N)) then
5570          Old_Disc := First_Discriminant (Parent_Type);
5571          while Present (Old_Disc) loop
5572             if No (Next_Entity (Old_Disc))
5573               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5574             then
5575                Set_Next_Entity
5576                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5577                exit;
5578             end if;
5579
5580             Next_Discriminant (Old_Disc);
5581          end loop;
5582
5583       else
5584          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5585          if Has_Discriminants (Parent_Type) then
5586             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5587             Set_Discriminant_Constraint (
5588               Derived_Type, Discriminant_Constraint (Parent_Type));
5589          end if;
5590       end if;
5591
5592       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5593
5594       Set_Has_Completion (Derived_Type);
5595
5596       if Corr_Decl_Needed then
5597          Set_Stored_Constraint (Derived_Type, New_Constraint);
5598          Insert_After (N, Corr_Decl);
5599          Analyze (Corr_Decl);
5600          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5601       end if;
5602    end Build_Derived_Concurrent_Type;
5603
5604    ------------------------------------
5605    -- Build_Derived_Enumeration_Type --
5606    ------------------------------------
5607
5608    procedure Build_Derived_Enumeration_Type
5609      (N            : Node_Id;
5610       Parent_Type  : Entity_Id;
5611       Derived_Type : Entity_Id)
5612    is
5613       Loc           : constant Source_Ptr := Sloc (N);
5614       Def           : constant Node_Id    := Type_Definition (N);
5615       Indic         : constant Node_Id    := Subtype_Indication (Def);
5616       Implicit_Base : Entity_Id;
5617       Literal       : Entity_Id;
5618       New_Lit       : Entity_Id;
5619       Literals_List : List_Id;
5620       Type_Decl     : Node_Id;
5621       Hi, Lo        : Node_Id;
5622       Rang_Expr     : Node_Id;
5623
5624    begin
5625       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5626       --  not have explicit literals lists we need to process types derived
5627       --  from them specially. This is handled by Derived_Standard_Character.
5628       --  If the parent type is a generic type, there are no literals either,
5629       --  and we construct the same skeletal representation as for the generic
5630       --  parent type.
5631
5632       if Is_Standard_Character_Type (Parent_Type) then
5633          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5634
5635       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5636          declare
5637             Lo : Node_Id;
5638             Hi : Node_Id;
5639
5640          begin
5641             if Nkind (Indic) /= N_Subtype_Indication then
5642                Lo :=
5643                   Make_Attribute_Reference (Loc,
5644                     Attribute_Name => Name_First,
5645                     Prefix         => New_Reference_To (Derived_Type, Loc));
5646                Set_Etype (Lo, Derived_Type);
5647
5648                Hi :=
5649                   Make_Attribute_Reference (Loc,
5650                     Attribute_Name => Name_Last,
5651                     Prefix         => New_Reference_To (Derived_Type, Loc));
5652                Set_Etype (Hi, Derived_Type);
5653
5654                Set_Scalar_Range (Derived_Type,
5655                   Make_Range (Loc,
5656                     Low_Bound  => Lo,
5657                     High_Bound => Hi));
5658             else
5659
5660                --   Analyze subtype indication and verify compatibility
5661                --   with parent type.
5662
5663                if Base_Type (Process_Subtype (Indic, N)) /=
5664                   Base_Type (Parent_Type)
5665                then
5666                   Error_Msg_N
5667                     ("illegal constraint for formal discrete type", N);
5668                end if;
5669             end if;
5670          end;
5671
5672       else
5673          --  If a constraint is present, analyze the bounds to catch
5674          --  premature usage of the derived literals.
5675
5676          if Nkind (Indic) = N_Subtype_Indication
5677            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5678          then
5679             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5680             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5681          end if;
5682
5683          --  Introduce an implicit base type for the derived type even if there
5684          --  is no constraint attached to it, since this seems closer to the
5685          --  Ada semantics. Build a full type declaration tree for the derived
5686          --  type using the implicit base type as the defining identifier. The
5687          --  build a subtype declaration tree which applies the constraint (if
5688          --  any) have it replace the derived type declaration.
5689
5690          Literal := First_Literal (Parent_Type);
5691          Literals_List := New_List;
5692          while Present (Literal)
5693            and then Ekind (Literal) = E_Enumeration_Literal
5694          loop
5695             --  Literals of the derived type have the same representation as
5696             --  those of the parent type, but this representation can be
5697             --  overridden by an explicit representation clause. Indicate
5698             --  that there is no explicit representation given yet. These
5699             --  derived literals are implicit operations of the new type,
5700             --  and can be overridden by explicit ones.
5701
5702             if Nkind (Literal) = N_Defining_Character_Literal then
5703                New_Lit :=
5704                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5705             else
5706                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5707             end if;
5708
5709             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5710             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5711             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5712             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5713             Set_Alias                (New_Lit, Literal);
5714             Set_Is_Known_Valid       (New_Lit, True);
5715
5716             Append (New_Lit, Literals_List);
5717             Next_Literal (Literal);
5718          end loop;
5719
5720          Implicit_Base :=
5721            Make_Defining_Identifier (Sloc (Derived_Type),
5722              Chars => New_External_Name (Chars (Derived_Type), 'B'));
5723
5724          --  Indicate the proper nature of the derived type. This must be done
5725          --  before analysis of the literals, to recognize cases when a literal
5726          --  may be hidden by a previous explicit function definition (cf.
5727          --  c83031a).
5728
5729          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5730          Set_Etype (Derived_Type, Implicit_Base);
5731
5732          Type_Decl :=
5733            Make_Full_Type_Declaration (Loc,
5734              Defining_Identifier => Implicit_Base,
5735              Discriminant_Specifications => No_List,
5736              Type_Definition =>
5737                Make_Enumeration_Type_Definition (Loc, Literals_List));
5738
5739          Mark_Rewrite_Insertion (Type_Decl);
5740          Insert_Before (N, Type_Decl);
5741          Analyze (Type_Decl);
5742
5743          --  After the implicit base is analyzed its Etype needs to be changed
5744          --  to reflect the fact that it is derived from the parent type which
5745          --  was ignored during analysis. We also set the size at this point.
5746
5747          Set_Etype (Implicit_Base, Parent_Type);
5748
5749          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5750          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5751          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5752
5753          --  Copy other flags from parent type
5754
5755          Set_Has_Non_Standard_Rep
5756                             (Implicit_Base, Has_Non_Standard_Rep
5757                                                            (Parent_Type));
5758          Set_Has_Pragma_Ordered
5759                             (Implicit_Base, Has_Pragma_Ordered
5760                                                            (Parent_Type));
5761          Set_Has_Delayed_Freeze (Implicit_Base);
5762
5763          --  Process the subtype indication including a validation check on the
5764          --  constraint, if any. If a constraint is given, its bounds must be
5765          --  implicitly converted to the new type.
5766
5767          if Nkind (Indic) = N_Subtype_Indication then
5768             declare
5769                R : constant Node_Id :=
5770                      Range_Expression (Constraint (Indic));
5771
5772             begin
5773                if Nkind (R) = N_Range then
5774                   Hi := Build_Scalar_Bound
5775                           (High_Bound (R), Parent_Type, Implicit_Base);
5776                   Lo := Build_Scalar_Bound
5777                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5778
5779                else
5780                   --  Constraint is a Range attribute. Replace with explicit
5781                   --  mention of the bounds of the prefix, which must be a
5782                   --  subtype.
5783
5784                   Analyze (Prefix (R));
5785                   Hi :=
5786                     Convert_To (Implicit_Base,
5787                       Make_Attribute_Reference (Loc,
5788                         Attribute_Name => Name_Last,
5789                         Prefix =>
5790                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5791
5792                   Lo :=
5793                     Convert_To (Implicit_Base,
5794                       Make_Attribute_Reference (Loc,
5795                         Attribute_Name => Name_First,
5796                         Prefix =>
5797                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5798                end if;
5799             end;
5800
5801          else
5802             Hi :=
5803               Build_Scalar_Bound
5804                 (Type_High_Bound (Parent_Type),
5805                  Parent_Type, Implicit_Base);
5806             Lo :=
5807                Build_Scalar_Bound
5808                  (Type_Low_Bound (Parent_Type),
5809                   Parent_Type, Implicit_Base);
5810          end if;
5811
5812          Rang_Expr :=
5813            Make_Range (Loc,
5814              Low_Bound  => Lo,
5815              High_Bound => Hi);
5816
5817          --  If we constructed a default range for the case where no range
5818          --  was given, then the expressions in the range must not freeze
5819          --  since they do not correspond to expressions in the source.
5820
5821          if Nkind (Indic) /= N_Subtype_Indication then
5822             Set_Must_Not_Freeze (Lo);
5823             Set_Must_Not_Freeze (Hi);
5824             Set_Must_Not_Freeze (Rang_Expr);
5825          end if;
5826
5827          Rewrite (N,
5828            Make_Subtype_Declaration (Loc,
5829              Defining_Identifier => Derived_Type,
5830              Subtype_Indication =>
5831                Make_Subtype_Indication (Loc,
5832                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
5833                  Constraint =>
5834                    Make_Range_Constraint (Loc,
5835                      Range_Expression => Rang_Expr))));
5836
5837          Analyze (N);
5838
5839          --  If pragma Discard_Names applies on the first subtype of the parent
5840          --  type, then it must be applied on this subtype as well.
5841
5842          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
5843             Set_Discard_Names (Derived_Type);
5844          end if;
5845
5846          --  Apply a range check. Since this range expression doesn't have an
5847          --  Etype, we have to specifically pass the Source_Typ parameter. Is
5848          --  this right???
5849
5850          if Nkind (Indic) = N_Subtype_Indication then
5851             Apply_Range_Check (Range_Expression (Constraint (Indic)),
5852                                Parent_Type,
5853                                Source_Typ => Entity (Subtype_Mark (Indic)));
5854          end if;
5855       end if;
5856    end Build_Derived_Enumeration_Type;
5857
5858    --------------------------------
5859    -- Build_Derived_Numeric_Type --
5860    --------------------------------
5861
5862    procedure Build_Derived_Numeric_Type
5863      (N            : Node_Id;
5864       Parent_Type  : Entity_Id;
5865       Derived_Type : Entity_Id)
5866    is
5867       Loc           : constant Source_Ptr := Sloc (N);
5868       Tdef          : constant Node_Id    := Type_Definition (N);
5869       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5870       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5871       No_Constraint : constant Boolean    := Nkind (Indic) /=
5872                                                   N_Subtype_Indication;
5873       Implicit_Base : Entity_Id;
5874
5875       Lo : Node_Id;
5876       Hi : Node_Id;
5877
5878    begin
5879       --  Process the subtype indication including a validation check on
5880       --  the constraint if any.
5881
5882       Discard_Node (Process_Subtype (Indic, N));
5883
5884       --  Introduce an implicit base type for the derived type even if there
5885       --  is no constraint attached to it, since this seems closer to the Ada
5886       --  semantics.
5887
5888       Implicit_Base :=
5889         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5890
5891       Set_Etype          (Implicit_Base, Parent_Base);
5892       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
5893       Set_Size_Info      (Implicit_Base,                 Parent_Base);
5894       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
5895       Set_Parent         (Implicit_Base, Parent (Derived_Type));
5896       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
5897
5898       --  Set RM Size for discrete type or decimal fixed-point type
5899       --  Ordinary fixed-point is excluded, why???
5900
5901       if Is_Discrete_Type (Parent_Base)
5902         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
5903       then
5904          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
5905       end if;
5906
5907       Set_Has_Delayed_Freeze (Implicit_Base);
5908
5909       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
5910       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
5911
5912       Set_Scalar_Range (Implicit_Base,
5913         Make_Range (Loc,
5914           Low_Bound  => Lo,
5915           High_Bound => Hi));
5916
5917       if Has_Infinities (Parent_Base) then
5918          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
5919       end if;
5920
5921       --  The Derived_Type, which is the entity of the declaration, is a
5922       --  subtype of the implicit base. Its Ekind is a subtype, even in the
5923       --  absence of an explicit constraint.
5924
5925       Set_Etype (Derived_Type, Implicit_Base);
5926
5927       --  If we did not have a constraint, then the Ekind is set from the
5928       --  parent type (otherwise Process_Subtype has set the bounds)
5929
5930       if No_Constraint then
5931          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
5932       end if;
5933
5934       --  If we did not have a range constraint, then set the range from the
5935       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
5936
5937       if No_Constraint
5938         or else not Has_Range_Constraint (Indic)
5939       then
5940          Set_Scalar_Range (Derived_Type,
5941            Make_Range (Loc,
5942              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
5943              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
5944          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5945
5946          if Has_Infinities (Parent_Type) then
5947             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5948          end if;
5949
5950          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
5951       end if;
5952
5953       Set_Is_Descendent_Of_Address (Derived_Type,
5954         Is_Descendent_Of_Address (Parent_Type));
5955       Set_Is_Descendent_Of_Address (Implicit_Base,
5956         Is_Descendent_Of_Address (Parent_Type));
5957
5958       --  Set remaining type-specific fields, depending on numeric type
5959
5960       if Is_Modular_Integer_Type (Parent_Type) then
5961          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5962
5963          Set_Non_Binary_Modulus
5964            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5965
5966          Set_Is_Known_Valid
5967            (Implicit_Base, Is_Known_Valid (Parent_Base));
5968
5969       elsif Is_Floating_Point_Type (Parent_Type) then
5970
5971          --  Digits of base type is always copied from the digits value of
5972          --  the parent base type, but the digits of the derived type will
5973          --  already have been set if there was a constraint present.
5974
5975          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5976          Set_Float_Rep    (Implicit_Base, Float_Rep    (Parent_Base));
5977
5978          if No_Constraint then
5979             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5980          end if;
5981
5982       elsif Is_Fixed_Point_Type (Parent_Type) then
5983
5984          --  Small of base type and derived type are always copied from the
5985          --  parent base type, since smalls never change. The delta of the
5986          --  base type is also copied from the parent base type. However the
5987          --  delta of the derived type will have been set already if a
5988          --  constraint was present.
5989
5990          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5991          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5992          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5993
5994          if No_Constraint then
5995             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5996          end if;
5997
5998          --  The scale and machine radix in the decimal case are always
5999          --  copied from the parent base type.
6000
6001          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
6002             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
6003             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
6004
6005             Set_Machine_Radix_10
6006               (Derived_Type,  Machine_Radix_10 (Parent_Base));
6007             Set_Machine_Radix_10
6008               (Implicit_Base, Machine_Radix_10 (Parent_Base));
6009
6010             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6011
6012             if No_Constraint then
6013                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
6014
6015             else
6016                --  the analysis of the subtype_indication sets the
6017                --  digits value of the derived type.
6018
6019                null;
6020             end if;
6021          end if;
6022       end if;
6023
6024       --  The type of the bounds is that of the parent type, and they
6025       --  must be converted to the derived type.
6026
6027       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
6028
6029       --  The implicit_base should be frozen when the derived type is frozen,
6030       --  but note that it is used in the conversions of the bounds. For fixed
6031       --  types we delay the determination of the bounds until the proper
6032       --  freezing point. For other numeric types this is rejected by GCC, for
6033       --  reasons that are currently unclear (???), so we choose to freeze the
6034       --  implicit base now. In the case of integers and floating point types
6035       --  this is harmless because subsequent representation clauses cannot
6036       --  affect anything, but it is still baffling that we cannot use the
6037       --  same mechanism for all derived numeric types.
6038
6039       --  There is a further complication: actually *some* representation
6040       --  clauses can affect the implicit base type. Namely, attribute
6041       --  definition clauses for stream-oriented attributes need to set the
6042       --  corresponding TSS entries on the base type, and this normally cannot
6043       --  be done after the base type is frozen, so the circuitry in
6044       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
6045       --  not use Set_TSS in this case.
6046
6047       if Is_Fixed_Point_Type (Parent_Type) then
6048          Conditional_Delay (Implicit_Base, Parent_Type);
6049       else
6050          Freeze_Before (N, Implicit_Base);
6051       end if;
6052    end Build_Derived_Numeric_Type;
6053
6054    --------------------------------
6055    -- Build_Derived_Private_Type --
6056    --------------------------------
6057
6058    procedure Build_Derived_Private_Type
6059      (N             : Node_Id;
6060       Parent_Type   : Entity_Id;
6061       Derived_Type  : Entity_Id;
6062       Is_Completion : Boolean;
6063       Derive_Subps  : Boolean := True)
6064    is
6065       Loc         : constant Source_Ptr := Sloc (N);
6066       Der_Base    : Entity_Id;
6067       Discr       : Entity_Id;
6068       Full_Decl   : Node_Id := Empty;
6069       Full_Der    : Entity_Id;
6070       Full_P      : Entity_Id;
6071       Last_Discr  : Entity_Id;
6072       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
6073       Swapped     : Boolean := False;
6074
6075       procedure Copy_And_Build;
6076       --  Copy derived type declaration, replace parent with its full view,
6077       --  and analyze new declaration.
6078
6079       --------------------
6080       -- Copy_And_Build --
6081       --------------------
6082
6083       procedure Copy_And_Build is
6084          Full_N : Node_Id;
6085
6086       begin
6087          if Ekind (Parent_Type) in Record_Kind
6088            or else
6089              (Ekind (Parent_Type) in Enumeration_Kind
6090                and then not Is_Standard_Character_Type (Parent_Type)
6091                and then not Is_Generic_Type (Root_Type (Parent_Type)))
6092          then
6093             Full_N := New_Copy_Tree (N);
6094             Insert_After (N, Full_N);
6095             Build_Derived_Type (
6096               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
6097
6098          else
6099             Build_Derived_Type (
6100               N, Parent_Type, Full_Der, True, Derive_Subps => False);
6101          end if;
6102       end Copy_And_Build;
6103
6104    --  Start of processing for Build_Derived_Private_Type
6105
6106    begin
6107       if Is_Tagged_Type (Parent_Type) then
6108          Full_P := Full_View (Parent_Type);
6109
6110          --  A type extension of a type with unknown discriminants is an
6111          --  indefinite type that the back-end cannot handle directly.
6112          --  We treat it as a private type, and build a completion that is
6113          --  derived from the full view of the parent, and hopefully has
6114          --  known discriminants.
6115
6116          --  If the full view of the parent type has an underlying record view,
6117          --  use it to generate the underlying record view of this derived type
6118          --  (required for chains of derivations with unknown discriminants).
6119
6120          --  Minor optimization: we avoid the generation of useless underlying
6121          --  record view entities if the private type declaration has unknown
6122          --  discriminants but its corresponding full view has no
6123          --  discriminants.
6124
6125          if Has_Unknown_Discriminants (Parent_Type)
6126            and then Present (Full_P)
6127            and then (Has_Discriminants (Full_P)
6128                       or else Present (Underlying_Record_View (Full_P)))
6129            and then not In_Open_Scopes (Par_Scope)
6130            and then Expander_Active
6131          then
6132             declare
6133                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
6134                New_Ext  : constant Node_Id :=
6135                             Copy_Separate_Tree
6136                               (Record_Extension_Part (Type_Definition (N)));
6137                Decl     : Node_Id;
6138
6139             begin
6140                Build_Derived_Record_Type
6141                  (N, Parent_Type, Derived_Type, Derive_Subps);
6142
6143                --  Build anonymous completion, as a derivation from the full
6144                --  view of the parent. This is not a completion in the usual
6145                --  sense, because the current type is not private.
6146
6147                Decl :=
6148                  Make_Full_Type_Declaration (Loc,
6149                    Defining_Identifier => Full_Der,
6150                    Type_Definition     =>
6151                      Make_Derived_Type_Definition (Loc,
6152                        Subtype_Indication =>
6153                          New_Copy_Tree
6154                            (Subtype_Indication (Type_Definition (N))),
6155                        Record_Extension_Part => New_Ext));
6156
6157                --  If the parent type has an underlying record view, use it
6158                --  here to build the new underlying record view.
6159
6160                if Present (Underlying_Record_View (Full_P)) then
6161                   pragma Assert
6162                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
6163                        = N_Identifier);
6164                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
6165                     Underlying_Record_View (Full_P));
6166                end if;
6167
6168                Install_Private_Declarations (Par_Scope);
6169                Install_Visible_Declarations (Par_Scope);
6170                Insert_Before (N, Decl);
6171
6172                --  Mark entity as an underlying record view before analysis,
6173                --  to avoid generating the list of its primitive operations
6174                --  (which is not really required for this entity) and thus
6175                --  prevent spurious errors associated with missing overriding
6176                --  of abstract primitives (overridden only for Derived_Type).
6177
6178                Set_Ekind (Full_Der, E_Record_Type);
6179                Set_Is_Underlying_Record_View (Full_Der);
6180
6181                Analyze (Decl);
6182
6183                pragma Assert (Has_Discriminants (Full_Der)
6184                  and then not Has_Unknown_Discriminants (Full_Der));
6185
6186                Uninstall_Declarations (Par_Scope);
6187
6188                --  Freeze the underlying record view, to prevent generation of
6189                --  useless dispatching information, which is simply shared with
6190                --  the real derived type.
6191
6192                Set_Is_Frozen (Full_Der);
6193
6194                --  Set up links between real entity and underlying record view
6195
6196                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
6197                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
6198             end;
6199
6200          --  If discriminants are known, build derived record
6201
6202          else
6203             Build_Derived_Record_Type
6204               (N, Parent_Type, Derived_Type, Derive_Subps);
6205          end if;
6206
6207          return;
6208
6209       elsif Has_Discriminants (Parent_Type) then
6210          if Present (Full_View (Parent_Type)) then
6211             if not Is_Completion then
6212
6213                --  Copy declaration for subsequent analysis, to provide a
6214                --  completion for what is a private declaration. Indicate that
6215                --  the full type is internally generated.
6216
6217                Full_Decl := New_Copy_Tree (N);
6218                Full_Der  := New_Copy (Derived_Type);
6219                Set_Comes_From_Source (Full_Decl, False);
6220                Set_Comes_From_Source (Full_Der, False);
6221                Set_Parent (Full_Der, Full_Decl);
6222
6223                Insert_After (N, Full_Decl);
6224
6225             else
6226                --  If this is a completion, the full view being built is itself
6227                --  private. We build a subtype of the parent with the same
6228                --  constraints as this full view, to convey to the back end the
6229                --  constrained components and the size of this subtype. If the
6230                --  parent is constrained, its full view can serve as the
6231                --  underlying full view of the derived type.
6232
6233                if No (Discriminant_Specifications (N)) then
6234                   if Nkind (Subtype_Indication (Type_Definition (N))) =
6235                                                         N_Subtype_Indication
6236                   then
6237                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
6238
6239                   elsif Is_Constrained (Full_View (Parent_Type)) then
6240                      Set_Underlying_Full_View
6241                        (Derived_Type, Full_View (Parent_Type));
6242                   end if;
6243
6244                else
6245                   --  If there are new discriminants, the parent subtype is
6246                   --  constrained by them, but it is not clear how to build
6247                   --  the Underlying_Full_View in this case???
6248
6249                   null;
6250                end if;
6251             end if;
6252          end if;
6253
6254          --  Build partial view of derived type from partial view of parent
6255
6256          Build_Derived_Record_Type
6257            (N, Parent_Type, Derived_Type, Derive_Subps);
6258
6259          if Present (Full_View (Parent_Type)) and then not Is_Completion then
6260             if not In_Open_Scopes (Par_Scope)
6261               or else not In_Same_Source_Unit (N, Parent_Type)
6262             then
6263                --  Swap partial and full views temporarily
6264
6265                Install_Private_Declarations (Par_Scope);
6266                Install_Visible_Declarations (Par_Scope);
6267                Swapped := True;
6268             end if;
6269
6270             --  Build full view of derived type from full view of parent which
6271             --  is now installed. Subprograms have been derived on the partial
6272             --  view, the completion does not derive them anew.
6273
6274             if not Is_Tagged_Type (Parent_Type) then
6275
6276                --  If the parent is itself derived from another private type,
6277                --  installing the private declarations has not affected its
6278                --  privacy status, so use its own full view explicitly.
6279
6280                if Is_Private_Type (Parent_Type) then
6281                   Build_Derived_Record_Type
6282                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
6283                else
6284                   Build_Derived_Record_Type
6285                     (Full_Decl, Parent_Type, Full_Der, False);
6286                end if;
6287
6288             else
6289                --  If full view of parent is tagged, the completion inherits
6290                --  the proper primitive operations.
6291
6292                Set_Defining_Identifier (Full_Decl, Full_Der);
6293                Build_Derived_Record_Type
6294                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
6295             end if;
6296
6297             --  The full declaration has been introduced into the tree and
6298             --  processed in the step above. It should not be analyzed again
6299             --  (when encountered later in the current list of declarations)
6300             --  to prevent spurious name conflicts. The full entity remains
6301             --  invisible.
6302
6303             Set_Analyzed (Full_Decl);
6304
6305             if Swapped then
6306                Uninstall_Declarations (Par_Scope);
6307
6308                if In_Open_Scopes (Par_Scope) then
6309                   Install_Visible_Declarations (Par_Scope);
6310                end if;
6311             end if;
6312
6313             Der_Base := Base_Type (Derived_Type);
6314             Set_Full_View (Derived_Type, Full_Der);
6315             Set_Full_View (Der_Base, Base_Type (Full_Der));
6316
6317             --  Copy the discriminant list from full view to the partial views
6318             --  (base type and its subtype). Gigi requires that the partial and
6319             --  full views have the same discriminants.
6320
6321             --  Note that since the partial view is pointing to discriminants
6322             --  in the full view, their scope will be that of the full view.
6323             --  This might cause some front end problems and need adjustment???
6324
6325             Discr := First_Discriminant (Base_Type (Full_Der));
6326             Set_First_Entity (Der_Base, Discr);
6327
6328             loop
6329                Last_Discr := Discr;
6330                Next_Discriminant (Discr);
6331                exit when No (Discr);
6332             end loop;
6333
6334             Set_Last_Entity (Der_Base, Last_Discr);
6335
6336             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
6337             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
6338             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
6339
6340          else
6341             --  If this is a completion, the derived type stays private and
6342             --  there is no need to create a further full view, except in the
6343             --  unusual case when the derivation is nested within a child unit,
6344             --  see below.
6345
6346             null;
6347          end if;
6348
6349       elsif Present (Full_View (Parent_Type))
6350         and then  Has_Discriminants (Full_View (Parent_Type))
6351       then
6352          if Has_Unknown_Discriminants (Parent_Type)
6353            and then Nkind (Subtype_Indication (Type_Definition (N))) =
6354                                                          N_Subtype_Indication
6355          then
6356             Error_Msg_N
6357               ("cannot constrain type with unknown discriminants",
6358                Subtype_Indication (Type_Definition (N)));
6359             return;
6360          end if;
6361
6362          --  If full view of parent is a record type, build full view as a
6363          --  derivation from the parent's full view. Partial view remains
6364          --  private. For code generation and linking, the full view must have
6365          --  the same public status as the partial one. This full view is only
6366          --  needed if the parent type is in an enclosing scope, so that the
6367          --  full view may actually become visible, e.g. in a child unit. This
6368          --  is both more efficient, and avoids order of freezing problems with
6369          --  the added entities.
6370
6371          if not Is_Private_Type (Full_View (Parent_Type))
6372            and then (In_Open_Scopes (Scope (Parent_Type)))
6373          then
6374             Full_Der :=
6375               Make_Defining_Identifier
6376                 (Sloc (Derived_Type), Chars (Derived_Type));
6377             Set_Is_Itype (Full_Der);
6378             Set_Has_Private_Declaration (Full_Der);
6379             Set_Has_Private_Declaration (Derived_Type);
6380             Set_Associated_Node_For_Itype (Full_Der, N);
6381             Set_Parent (Full_Der, Parent (Derived_Type));
6382             Set_Full_View (Derived_Type, Full_Der);
6383             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6384             Full_P := Full_View (Parent_Type);
6385             Exchange_Declarations (Parent_Type);
6386             Copy_And_Build;
6387             Exchange_Declarations (Full_P);
6388
6389          else
6390             Build_Derived_Record_Type
6391               (N, Full_View (Parent_Type), Derived_Type,
6392                 Derive_Subps => False);
6393          end if;
6394
6395          --  In any case, the primitive operations are inherited from the
6396          --  parent type, not from the internal full view.
6397
6398          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6399
6400          if Derive_Subps then
6401             Derive_Subprograms (Parent_Type, Derived_Type);
6402          end if;
6403
6404       else
6405          --  Untagged type, No discriminants on either view
6406
6407          if Nkind (Subtype_Indication (Type_Definition (N))) =
6408                                                    N_Subtype_Indication
6409          then
6410             Error_Msg_N
6411               ("illegal constraint on type without discriminants", N);
6412          end if;
6413
6414          if Present (Discriminant_Specifications (N))
6415            and then Present (Full_View (Parent_Type))
6416            and then not Is_Tagged_Type (Full_View (Parent_Type))
6417          then
6418             Error_Msg_N ("cannot add discriminants to untagged type", N);
6419          end if;
6420
6421          Set_Stored_Constraint (Derived_Type, No_Elist);
6422          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6423          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6424          Set_Has_Controlled_Component
6425                                (Derived_Type, Has_Controlled_Component
6426                                                              (Parent_Type));
6427
6428          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6429
6430          if not Is_Controlled  (Parent_Type) then
6431             Set_Finalize_Storage_Only
6432               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6433          end if;
6434
6435          --  Construct the implicit full view by deriving from full view of the
6436          --  parent type. In order to get proper visibility, we install the
6437          --  parent scope and its declarations.
6438
6439          --  ??? If the parent is untagged private and its completion is
6440          --  tagged, this mechanism will not work because we cannot derive from
6441          --  the tagged full view unless we have an extension.
6442
6443          if Present (Full_View (Parent_Type))
6444            and then not Is_Tagged_Type (Full_View (Parent_Type))
6445            and then not Is_Completion
6446          then
6447             Full_Der :=
6448               Make_Defining_Identifier
6449                 (Sloc (Derived_Type), Chars (Derived_Type));
6450             Set_Is_Itype (Full_Der);
6451             Set_Has_Private_Declaration (Full_Der);
6452             Set_Has_Private_Declaration (Derived_Type);
6453             Set_Associated_Node_For_Itype (Full_Der, N);
6454             Set_Parent (Full_Der, Parent (Derived_Type));
6455             Set_Full_View (Derived_Type, Full_Der);
6456
6457             if not In_Open_Scopes (Par_Scope) then
6458                Install_Private_Declarations (Par_Scope);
6459                Install_Visible_Declarations (Par_Scope);
6460                Copy_And_Build;
6461                Uninstall_Declarations (Par_Scope);
6462
6463             --  If parent scope is open and in another unit, and parent has a
6464             --  completion, then the derivation is taking place in the visible
6465             --  part of a child unit. In that case retrieve the full view of
6466             --  the parent momentarily.
6467
6468             elsif not In_Same_Source_Unit (N, Parent_Type) then
6469                Full_P := Full_View (Parent_Type);
6470                Exchange_Declarations (Parent_Type);
6471                Copy_And_Build;
6472                Exchange_Declarations (Full_P);
6473
6474             --  Otherwise it is a local derivation
6475
6476             else
6477                Copy_And_Build;
6478             end if;
6479
6480             Set_Scope                (Full_Der, Current_Scope);
6481             Set_Is_First_Subtype     (Full_Der,
6482                                        Is_First_Subtype (Derived_Type));
6483             Set_Has_Size_Clause      (Full_Der, False);
6484             Set_Has_Alignment_Clause (Full_Der, False);
6485             Set_Next_Entity          (Full_Der, Empty);
6486             Set_Has_Delayed_Freeze   (Full_Der);
6487             Set_Is_Frozen            (Full_Der, False);
6488             Set_Freeze_Node          (Full_Der, Empty);
6489             Set_Depends_On_Private   (Full_Der,
6490                                        Has_Private_Component (Full_Der));
6491             Set_Public_Status        (Full_Der);
6492          end if;
6493       end if;
6494
6495       Set_Has_Unknown_Discriminants (Derived_Type,
6496         Has_Unknown_Discriminants (Parent_Type));
6497
6498       if Is_Private_Type (Derived_Type) then
6499          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6500       end if;
6501
6502       if Is_Private_Type (Parent_Type)
6503         and then Base_Type (Parent_Type) = Parent_Type
6504         and then In_Open_Scopes (Scope (Parent_Type))
6505       then
6506          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6507
6508          if Is_Child_Unit (Scope (Current_Scope))
6509            and then Is_Completion
6510            and then In_Private_Part (Current_Scope)
6511            and then Scope (Parent_Type) /= Current_Scope
6512          then
6513             --  This is the unusual case where a type completed by a private
6514             --  derivation occurs within a package nested in a child unit, and
6515             --  the parent is declared in an ancestor. In this case, the full
6516             --  view of the parent type will become visible in the body of
6517             --  the enclosing child, and only then will the current type be
6518             --  possibly non-private. We build a underlying full view that
6519             --  will be installed when the enclosing child body is compiled.
6520
6521             Full_Der :=
6522               Make_Defining_Identifier
6523                 (Sloc (Derived_Type), Chars (Derived_Type));
6524             Set_Is_Itype (Full_Der);
6525             Build_Itype_Reference (Full_Der, N);
6526
6527             --  The full view will be used to swap entities on entry/exit to
6528             --  the body, and must appear in the entity list for the package.
6529
6530             Append_Entity (Full_Der, Scope (Derived_Type));
6531             Set_Has_Private_Declaration (Full_Der);
6532             Set_Has_Private_Declaration (Derived_Type);
6533             Set_Associated_Node_For_Itype (Full_Der, N);
6534             Set_Parent (Full_Der, Parent (Derived_Type));
6535             Full_P := Full_View (Parent_Type);
6536             Exchange_Declarations (Parent_Type);
6537             Copy_And_Build;
6538             Exchange_Declarations (Full_P);
6539             Set_Underlying_Full_View (Derived_Type, Full_Der);
6540          end if;
6541       end if;
6542    end Build_Derived_Private_Type;
6543
6544    -------------------------------
6545    -- Build_Derived_Record_Type --
6546    -------------------------------
6547
6548    --  1. INTRODUCTION
6549
6550    --  Ideally we would like to use the same model of type derivation for
6551    --  tagged and untagged record types. Unfortunately this is not quite
6552    --  possible because the semantics of representation clauses is different
6553    --  for tagged and untagged records under inheritance. Consider the
6554    --  following:
6555
6556    --     type R (...) is [tagged] record ... end record;
6557    --     type T (...) is new R (...) [with ...];
6558
6559    --  The representation clauses for T can specify a completely different
6560    --  record layout from R's. Hence the same component can be placed in two
6561    --  very different positions in objects of type T and R. If R and T are
6562    --  tagged types, representation clauses for T can only specify the layout
6563    --  of non inherited components, thus components that are common in R and T
6564    --  have the same position in objects of type R and T.
6565
6566    --  This has two implications. The first is that the entire tree for R's
6567    --  declaration needs to be copied for T in the untagged case, so that T
6568    --  can be viewed as a record type of its own with its own representation
6569    --  clauses. The second implication is the way we handle discriminants.
6570    --  Specifically, in the untagged case we need a way to communicate to Gigi
6571    --  what are the real discriminants in the record, while for the semantics
6572    --  we need to consider those introduced by the user to rename the
6573    --  discriminants in the parent type. This is handled by introducing the
6574    --  notion of stored discriminants. See below for more.
6575
6576    --  Fortunately the way regular components are inherited can be handled in
6577    --  the same way in tagged and untagged types.
6578
6579    --  To complicate things a bit more the private view of a private extension
6580    --  cannot be handled in the same way as the full view (for one thing the
6581    --  semantic rules are somewhat different). We will explain what differs
6582    --  below.
6583
6584    --  2. DISCRIMINANTS UNDER INHERITANCE
6585
6586    --  The semantic rules governing the discriminants of derived types are
6587    --  quite subtle.
6588
6589    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6590    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6591
6592    --  If parent type has discriminants, then the discriminants that are
6593    --  declared in the derived type are [3.4 (11)]:
6594
6595    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6596    --    there is one;
6597
6598    --  o Otherwise, each discriminant of the parent type (implicitly declared
6599    --    in the same order with the same specifications). In this case, the
6600    --    discriminants are said to be "inherited", or if unknown in the parent
6601    --    are also unknown in the derived type.
6602
6603    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6604
6605    --  o The parent subtype shall be constrained;
6606
6607    --  o If the parent type is not a tagged type, then each discriminant of
6608    --    the derived type shall be used in the constraint defining a parent
6609    --    subtype. [Implementation note: This ensures that the new discriminant
6610    --    can share storage with an existing discriminant.]
6611
6612    --  For the derived type each discriminant of the parent type is either
6613    --  inherited, constrained to equal some new discriminant of the derived
6614    --  type, or constrained to the value of an expression.
6615
6616    --  When inherited or constrained to equal some new discriminant, the
6617    --  parent discriminant and the discriminant of the derived type are said
6618    --  to "correspond".
6619
6620    --  If a discriminant of the parent type is constrained to a specific value
6621    --  in the derived type definition, then the discriminant is said to be
6622    --  "specified" by that derived type definition.
6623
6624    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6625
6626    --  We have spoken about stored discriminants in point 1 (introduction)
6627    --  above. There are two sort of stored discriminants: implicit and
6628    --  explicit. As long as the derived type inherits the same discriminants as
6629    --  the root record type, stored discriminants are the same as regular
6630    --  discriminants, and are said to be implicit. However, if any discriminant
6631    --  in the root type was renamed in the derived type, then the derived
6632    --  type will contain explicit stored discriminants. Explicit stored
6633    --  discriminants are discriminants in addition to the semantically visible
6634    --  discriminants defined for the derived type. Stored discriminants are
6635    --  used by Gigi to figure out what are the physical discriminants in
6636    --  objects of the derived type (see precise definition in einfo.ads).
6637    --  As an example, consider the following:
6638
6639    --           type R  (D1, D2, D3 : Int) is record ... end record;
6640    --           type T1 is new R;
6641    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6642    --           type T3 is new T2;
6643    --           type T4 (Y : Int) is new T3 (Y, 99);
6644
6645    --  The following table summarizes the discriminants and stored
6646    --  discriminants in R and T1 through T4.
6647
6648    --   Type      Discrim     Stored Discrim  Comment
6649    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6650    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6651    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6652    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6653    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6654
6655    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6656    --  find the corresponding discriminant in the parent type, while
6657    --  Original_Record_Component (abbreviated ORC below), the actual physical
6658    --  component that is renamed. Finally the field Is_Completely_Hidden
6659    --  (abbreviated ICH below) is set for all explicit stored discriminants
6660    --  (see einfo.ads for more info). For the above example this gives:
6661
6662    --                 Discrim     CD        ORC     ICH
6663    --                 ^^^^^^^     ^^        ^^^     ^^^
6664    --                 D1 in R    empty     itself    no
6665    --                 D2 in R    empty     itself    no
6666    --                 D3 in R    empty     itself    no
6667
6668    --                 D1 in T1  D1 in R    itself    no
6669    --                 D2 in T1  D2 in R    itself    no
6670    --                 D3 in T1  D3 in R    itself    no
6671
6672    --                 X1 in T2  D3 in T1  D3 in T2   no
6673    --                 X2 in T2  D1 in T1  D1 in T2   no
6674    --                 D1 in T2   empty    itself    yes
6675    --                 D2 in T2   empty    itself    yes
6676    --                 D3 in T2   empty    itself    yes
6677
6678    --                 X1 in T3  X1 in T2  D3 in T3   no
6679    --                 X2 in T3  X2 in T2  D1 in T3   no
6680    --                 D1 in T3   empty    itself    yes
6681    --                 D2 in T3   empty    itself    yes
6682    --                 D3 in T3   empty    itself    yes
6683
6684    --                 Y  in T4  X1 in T3  D3 in T3   no
6685    --                 D1 in T3   empty    itself    yes
6686    --                 D2 in T3   empty    itself    yes
6687    --                 D3 in T3   empty    itself    yes
6688
6689    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6690
6691    --  Type derivation for tagged types is fairly straightforward. If no
6692    --  discriminants are specified by the derived type, these are inherited
6693    --  from the parent. No explicit stored discriminants are ever necessary.
6694    --  The only manipulation that is done to the tree is that of adding a
6695    --  _parent field with parent type and constrained to the same constraint
6696    --  specified for the parent in the derived type definition. For instance:
6697
6698    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6699    --           type T1 is new R with null record;
6700    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6701
6702    --  are changed into:
6703
6704    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6705    --              _parent : R (D1, D2, D3);
6706    --           end record;
6707
6708    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6709    --              _parent : T1 (X2, 88, X1);
6710    --           end record;
6711
6712    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6713    --  ORC and ICH fields are:
6714
6715    --                 Discrim     CD        ORC     ICH
6716    --                 ^^^^^^^     ^^        ^^^     ^^^
6717    --                 D1 in R    empty     itself    no
6718    --                 D2 in R    empty     itself    no
6719    --                 D3 in R    empty     itself    no
6720
6721    --                 D1 in T1  D1 in R    D1 in R   no
6722    --                 D2 in T1  D2 in R    D2 in R   no
6723    --                 D3 in T1  D3 in R    D3 in R   no
6724
6725    --                 X1 in T2  D3 in T1   D3 in R   no
6726    --                 X2 in T2  D1 in T1   D1 in R   no
6727
6728    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6729    --
6730    --  Regardless of whether we dealing with a tagged or untagged type
6731    --  we will transform all derived type declarations of the form
6732    --
6733    --               type T is new R (...) [with ...];
6734    --  or
6735    --               subtype S is R (...);
6736    --               type T is new S [with ...];
6737    --  into
6738    --               type BT is new R [with ...];
6739    --               subtype T is BT (...);
6740    --
6741    --  That is, the base derived type is constrained only if it has no
6742    --  discriminants. The reason for doing this is that GNAT's semantic model
6743    --  assumes that a base type with discriminants is unconstrained.
6744    --
6745    --  Note that, strictly speaking, the above transformation is not always
6746    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6747    --
6748    --       procedure B34011A is
6749    --          type REC (D : integer := 0) is record
6750    --             I : Integer;
6751    --          end record;
6752
6753    --          package P is
6754    --             type T6 is new Rec;
6755    --             function F return T6;
6756    --          end P;
6757
6758    --          use P;
6759    --          package Q6 is
6760    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6761    --          end Q6;
6762    --
6763    --  The definition of Q6.U is illegal. However transforming Q6.U into
6764
6765    --             type BaseU is new T6;
6766    --             subtype U is BaseU (Q6.F.I)
6767
6768    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6769    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6770    --  the transformation described above.
6771
6772    --  There is another instance where the above transformation is incorrect.
6773    --  Consider:
6774
6775    --          package Pack is
6776    --             type Base (D : Integer) is tagged null record;
6777    --             procedure P (X : Base);
6778
6779    --             type Der is new Base (2) with null record;
6780    --             procedure P (X : Der);
6781    --          end Pack;
6782
6783    --  Then the above transformation turns this into
6784
6785    --             type Der_Base is new Base with null record;
6786    --             --  procedure P (X : Base) is implicitly inherited here
6787    --             --  as procedure P (X : Der_Base).
6788
6789    --             subtype Der is Der_Base (2);
6790    --             procedure P (X : Der);
6791    --             --  The overriding of P (X : Der_Base) is illegal since we
6792    --             --  have a parameter conformance problem.
6793
6794    --  To get around this problem, after having semantically processed Der_Base
6795    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6796    --  Discriminant_Constraint from Der so that when parameter conformance is
6797    --  checked when P is overridden, no semantic errors are flagged.
6798
6799    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6800
6801    --  Regardless of whether we are dealing with a tagged or untagged type
6802    --  we will transform all derived type declarations of the form
6803
6804    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6805    --               type T is new R [with ...];
6806    --  into
6807    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6808
6809    --  The reason for such transformation is that it allows us to implement a
6810    --  very clean form of component inheritance as explained below.
6811
6812    --  Note that this transformation is not achieved by direct tree rewriting
6813    --  and manipulation, but rather by redoing the semantic actions that the
6814    --  above transformation will entail. This is done directly in routine
6815    --  Inherit_Components.
6816
6817    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
6818
6819    --  In both tagged and untagged derived types, regular non discriminant
6820    --  components are inherited in the derived type from the parent type. In
6821    --  the absence of discriminants component, inheritance is straightforward
6822    --  as components can simply be copied from the parent.
6823
6824    --  If the parent has discriminants, inheriting components constrained with
6825    --  these discriminants requires caution. Consider the following example:
6826
6827    --      type R  (D1, D2 : Positive) is [tagged] record
6828    --         S : String (D1 .. D2);
6829    --      end record;
6830
6831    --      type T1                is new R        [with null record];
6832    --      type T2 (X : positive) is new R (1, X) [with null record];
6833
6834    --  As explained in 6. above, T1 is rewritten as
6835    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
6836    --  which makes the treatment for T1 and T2 identical.
6837
6838    --  What we want when inheriting S, is that references to D1 and D2 in R are
6839    --  replaced with references to their correct constraints, i.e. D1 and D2 in
6840    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
6841    --  with either discriminant references in the derived type or expressions.
6842    --  This replacement is achieved as follows: before inheriting R's
6843    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
6844    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
6845    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
6846    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
6847    --  by String (1 .. X).
6848
6849    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
6850
6851    --  We explain here the rules governing private type extensions relevant to
6852    --  type derivation. These rules are explained on the following example:
6853
6854    --      type D [(...)] is new A [(...)] with private;      <-- partial view
6855    --      type D [(...)] is new P [(...)] with null record;  <-- full view
6856
6857    --  Type A is called the ancestor subtype of the private extension.
6858    --  Type P is the parent type of the full view of the private extension. It
6859    --  must be A or a type derived from A.
6860
6861    --  The rules concerning the discriminants of private type extensions are
6862    --  [7.3(10-13)]:
6863
6864    --  o If a private extension inherits known discriminants from the ancestor
6865    --    subtype, then the full view shall also inherit its discriminants from
6866    --    the ancestor subtype and the parent subtype of the full view shall be
6867    --    constrained if and only if the ancestor subtype is constrained.
6868
6869    --  o If a partial view has unknown discriminants, then the full view may
6870    --    define a definite or an indefinite subtype, with or without
6871    --    discriminants.
6872
6873    --  o If a partial view has neither known nor unknown discriminants, then
6874    --    the full view shall define a definite subtype.
6875
6876    --  o If the ancestor subtype of a private extension has constrained
6877    --    discriminants, then the parent subtype of the full view shall impose a
6878    --    statically matching constraint on those discriminants.
6879
6880    --  This means that only the following forms of private extensions are
6881    --  allowed:
6882
6883    --      type D is new A with private;      <-- partial view
6884    --      type D is new P with null record;  <-- full view
6885
6886    --  If A has no discriminants than P has no discriminants, otherwise P must
6887    --  inherit A's discriminants.
6888
6889    --      type D is new A (...) with private;      <-- partial view
6890    --      type D is new P (:::) with null record;  <-- full view
6891
6892    --  P must inherit A's discriminants and (...) and (:::) must statically
6893    --  match.
6894
6895    --      subtype A is R (...);
6896    --      type D is new A with private;      <-- partial view
6897    --      type D is new P with null record;  <-- full view
6898
6899    --  P must have inherited R's discriminants and must be derived from A or
6900    --  any of its subtypes.
6901
6902    --      type D (..) is new A with private;              <-- partial view
6903    --      type D (..) is new P [(:::)] with null record;  <-- full view
6904
6905    --  No specific constraints on P's discriminants or constraint (:::).
6906    --  Note that A can be unconstrained, but the parent subtype P must either
6907    --  be constrained or (:::) must be present.
6908
6909    --      type D (..) is new A [(...)] with private;      <-- partial view
6910    --      type D (..) is new P [(:::)] with null record;  <-- full view
6911
6912    --  P's constraints on A's discriminants must statically match those
6913    --  imposed by (...).
6914
6915    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
6916
6917    --  The full view of a private extension is handled exactly as described
6918    --  above. The model chose for the private view of a private extension is
6919    --  the same for what concerns discriminants (i.e. they receive the same
6920    --  treatment as in the tagged case). However, the private view of the
6921    --  private extension always inherits the components of the parent base,
6922    --  without replacing any discriminant reference. Strictly speaking this is
6923    --  incorrect. However, Gigi never uses this view to generate code so this
6924    --  is a purely semantic issue. In theory, a set of transformations similar
6925    --  to those given in 5. and 6. above could be applied to private views of
6926    --  private extensions to have the same model of component inheritance as
6927    --  for non private extensions. However, this is not done because it would
6928    --  further complicate private type processing. Semantically speaking, this
6929    --  leaves us in an uncomfortable situation. As an example consider:
6930
6931    --          package Pack is
6932    --             type R (D : integer) is tagged record
6933    --                S : String (1 .. D);
6934    --             end record;
6935    --             procedure P (X : R);
6936    --             type T is new R (1) with private;
6937    --          private
6938    --             type T is new R (1) with null record;
6939    --          end;
6940
6941    --  This is transformed into:
6942
6943    --          package Pack is
6944    --             type R (D : integer) is tagged record
6945    --                S : String (1 .. D);
6946    --             end record;
6947    --             procedure P (X : R);
6948    --             type T is new R (1) with private;
6949    --          private
6950    --             type BaseT is new R with null record;
6951    --             subtype  T is BaseT (1);
6952    --          end;
6953
6954    --  (strictly speaking the above is incorrect Ada)
6955
6956    --  From the semantic standpoint the private view of private extension T
6957    --  should be flagged as constrained since one can clearly have
6958    --
6959    --             Obj : T;
6960    --
6961    --  in a unit withing Pack. However, when deriving subprograms for the
6962    --  private view of private extension T, T must be seen as unconstrained
6963    --  since T has discriminants (this is a constraint of the current
6964    --  subprogram derivation model). Thus, when processing the private view of
6965    --  a private extension such as T, we first mark T as unconstrained, we
6966    --  process it, we perform program derivation and just before returning from
6967    --  Build_Derived_Record_Type we mark T as constrained.
6968
6969    --  ??? Are there are other uncomfortable cases that we will have to
6970    --      deal with.
6971
6972    --  10. RECORD_TYPE_WITH_PRIVATE complications
6973
6974    --  Types that are derived from a visible record type and have a private
6975    --  extension present other peculiarities. They behave mostly like private
6976    --  types, but if they have primitive operations defined, these will not
6977    --  have the proper signatures for further inheritance, because other
6978    --  primitive operations will use the implicit base that we define for
6979    --  private derivations below. This affect subprogram inheritance (see
6980    --  Derive_Subprograms for details). We also derive the implicit base from
6981    --  the base type of the full view, so that the implicit base is a record
6982    --  type and not another private type, This avoids infinite loops.
6983
6984    procedure Build_Derived_Record_Type
6985      (N            : Node_Id;
6986       Parent_Type  : Entity_Id;
6987       Derived_Type : Entity_Id;
6988       Derive_Subps : Boolean := True)
6989    is
6990       Discriminant_Specs : constant Boolean :=
6991                              Present (Discriminant_Specifications (N));
6992       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
6993       Loc                : constant Source_Ptr := Sloc (N);
6994       Private_Extension  : constant Boolean :=
6995                              Nkind (N) = N_Private_Extension_Declaration;
6996       Assoc_List         : Elist_Id;
6997       Constraint_Present : Boolean;
6998       Constrs            : Elist_Id;
6999       Discrim            : Entity_Id;
7000       Indic              : Node_Id;
7001       Inherit_Discrims   : Boolean := False;
7002       Last_Discrim       : Entity_Id;
7003       New_Base           : Entity_Id;
7004       New_Decl           : Node_Id;
7005       New_Discrs         : Elist_Id;
7006       New_Indic          : Node_Id;
7007       Parent_Base        : Entity_Id;
7008       Save_Etype         : Entity_Id;
7009       Save_Discr_Constr  : Elist_Id;
7010       Save_Next_Entity   : Entity_Id;
7011       Type_Def           : Node_Id;
7012
7013       Discs : Elist_Id := New_Elmt_List;
7014       --  An empty Discs list means that there were no constraints in the
7015       --  subtype indication or that there was an error processing it.
7016
7017    begin
7018       if Ekind (Parent_Type) = E_Record_Type_With_Private
7019         and then Present (Full_View (Parent_Type))
7020         and then Has_Discriminants (Parent_Type)
7021       then
7022          Parent_Base := Base_Type (Full_View (Parent_Type));
7023       else
7024          Parent_Base := Base_Type (Parent_Type);
7025       end if;
7026
7027       --  AI05-0115 : if this is a derivation from a private type in some
7028       --  other scope that may lead to invisible components for the derived
7029       --  type, mark it accordingly.
7030
7031       if Is_Private_Type (Parent_Type) then
7032          if Scope (Parent_Type) = Scope (Derived_Type) then
7033             null;
7034
7035          elsif In_Open_Scopes (Scope (Parent_Type))
7036            and then In_Private_Part (Scope (Parent_Type))
7037          then
7038             null;
7039
7040          else
7041             Set_Has_Private_Ancestor (Derived_Type);
7042          end if;
7043
7044       else
7045          Set_Has_Private_Ancestor
7046            (Derived_Type, Has_Private_Ancestor (Parent_Type));
7047       end if;
7048
7049       --  Before we start the previously documented transformations, here is
7050       --  little fix for size and alignment of tagged types. Normally when we
7051       --  derive type D from type P, we copy the size and alignment of P as the
7052       --  default for D, and in the absence of explicit representation clauses
7053       --  for D, the size and alignment are indeed the same as the parent.
7054
7055       --  But this is wrong for tagged types, since fields may be added, and
7056       --  the default size may need to be larger, and the default alignment may
7057       --  need to be larger.
7058
7059       --  We therefore reset the size and alignment fields in the tagged case.
7060       --  Note that the size and alignment will in any case be at least as
7061       --  large as the parent type (since the derived type has a copy of the
7062       --  parent type in the _parent field)
7063
7064       --  The type is also marked as being tagged here, which is needed when
7065       --  processing components with a self-referential anonymous access type
7066       --  in the call to Check_Anonymous_Access_Components below. Note that
7067       --  this flag is also set later on for completeness.
7068
7069       if Is_Tagged then
7070          Set_Is_Tagged_Type (Derived_Type);
7071          Init_Size_Align    (Derived_Type);
7072       end if;
7073
7074       --  STEP 0a: figure out what kind of derived type declaration we have
7075
7076       if Private_Extension then
7077          Type_Def := N;
7078          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
7079
7080       else
7081          Type_Def := Type_Definition (N);
7082
7083          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7084          --  Parent_Base can be a private type or private extension. However,
7085          --  for tagged types with an extension the newly added fields are
7086          --  visible and hence the Derived_Type is always an E_Record_Type.
7087          --  (except that the parent may have its own private fields).
7088          --  For untagged types we preserve the Ekind of the Parent_Base.
7089
7090          if Present (Record_Extension_Part (Type_Def)) then
7091             Set_Ekind (Derived_Type, E_Record_Type);
7092
7093             --  Create internal access types for components with anonymous
7094             --  access types.
7095
7096             if Ada_Version >= Ada_2005 then
7097                Check_Anonymous_Access_Components
7098                  (N, Derived_Type, Derived_Type,
7099                    Component_List (Record_Extension_Part (Type_Def)));
7100             end if;
7101
7102          else
7103             Set_Ekind (Derived_Type, Ekind (Parent_Base));
7104          end if;
7105       end if;
7106
7107       --  Indic can either be an N_Identifier if the subtype indication
7108       --  contains no constraint or an N_Subtype_Indication if the subtype
7109       --  indication has a constraint.
7110
7111       Indic := Subtype_Indication (Type_Def);
7112       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
7113
7114       --  Check that the type has visible discriminants. The type may be
7115       --  a private type with unknown discriminants whose full view has
7116       --  discriminants which are invisible.
7117
7118       if Constraint_Present then
7119          if not Has_Discriminants (Parent_Base)
7120            or else
7121              (Has_Unknown_Discriminants (Parent_Base)
7122                 and then Is_Private_Type (Parent_Base))
7123          then
7124             Error_Msg_N
7125               ("invalid constraint: type has no discriminant",
7126                  Constraint (Indic));
7127
7128             Constraint_Present := False;
7129             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7130
7131          elsif Is_Constrained (Parent_Type) then
7132             Error_Msg_N
7133                ("invalid constraint: parent type is already constrained",
7134                   Constraint (Indic));
7135
7136             Constraint_Present := False;
7137             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7138          end if;
7139       end if;
7140
7141       --  STEP 0b: If needed, apply transformation given in point 5. above
7142
7143       if not Private_Extension
7144         and then Has_Discriminants (Parent_Type)
7145         and then not Discriminant_Specs
7146         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
7147       then
7148          --  First, we must analyze the constraint (see comment in point 5.)
7149
7150          if Constraint_Present then
7151             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
7152
7153             if Has_Discriminants (Derived_Type)
7154               and then Has_Private_Declaration (Derived_Type)
7155               and then Present (Discriminant_Constraint (Derived_Type))
7156             then
7157                --  Verify that constraints of the full view statically match
7158                --  those given in the partial view.
7159
7160                declare
7161                   C1, C2 : Elmt_Id;
7162
7163                begin
7164                   C1 := First_Elmt (New_Discrs);
7165                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
7166                   while Present (C1) and then Present (C2) loop
7167                      if Fully_Conformant_Expressions (Node (C1), Node (C2))
7168                        or else
7169                          (Is_OK_Static_Expression (Node (C1))
7170                             and then
7171                           Is_OK_Static_Expression (Node (C2))
7172                             and then
7173                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
7174                      then
7175                         null;
7176
7177                      else
7178                         Error_Msg_N (
7179                           "constraint not conformant to previous declaration",
7180                              Node (C1));
7181                      end if;
7182
7183                      Next_Elmt (C1);
7184                      Next_Elmt (C2);
7185                   end loop;
7186                end;
7187             end if;
7188          end if;
7189
7190          --  Insert and analyze the declaration for the unconstrained base type
7191
7192          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
7193
7194          New_Decl :=
7195            Make_Full_Type_Declaration (Loc,
7196               Defining_Identifier => New_Base,
7197               Type_Definition     =>
7198                 Make_Derived_Type_Definition (Loc,
7199                   Abstract_Present      => Abstract_Present (Type_Def),
7200                   Limited_Present       => Limited_Present (Type_Def),
7201                   Subtype_Indication    =>
7202                     New_Occurrence_Of (Parent_Base, Loc),
7203                   Record_Extension_Part =>
7204                     Relocate_Node (Record_Extension_Part (Type_Def)),
7205                   Interface_List        => Interface_List (Type_Def)));
7206
7207          Set_Parent (New_Decl, Parent (N));
7208          Mark_Rewrite_Insertion (New_Decl);
7209          Insert_Before (N, New_Decl);
7210
7211          --  In the extension case, make sure ancestor is frozen appropriately
7212          --  (see also non-discriminated case below).
7213
7214          if Present (Record_Extension_Part (Type_Def))
7215            or else Is_Interface (Parent_Base)
7216          then
7217             Freeze_Before (New_Decl, Parent_Type);
7218          end if;
7219
7220          --  Note that this call passes False for the Derive_Subps parameter
7221          --  because subprogram derivation is deferred until after creating
7222          --  the subtype (see below).
7223
7224          Build_Derived_Type
7225            (New_Decl, Parent_Base, New_Base,
7226             Is_Completion => True, Derive_Subps => False);
7227
7228          --  ??? This needs re-examination to determine whether the
7229          --  above call can simply be replaced by a call to Analyze.
7230
7231          Set_Analyzed (New_Decl);
7232
7233          --  Insert and analyze the declaration for the constrained subtype
7234
7235          if Constraint_Present then
7236             New_Indic :=
7237               Make_Subtype_Indication (Loc,
7238                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7239                 Constraint   => Relocate_Node (Constraint (Indic)));
7240
7241          else
7242             declare
7243                Constr_List : constant List_Id := New_List;
7244                C           : Elmt_Id;
7245                Expr        : Node_Id;
7246
7247             begin
7248                C := First_Elmt (Discriminant_Constraint (Parent_Type));
7249                while Present (C) loop
7250                   Expr := Node (C);
7251
7252                   --  It is safe here to call New_Copy_Tree since
7253                   --  Force_Evaluation was called on each constraint in
7254                   --  Build_Discriminant_Constraints.
7255
7256                   Append (New_Copy_Tree (Expr), To => Constr_List);
7257
7258                   Next_Elmt (C);
7259                end loop;
7260
7261                New_Indic :=
7262                  Make_Subtype_Indication (Loc,
7263                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7264                    Constraint   =>
7265                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
7266             end;
7267          end if;
7268
7269          Rewrite (N,
7270            Make_Subtype_Declaration (Loc,
7271              Defining_Identifier => Derived_Type,
7272              Subtype_Indication  => New_Indic));
7273
7274          Analyze (N);
7275
7276          --  Derivation of subprograms must be delayed until the full subtype
7277          --  has been established, to ensure proper overriding of subprograms
7278          --  inherited by full types. If the derivations occurred as part of
7279          --  the call to Build_Derived_Type above, then the check for type
7280          --  conformance would fail because earlier primitive subprograms
7281          --  could still refer to the full type prior the change to the new
7282          --  subtype and hence would not match the new base type created here.
7283          --  Subprograms are not derived, however, when Derive_Subps is False
7284          --  (since otherwise there could be redundant derivations).
7285
7286          if Derive_Subps then
7287             Derive_Subprograms (Parent_Type, Derived_Type);
7288          end if;
7289
7290          --  For tagged types the Discriminant_Constraint of the new base itype
7291          --  is inherited from the first subtype so that no subtype conformance
7292          --  problem arise when the first subtype overrides primitive
7293          --  operations inherited by the implicit base type.
7294
7295          if Is_Tagged then
7296             Set_Discriminant_Constraint
7297               (New_Base, Discriminant_Constraint (Derived_Type));
7298          end if;
7299
7300          return;
7301       end if;
7302
7303       --  If we get here Derived_Type will have no discriminants or it will be
7304       --  a discriminated unconstrained base type.
7305
7306       --  STEP 1a: perform preliminary actions/checks for derived tagged types
7307
7308       if Is_Tagged then
7309
7310          --  The parent type is frozen for non-private extensions (RM 13.14(7))
7311          --  The declaration of a specific descendant of an interface type
7312          --  freezes the interface type (RM 13.14).
7313
7314          if not Private_Extension or else Is_Interface (Parent_Base) then
7315             Freeze_Before (N, Parent_Type);
7316          end if;
7317
7318          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
7319          --  cannot be declared at a deeper level than its parent type is
7320          --  removed. The check on derivation within a generic body is also
7321          --  relaxed, but there's a restriction that a derived tagged type
7322          --  cannot be declared in a generic body if it's derived directly
7323          --  or indirectly from a formal type of that generic.
7324
7325          if Ada_Version >= Ada_2005 then
7326             if Present (Enclosing_Generic_Body (Derived_Type)) then
7327                declare
7328                   Ancestor_Type : Entity_Id;
7329
7330                begin
7331                   --  Check to see if any ancestor of the derived type is a
7332                   --  formal type.
7333
7334                   Ancestor_Type := Parent_Type;
7335                   while not Is_Generic_Type (Ancestor_Type)
7336                     and then Etype (Ancestor_Type) /= Ancestor_Type
7337                   loop
7338                      Ancestor_Type := Etype (Ancestor_Type);
7339                   end loop;
7340
7341                   --  If the derived type does have a formal type as an
7342                   --  ancestor, then it's an error if the derived type is
7343                   --  declared within the body of the generic unit that
7344                   --  declares the formal type in its generic formal part. It's
7345                   --  sufficient to check whether the ancestor type is declared
7346                   --  inside the same generic body as the derived type (such as
7347                   --  within a nested generic spec), in which case the
7348                   --  derivation is legal. If the formal type is declared
7349                   --  outside of that generic body, then it's guaranteed that
7350                   --  the derived type is declared within the generic body of
7351                   --  the generic unit declaring the formal type.
7352
7353                   if Is_Generic_Type (Ancestor_Type)
7354                     and then Enclosing_Generic_Body (Ancestor_Type) /=
7355                                Enclosing_Generic_Body (Derived_Type)
7356                   then
7357                      Error_Msg_NE
7358                        ("parent type of& must not be descendant of formal type"
7359                           & " of an enclosing generic body",
7360                             Indic, Derived_Type);
7361                   end if;
7362                end;
7363             end if;
7364
7365          elsif Type_Access_Level (Derived_Type) /=
7366                  Type_Access_Level (Parent_Type)
7367            and then not Is_Generic_Type (Derived_Type)
7368          then
7369             if Is_Controlled (Parent_Type) then
7370                Error_Msg_N
7371                  ("controlled type must be declared at the library level",
7372                   Indic);
7373             else
7374                Error_Msg_N
7375                  ("type extension at deeper accessibility level than parent",
7376                   Indic);
7377             end if;
7378
7379          else
7380             declare
7381                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
7382
7383             begin
7384                if Present (GB)
7385                  and then GB /= Enclosing_Generic_Body (Parent_Base)
7386                then
7387                   Error_Msg_NE
7388                     ("parent type of& must not be outside generic body"
7389                        & " (RM 3.9.1(4))",
7390                          Indic, Derived_Type);
7391                end if;
7392             end;
7393          end if;
7394       end if;
7395
7396       --  Ada 2005 (AI-251)
7397
7398       if Ada_Version >= Ada_2005 and then Is_Tagged then
7399
7400          --  "The declaration of a specific descendant of an interface type
7401          --  freezes the interface type" (RM 13.14).
7402
7403          declare
7404             Iface : Node_Id;
7405          begin
7406             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7407                Iface := First (Interface_List (Type_Def));
7408                while Present (Iface) loop
7409                   Freeze_Before (N, Etype (Iface));
7410                   Next (Iface);
7411                end loop;
7412             end if;
7413          end;
7414       end if;
7415
7416       --  STEP 1b : preliminary cleanup of the full view of private types
7417
7418       --  If the type is already marked as having discriminants, then it's the
7419       --  completion of a private type or private extension and we need to
7420       --  retain the discriminants from the partial view if the current
7421       --  declaration has Discriminant_Specifications so that we can verify
7422       --  conformance. However, we must remove any existing components that
7423       --  were inherited from the parent (and attached in Copy_And_Swap)
7424       --  because the full type inherits all appropriate components anyway, and
7425       --  we do not want the partial view's components interfering.
7426
7427       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7428          Discrim := First_Discriminant (Derived_Type);
7429          loop
7430             Last_Discrim := Discrim;
7431             Next_Discriminant (Discrim);
7432             exit when No (Discrim);
7433          end loop;
7434
7435          Set_Last_Entity (Derived_Type, Last_Discrim);
7436
7437       --  In all other cases wipe out the list of inherited components (even
7438       --  inherited discriminants), it will be properly rebuilt here.
7439
7440       else
7441          Set_First_Entity (Derived_Type, Empty);
7442          Set_Last_Entity  (Derived_Type, Empty);
7443       end if;
7444
7445       --  STEP 1c: Initialize some flags for the Derived_Type
7446
7447       --  The following flags must be initialized here so that
7448       --  Process_Discriminants can check that discriminants of tagged types do
7449       --  not have a default initial value and that access discriminants are
7450       --  only specified for limited records. For completeness, these flags are
7451       --  also initialized along with all the other flags below.
7452
7453       --  AI-419: Limitedness is not inherited from an interface parent, so to
7454       --  be limited in that case the type must be explicitly declared as
7455       --  limited. However, task and protected interfaces are always limited.
7456
7457       if Limited_Present (Type_Def) then
7458          Set_Is_Limited_Record (Derived_Type);
7459
7460       elsif Is_Limited_Record (Parent_Type)
7461         or else (Present (Full_View (Parent_Type))
7462                    and then Is_Limited_Record (Full_View (Parent_Type)))
7463       then
7464          if not Is_Interface (Parent_Type)
7465            or else Is_Synchronized_Interface (Parent_Type)
7466            or else Is_Protected_Interface (Parent_Type)
7467            or else Is_Task_Interface (Parent_Type)
7468          then
7469             Set_Is_Limited_Record (Derived_Type);
7470          end if;
7471       end if;
7472
7473       --  STEP 2a: process discriminants of derived type if any
7474
7475       Push_Scope (Derived_Type);
7476
7477       if Discriminant_Specs then
7478          Set_Has_Unknown_Discriminants (Derived_Type, False);
7479
7480          --  The following call initializes fields Has_Discriminants and
7481          --  Discriminant_Constraint, unless we are processing the completion
7482          --  of a private type declaration.
7483
7484          Check_Or_Process_Discriminants (N, Derived_Type);
7485
7486          --  For untagged types, the constraint on the Parent_Type must be
7487          --  present and is used to rename the discriminants.
7488
7489          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7490             Error_Msg_N ("untagged parent must have discriminants", Indic);
7491
7492          elsif not Is_Tagged and then not Constraint_Present then
7493             Error_Msg_N
7494               ("discriminant constraint needed for derived untagged records",
7495                Indic);
7496
7497          --  Otherwise the parent subtype must be constrained unless we have a
7498          --  private extension.
7499
7500          elsif not Constraint_Present
7501            and then not Private_Extension
7502            and then not Is_Constrained (Parent_Type)
7503          then
7504             Error_Msg_N
7505               ("unconstrained type not allowed in this context", Indic);
7506
7507          elsif Constraint_Present then
7508             --  The following call sets the field Corresponding_Discriminant
7509             --  for the discriminants in the Derived_Type.
7510
7511             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7512
7513             --  For untagged types all new discriminants must rename
7514             --  discriminants in the parent. For private extensions new
7515             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7516
7517             Discrim := First_Discriminant (Derived_Type);
7518             while Present (Discrim) loop
7519                if not Is_Tagged
7520                  and then No (Corresponding_Discriminant (Discrim))
7521                then
7522                   Error_Msg_N
7523                     ("new discriminants must constrain old ones", Discrim);
7524
7525                elsif Private_Extension
7526                  and then Present (Corresponding_Discriminant (Discrim))
7527                then
7528                   Error_Msg_N
7529                     ("only static constraints allowed for parent"
7530                      & " discriminants in the partial view", Indic);
7531                   exit;
7532                end if;
7533
7534                --  If a new discriminant is used in the constraint, then its
7535                --  subtype must be statically compatible with the parent
7536                --  discriminant's subtype (3.7(15)).
7537
7538                if Present (Corresponding_Discriminant (Discrim))
7539                  and then
7540                    not Subtypes_Statically_Compatible
7541                          (Etype (Discrim),
7542                           Etype (Corresponding_Discriminant (Discrim)))
7543                then
7544                   Error_Msg_N
7545                     ("subtype must be compatible with parent discriminant",
7546                      Discrim);
7547                end if;
7548
7549                Next_Discriminant (Discrim);
7550             end loop;
7551
7552             --  Check whether the constraints of the full view statically
7553             --  match those imposed by the parent subtype [7.3(13)].
7554
7555             if Present (Stored_Constraint (Derived_Type)) then
7556                declare
7557                   C1, C2 : Elmt_Id;
7558
7559                begin
7560                   C1 := First_Elmt (Discs);
7561                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7562                   while Present (C1) and then Present (C2) loop
7563                      if not
7564                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7565                      then
7566                         Error_Msg_N
7567                           ("not conformant with previous declaration",
7568                            Node (C1));
7569                      end if;
7570
7571                      Next_Elmt (C1);
7572                      Next_Elmt (C2);
7573                   end loop;
7574                end;
7575             end if;
7576          end if;
7577
7578       --  STEP 2b: No new discriminants, inherit discriminants if any
7579
7580       else
7581          if Private_Extension then
7582             Set_Has_Unknown_Discriminants
7583               (Derived_Type,
7584                Has_Unknown_Discriminants (Parent_Type)
7585                  or else Unknown_Discriminants_Present (N));
7586
7587          --  The partial view of the parent may have unknown discriminants,
7588          --  but if the full view has discriminants and the parent type is
7589          --  in scope they must be inherited.
7590
7591          elsif Has_Unknown_Discriminants (Parent_Type)
7592            and then
7593             (not Has_Discriminants (Parent_Type)
7594               or else not In_Open_Scopes (Scope (Parent_Type)))
7595          then
7596             Set_Has_Unknown_Discriminants (Derived_Type);
7597          end if;
7598
7599          if not Has_Unknown_Discriminants (Derived_Type)
7600            and then not Has_Unknown_Discriminants (Parent_Base)
7601            and then Has_Discriminants (Parent_Type)
7602          then
7603             Inherit_Discrims := True;
7604             Set_Has_Discriminants
7605               (Derived_Type, True);
7606             Set_Discriminant_Constraint
7607               (Derived_Type, Discriminant_Constraint (Parent_Base));
7608          end if;
7609
7610          --  The following test is true for private types (remember
7611          --  transformation 5. is not applied to those) and in an error
7612          --  situation.
7613
7614          if Constraint_Present then
7615             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7616          end if;
7617
7618          --  For now mark a new derived type as constrained only if it has no
7619          --  discriminants. At the end of Build_Derived_Record_Type we properly
7620          --  set this flag in the case of private extensions. See comments in
7621          --  point 9. just before body of Build_Derived_Record_Type.
7622
7623          Set_Is_Constrained
7624            (Derived_Type,
7625             not (Inherit_Discrims
7626                    or else Has_Unknown_Discriminants (Derived_Type)));
7627       end if;
7628
7629       --  STEP 3: initialize fields of derived type
7630
7631       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7632       Set_Stored_Constraint (Derived_Type, No_Elist);
7633
7634       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7635       --  but cannot be interfaces
7636
7637       if not Private_Extension
7638          and then Ekind (Derived_Type) /= E_Private_Type
7639          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7640       then
7641          if Interface_Present (Type_Def) then
7642             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7643          end if;
7644
7645          Set_Interfaces (Derived_Type, No_Elist);
7646       end if;
7647
7648       --  Fields inherited from the Parent_Type
7649
7650       Set_Discard_Names
7651         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
7652       Set_Has_Specified_Layout
7653         (Derived_Type, Has_Specified_Layout (Parent_Type));
7654       Set_Is_Limited_Composite
7655         (Derived_Type, Is_Limited_Composite (Parent_Type));
7656       Set_Is_Private_Composite
7657         (Derived_Type, Is_Private_Composite (Parent_Type));
7658
7659       --  Fields inherited from the Parent_Base
7660
7661       Set_Has_Controlled_Component
7662         (Derived_Type, Has_Controlled_Component (Parent_Base));
7663       Set_Has_Non_Standard_Rep
7664         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7665       Set_Has_Primitive_Operations
7666         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7667
7668       --  Fields inherited from the Parent_Base in the non-private case
7669
7670       if Ekind (Derived_Type) = E_Record_Type then
7671          Set_Has_Complex_Representation
7672            (Derived_Type, Has_Complex_Representation (Parent_Base));
7673       end if;
7674
7675       --  Fields inherited from the Parent_Base for record types
7676
7677       if Is_Record_Type (Derived_Type) then
7678
7679          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7680          --  Parent_Base can be a private type or private extension.
7681
7682          if Present (Full_View (Parent_Base)) then
7683             Set_OK_To_Reorder_Components
7684               (Derived_Type,
7685                OK_To_Reorder_Components (Full_View (Parent_Base)));
7686             Set_Reverse_Bit_Order
7687               (Derived_Type, Reverse_Bit_Order (Full_View (Parent_Base)));
7688          else
7689             Set_OK_To_Reorder_Components
7690               (Derived_Type, OK_To_Reorder_Components (Parent_Base));
7691             Set_Reverse_Bit_Order
7692               (Derived_Type, Reverse_Bit_Order (Parent_Base));
7693          end if;
7694       end if;
7695
7696       --  Direct controlled types do not inherit Finalize_Storage_Only flag
7697
7698       if not Is_Controlled (Parent_Type) then
7699          Set_Finalize_Storage_Only
7700            (Derived_Type, Finalize_Storage_Only (Parent_Type));
7701       end if;
7702
7703       --  Set fields for private derived types
7704
7705       if Is_Private_Type (Derived_Type) then
7706          Set_Depends_On_Private (Derived_Type, True);
7707          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7708
7709       --  Inherit fields from non private record types. If this is the
7710       --  completion of a derivation from a private type, the parent itself
7711       --  is private, and the attributes come from its full view, which must
7712       --  be present.
7713
7714       else
7715          if Is_Private_Type (Parent_Base)
7716            and then not Is_Record_Type (Parent_Base)
7717          then
7718             Set_Component_Alignment
7719               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7720             Set_C_Pass_By_Copy
7721               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7722          else
7723             Set_Component_Alignment
7724               (Derived_Type, Component_Alignment (Parent_Base));
7725             Set_C_Pass_By_Copy
7726               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7727          end if;
7728       end if;
7729
7730       --  Set fields for tagged types
7731
7732       if Is_Tagged then
7733          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
7734
7735          --  All tagged types defined in Ada.Finalization are controlled
7736
7737          if Chars (Scope (Derived_Type)) = Name_Finalization
7738            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7739            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7740          then
7741             Set_Is_Controlled (Derived_Type);
7742          else
7743             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7744          end if;
7745
7746          --  Minor optimization: there is no need to generate the class-wide
7747          --  entity associated with an underlying record view.
7748
7749          if not Is_Underlying_Record_View (Derived_Type) then
7750             Make_Class_Wide_Type (Derived_Type);
7751          end if;
7752
7753          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7754
7755          if Has_Discriminants (Derived_Type)
7756            and then Constraint_Present
7757          then
7758             Set_Stored_Constraint
7759               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7760          end if;
7761
7762          if Ada_Version >= Ada_2005 then
7763             declare
7764                Ifaces_List : Elist_Id;
7765
7766             begin
7767                --  Checks rules 3.9.4 (13/2 and 14/2)
7768
7769                if Comes_From_Source (Derived_Type)
7770                  and then not Is_Private_Type (Derived_Type)
7771                  and then Is_Interface (Parent_Type)
7772                  and then not Is_Interface (Derived_Type)
7773                then
7774                   if Is_Task_Interface (Parent_Type) then
7775                      Error_Msg_N
7776                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
7777                         Derived_Type);
7778
7779                   elsif Is_Protected_Interface (Parent_Type) then
7780                      Error_Msg_N
7781                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
7782                         Derived_Type);
7783                   end if;
7784                end if;
7785
7786                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
7787
7788                Check_Interfaces (N, Type_Def);
7789
7790                --  Ada 2005 (AI-251): Collect the list of progenitors that are
7791                --  not already in the parents.
7792
7793                Collect_Interfaces
7794                  (T               => Derived_Type,
7795                   Ifaces_List     => Ifaces_List,
7796                   Exclude_Parents => True);
7797
7798                Set_Interfaces (Derived_Type, Ifaces_List);
7799
7800                --  If the derived type is the anonymous type created for
7801                --  a declaration whose parent has a constraint, propagate
7802                --  the interface list to the source type. This must be done
7803                --  prior to the completion of the analysis of the source type
7804                --  because the components in the extension may contain current
7805                --  instances whose legality depends on some ancestor.
7806
7807                if Is_Itype (Derived_Type) then
7808                   declare
7809                      Def : constant Node_Id :=
7810                        Associated_Node_For_Itype (Derived_Type);
7811                   begin
7812                      if Present (Def)
7813                        and then Nkind (Def) = N_Full_Type_Declaration
7814                      then
7815                         Set_Interfaces
7816                           (Defining_Identifier (Def), Ifaces_List);
7817                      end if;
7818                   end;
7819                end if;
7820             end;
7821          end if;
7822
7823       else
7824          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
7825          Set_Has_Non_Standard_Rep
7826                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
7827       end if;
7828
7829       --  STEP 4: Inherit components from the parent base and constrain them.
7830       --          Apply the second transformation described in point 6. above.
7831
7832       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
7833         or else not Has_Discriminants (Parent_Type)
7834         or else not Is_Constrained (Parent_Type)
7835       then
7836          Constrs := Discs;
7837       else
7838          Constrs := Discriminant_Constraint (Parent_Type);
7839       end if;
7840
7841       Assoc_List :=
7842         Inherit_Components
7843           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
7844
7845       --  STEP 5a: Copy the parent record declaration for untagged types
7846
7847       if not Is_Tagged then
7848
7849          --  Discriminant_Constraint (Derived_Type) has been properly
7850          --  constructed. Save it and temporarily set it to Empty because we
7851          --  do not want the call to New_Copy_Tree below to mess this list.
7852
7853          if Has_Discriminants (Derived_Type) then
7854             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
7855             Set_Discriminant_Constraint (Derived_Type, No_Elist);
7856          else
7857             Save_Discr_Constr := No_Elist;
7858          end if;
7859
7860          --  Save the Etype field of Derived_Type. It is correctly set now,
7861          --  but the call to New_Copy tree may remap it to point to itself,
7862          --  which is not what we want. Ditto for the Next_Entity field.
7863
7864          Save_Etype       := Etype (Derived_Type);
7865          Save_Next_Entity := Next_Entity (Derived_Type);
7866
7867          --  Assoc_List maps all stored discriminants in the Parent_Base to
7868          --  stored discriminants in the Derived_Type. It is fundamental that
7869          --  no types or itypes with discriminants other than the stored
7870          --  discriminants appear in the entities declared inside
7871          --  Derived_Type, since the back end cannot deal with it.
7872
7873          New_Decl :=
7874            New_Copy_Tree
7875              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
7876
7877          --  Restore the fields saved prior to the New_Copy_Tree call
7878          --  and compute the stored constraint.
7879
7880          Set_Etype       (Derived_Type, Save_Etype);
7881          Set_Next_Entity (Derived_Type, Save_Next_Entity);
7882
7883          if Has_Discriminants (Derived_Type) then
7884             Set_Discriminant_Constraint
7885               (Derived_Type, Save_Discr_Constr);
7886             Set_Stored_Constraint
7887               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
7888             Replace_Components (Derived_Type, New_Decl);
7889             Set_Has_Implicit_Dereference
7890               (Derived_Type, Has_Implicit_Dereference (Parent_Type));
7891          end if;
7892
7893          --  Insert the new derived type declaration
7894
7895          Rewrite (N, New_Decl);
7896
7897       --  STEP 5b: Complete the processing for record extensions in generics
7898
7899       --  There is no completion for record extensions declared in the
7900       --  parameter part of a generic, so we need to complete processing for
7901       --  these generic record extensions here. The Record_Type_Definition call
7902       --  will change the Ekind of the components from E_Void to E_Component.
7903
7904       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
7905          Record_Type_Definition (Empty, Derived_Type);
7906
7907       --  STEP 5c: Process the record extension for non private tagged types
7908
7909       elsif not Private_Extension then
7910
7911          --  Add the _parent field in the derived type
7912
7913          Expand_Record_Extension (Derived_Type, Type_Def);
7914
7915          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
7916          --  implemented interfaces if we are in expansion mode
7917
7918          if Expander_Active
7919            and then Has_Interfaces (Derived_Type)
7920          then
7921             Add_Interface_Tag_Components (N, Derived_Type);
7922          end if;
7923
7924          --  Analyze the record extension
7925
7926          Record_Type_Definition
7927            (Record_Extension_Part (Type_Def), Derived_Type);
7928       end if;
7929
7930       End_Scope;
7931
7932       --  Nothing else to do if there is an error in the derivation.
7933       --  An unusual case: the full view may be derived from a type in an
7934       --  instance, when the partial view was used illegally as an actual
7935       --  in that instance, leading to a circular definition.
7936
7937       if Etype (Derived_Type) = Any_Type
7938         or else Etype (Parent_Type) = Derived_Type
7939       then
7940          return;
7941       end if;
7942
7943       --  Set delayed freeze and then derive subprograms, we need to do
7944       --  this in this order so that derived subprograms inherit the
7945       --  derived freeze if necessary.
7946
7947       Set_Has_Delayed_Freeze (Derived_Type);
7948
7949       if Derive_Subps then
7950          Derive_Subprograms (Parent_Type, Derived_Type);
7951       end if;
7952
7953       --  If we have a private extension which defines a constrained derived
7954       --  type mark as constrained here after we have derived subprograms. See
7955       --  comment on point 9. just above the body of Build_Derived_Record_Type.
7956
7957       if Private_Extension and then Inherit_Discrims then
7958          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
7959             Set_Is_Constrained          (Derived_Type, True);
7960             Set_Discriminant_Constraint (Derived_Type, Discs);
7961
7962          elsif Is_Constrained (Parent_Type) then
7963             Set_Is_Constrained
7964               (Derived_Type, True);
7965             Set_Discriminant_Constraint
7966               (Derived_Type, Discriminant_Constraint (Parent_Type));
7967          end if;
7968       end if;
7969
7970       --  Update the class-wide type, which shares the now-completed entity
7971       --  list with its specific type. In case of underlying record views,
7972       --  we do not generate the corresponding class wide entity.
7973
7974       if Is_Tagged
7975         and then not Is_Underlying_Record_View (Derived_Type)
7976       then
7977          Set_First_Entity
7978            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
7979          Set_Last_Entity
7980            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
7981       end if;
7982    end Build_Derived_Record_Type;
7983
7984    ------------------------
7985    -- Build_Derived_Type --
7986    ------------------------
7987
7988    procedure Build_Derived_Type
7989      (N             : Node_Id;
7990       Parent_Type   : Entity_Id;
7991       Derived_Type  : Entity_Id;
7992       Is_Completion : Boolean;
7993       Derive_Subps  : Boolean := True)
7994    is
7995       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
7996
7997    begin
7998       --  Set common attributes
7999
8000       Set_Scope          (Derived_Type, Current_Scope);
8001
8002       Set_Ekind          (Derived_Type, Ekind    (Parent_Base));
8003       Set_Etype          (Derived_Type,           Parent_Base);
8004       Set_Has_Task       (Derived_Type, Has_Task (Parent_Base));
8005
8006       Set_Size_Info      (Derived_Type,                 Parent_Type);
8007       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
8008       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
8009       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
8010
8011       --  If the parent type is a private subtype, the convention on the base
8012       --  type may be set in the private part, and not propagated to the
8013       --  subtype until later, so we obtain the convention from the base type.
8014
8015       Set_Convention     (Derived_Type, Convention     (Parent_Base));
8016
8017       --  Propagate invariant information. The new type has invariants if
8018       --  they are inherited from the parent type, and these invariants can
8019       --  be further inherited, so both flags are set.
8020
8021       if Has_Inheritable_Invariants (Parent_Type) then
8022          Set_Has_Inheritable_Invariants (Derived_Type);
8023          Set_Has_Invariants (Derived_Type);
8024       end if;
8025
8026       --  We similarly inherit predicates
8027
8028       if Has_Predicates (Parent_Type) then
8029          Set_Has_Predicates (Derived_Type);
8030       end if;
8031
8032       --  The derived type inherits the representation clauses of the parent.
8033       --  However, for a private type that is completed by a derivation, there
8034       --  may be operation attributes that have been specified already (stream
8035       --  attributes and External_Tag) and those must be provided. Finally,
8036       --  if the partial view is a private extension, the representation items
8037       --  of the parent have been inherited already, and should not be chained
8038       --  twice to the derived type.
8039
8040       if Is_Tagged_Type (Parent_Type)
8041         and then Present (First_Rep_Item (Derived_Type))
8042       then
8043          --  The existing items are either operational items or items inherited
8044          --  from a private extension declaration.
8045
8046          declare
8047             Rep : Node_Id;
8048             --  Used to iterate over representation items of the derived type
8049
8050             Last_Rep : Node_Id;
8051             --  Last representation item of the (non-empty) representation
8052             --  item list of the derived type.
8053
8054             Found : Boolean := False;
8055
8056          begin
8057             Rep      := First_Rep_Item (Derived_Type);
8058             Last_Rep := Rep;
8059             while Present (Rep) loop
8060                if Rep = First_Rep_Item (Parent_Type) then
8061                   Found := True;
8062                   exit;
8063
8064                else
8065                   Rep := Next_Rep_Item (Rep);
8066
8067                   if Present (Rep) then
8068                      Last_Rep := Rep;
8069                   end if;
8070                end if;
8071             end loop;
8072
8073             --  Here if we either encountered the parent type's first rep
8074             --  item on the derived type's rep item list (in which case
8075             --  Found is True, and we have nothing else to do), or if we
8076             --  reached the last rep item of the derived type, which is
8077             --  Last_Rep, in which case we further chain the parent type's
8078             --  rep items to those of the derived type.
8079
8080             if not Found then
8081                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
8082             end if;
8083          end;
8084
8085       else
8086          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
8087       end if;
8088
8089       case Ekind (Parent_Type) is
8090          when Numeric_Kind =>
8091             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
8092
8093          when Array_Kind =>
8094             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
8095
8096          when E_Record_Type
8097             | E_Record_Subtype
8098             | Class_Wide_Kind  =>
8099             Build_Derived_Record_Type
8100               (N, Parent_Type, Derived_Type, Derive_Subps);
8101             return;
8102
8103          when Enumeration_Kind =>
8104             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
8105
8106          when Access_Kind =>
8107             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
8108
8109          when Incomplete_Or_Private_Kind =>
8110             Build_Derived_Private_Type
8111               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
8112
8113             --  For discriminated types, the derivation includes deriving
8114             --  primitive operations. For others it is done below.
8115
8116             if Is_Tagged_Type (Parent_Type)
8117               or else Has_Discriminants (Parent_Type)
8118               or else (Present (Full_View (Parent_Type))
8119                         and then Has_Discriminants (Full_View (Parent_Type)))
8120             then
8121                return;
8122             end if;
8123
8124          when Concurrent_Kind =>
8125             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
8126
8127          when others =>
8128             raise Program_Error;
8129       end case;
8130
8131       if Etype (Derived_Type) = Any_Type then
8132          return;
8133       end if;
8134
8135       --  Set delayed freeze and then derive subprograms, we need to do this
8136       --  in this order so that derived subprograms inherit the derived freeze
8137       --  if necessary.
8138
8139       Set_Has_Delayed_Freeze (Derived_Type);
8140       if Derive_Subps then
8141          Derive_Subprograms (Parent_Type, Derived_Type);
8142       end if;
8143
8144       Set_Has_Primitive_Operations
8145         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
8146    end Build_Derived_Type;
8147
8148    -----------------------
8149    -- Build_Discriminal --
8150    -----------------------
8151
8152    procedure Build_Discriminal (Discrim : Entity_Id) is
8153       D_Minal : Entity_Id;
8154       CR_Disc : Entity_Id;
8155
8156    begin
8157       --  A discriminal has the same name as the discriminant
8158
8159       D_Minal := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
8160
8161       Set_Ekind     (D_Minal, E_In_Parameter);
8162       Set_Mechanism (D_Minal, Default_Mechanism);
8163       Set_Etype     (D_Minal, Etype (Discrim));
8164       Set_Scope     (D_Minal, Current_Scope);
8165
8166       Set_Discriminal (Discrim, D_Minal);
8167       Set_Discriminal_Link (D_Minal, Discrim);
8168
8169       --  For task types, build at once the discriminants of the corresponding
8170       --  record, which are needed if discriminants are used in entry defaults
8171       --  and in family bounds.
8172
8173       if Is_Concurrent_Type (Current_Scope)
8174         or else Is_Limited_Type (Current_Scope)
8175       then
8176          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
8177
8178          Set_Ekind            (CR_Disc, E_In_Parameter);
8179          Set_Mechanism        (CR_Disc, Default_Mechanism);
8180          Set_Etype            (CR_Disc, Etype (Discrim));
8181          Set_Scope            (CR_Disc, Current_Scope);
8182          Set_Discriminal_Link (CR_Disc, Discrim);
8183          Set_CR_Discriminant  (Discrim, CR_Disc);
8184       end if;
8185    end Build_Discriminal;
8186
8187    ------------------------------------
8188    -- Build_Discriminant_Constraints --
8189    ------------------------------------
8190
8191    function Build_Discriminant_Constraints
8192      (T           : Entity_Id;
8193       Def         : Node_Id;
8194       Derived_Def : Boolean := False) return Elist_Id
8195    is
8196       C        : constant Node_Id := Constraint (Def);
8197       Nb_Discr : constant Nat     := Number_Discriminants (T);
8198
8199       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
8200       --  Saves the expression corresponding to a given discriminant in T
8201
8202       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
8203       --  Return the Position number within array Discr_Expr of a discriminant
8204       --  D within the discriminant list of the discriminated type T.
8205
8206       ------------------
8207       -- Pos_Of_Discr --
8208       ------------------
8209
8210       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
8211          Disc : Entity_Id;
8212
8213       begin
8214          Disc := First_Discriminant (T);
8215          for J in Discr_Expr'Range loop
8216             if Disc = D then
8217                return J;
8218             end if;
8219
8220             Next_Discriminant (Disc);
8221          end loop;
8222
8223          --  Note: Since this function is called on discriminants that are
8224          --  known to belong to the discriminated type, falling through the
8225          --  loop with no match signals an internal compiler error.
8226
8227          raise Program_Error;
8228       end Pos_Of_Discr;
8229
8230       --  Declarations local to Build_Discriminant_Constraints
8231
8232       Discr : Entity_Id;
8233       E     : Entity_Id;
8234       Elist : constant Elist_Id := New_Elmt_List;
8235
8236       Constr   : Node_Id;
8237       Expr     : Node_Id;
8238       Id       : Node_Id;
8239       Position : Nat;
8240       Found    : Boolean;
8241
8242       Discrim_Present : Boolean := False;
8243
8244    --  Start of processing for Build_Discriminant_Constraints
8245
8246    begin
8247       --  The following loop will process positional associations only.
8248       --  For a positional association, the (single) discriminant is
8249       --  implicitly specified by position, in textual order (RM 3.7.2).
8250
8251       Discr  := First_Discriminant (T);
8252       Constr := First (Constraints (C));
8253       for D in Discr_Expr'Range loop
8254          exit when Nkind (Constr) = N_Discriminant_Association;
8255
8256          if No (Constr) then
8257             Error_Msg_N ("too few discriminants given in constraint", C);
8258             return New_Elmt_List;
8259
8260          elsif Nkind (Constr) = N_Range
8261            or else (Nkind (Constr) = N_Attribute_Reference
8262                      and then
8263                     Attribute_Name (Constr) = Name_Range)
8264          then
8265             Error_Msg_N
8266               ("a range is not a valid discriminant constraint", Constr);
8267             Discr_Expr (D) := Error;
8268
8269          else
8270             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
8271             Discr_Expr (D) := Constr;
8272          end if;
8273
8274          Next_Discriminant (Discr);
8275          Next (Constr);
8276       end loop;
8277
8278       if No (Discr) and then Present (Constr) then
8279          Error_Msg_N ("too many discriminants given in constraint", Constr);
8280          return New_Elmt_List;
8281       end if;
8282
8283       --  Named associations can be given in any order, but if both positional
8284       --  and named associations are used in the same discriminant constraint,
8285       --  then positional associations must occur first, at their normal
8286       --  position. Hence once a named association is used, the rest of the
8287       --  discriminant constraint must use only named associations.
8288
8289       while Present (Constr) loop
8290
8291          --  Positional association forbidden after a named association
8292
8293          if Nkind (Constr) /= N_Discriminant_Association then
8294             Error_Msg_N ("positional association follows named one", Constr);
8295             return New_Elmt_List;
8296
8297          --  Otherwise it is a named association
8298
8299          else
8300             --  E records the type of the discriminants in the named
8301             --  association. All the discriminants specified in the same name
8302             --  association must have the same type.
8303
8304             E := Empty;
8305
8306             --  Search the list of discriminants in T to see if the simple name
8307             --  given in the constraint matches any of them.
8308
8309             Id := First (Selector_Names (Constr));
8310             while Present (Id) loop
8311                Found := False;
8312
8313                --  If Original_Discriminant is present, we are processing a
8314                --  generic instantiation and this is an instance node. We need
8315                --  to find the name of the corresponding discriminant in the
8316                --  actual record type T and not the name of the discriminant in
8317                --  the generic formal. Example:
8318
8319                --    generic
8320                --       type G (D : int) is private;
8321                --    package P is
8322                --       subtype W is G (D => 1);
8323                --    end package;
8324                --    type Rec (X : int) is record ... end record;
8325                --    package Q is new P (G => Rec);
8326
8327                --  At the point of the instantiation, formal type G is Rec
8328                --  and therefore when reanalyzing "subtype W is G (D => 1);"
8329                --  which really looks like "subtype W is Rec (D => 1);" at
8330                --  the point of instantiation, we want to find the discriminant
8331                --  that corresponds to D in Rec, i.e. X.
8332
8333                if Present (Original_Discriminant (Id))
8334                  and then In_Instance
8335                then
8336                   Discr := Find_Corresponding_Discriminant (Id, T);
8337                   Found := True;
8338
8339                else
8340                   Discr := First_Discriminant (T);
8341                   while Present (Discr) loop
8342                      if Chars (Discr) = Chars (Id) then
8343                         Found := True;
8344                         exit;
8345                      end if;
8346
8347                      Next_Discriminant (Discr);
8348                   end loop;
8349
8350                   if not Found then
8351                      Error_Msg_N ("& does not match any discriminant", Id);
8352                      return New_Elmt_List;
8353
8354                   --  If the parent type is a generic formal, preserve the
8355                   --  name of the discriminant for subsequent instances.
8356                   --  see comment at the beginning of this if statement.
8357
8358                   elsif Is_Generic_Type (Root_Type (T)) then
8359                      Set_Original_Discriminant (Id, Discr);
8360                   end if;
8361                end if;
8362
8363                Position := Pos_Of_Discr (T, Discr);
8364
8365                if Present (Discr_Expr (Position)) then
8366                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
8367
8368                else
8369                   --  Each discriminant specified in the same named association
8370                   --  must be associated with a separate copy of the
8371                   --  corresponding expression.
8372
8373                   if Present (Next (Id)) then
8374                      Expr := New_Copy_Tree (Expression (Constr));
8375                      Set_Parent (Expr, Parent (Expression (Constr)));
8376                   else
8377                      Expr := Expression (Constr);
8378                   end if;
8379
8380                   Discr_Expr (Position) := Expr;
8381                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
8382                end if;
8383
8384                --  A discriminant association with more than one discriminant
8385                --  name is only allowed if the named discriminants are all of
8386                --  the same type (RM 3.7.1(8)).
8387
8388                if E = Empty then
8389                   E := Base_Type (Etype (Discr));
8390
8391                elsif Base_Type (Etype (Discr)) /= E then
8392                   Error_Msg_N
8393                     ("all discriminants in an association " &
8394                      "must have the same type", Id);
8395                end if;
8396
8397                Next (Id);
8398             end loop;
8399          end if;
8400
8401          Next (Constr);
8402       end loop;
8403
8404       --  A discriminant constraint must provide exactly one value for each
8405       --  discriminant of the type (RM 3.7.1(8)).
8406
8407       for J in Discr_Expr'Range loop
8408          if No (Discr_Expr (J)) then
8409             Error_Msg_N ("too few discriminants given in constraint", C);
8410             return New_Elmt_List;
8411          end if;
8412       end loop;
8413
8414       --  Determine if there are discriminant expressions in the constraint
8415
8416       for J in Discr_Expr'Range loop
8417          if Denotes_Discriminant
8418               (Discr_Expr (J), Check_Concurrent => True)
8419          then
8420             Discrim_Present := True;
8421          end if;
8422       end loop;
8423
8424       --  Build an element list consisting of the expressions given in the
8425       --  discriminant constraint and apply the appropriate checks. The list
8426       --  is constructed after resolving any named discriminant associations
8427       --  and therefore the expressions appear in the textual order of the
8428       --  discriminants.
8429
8430       Discr := First_Discriminant (T);
8431       for J in Discr_Expr'Range loop
8432          if Discr_Expr (J) /= Error then
8433             Append_Elmt (Discr_Expr (J), Elist);
8434
8435             --  If any of the discriminant constraints is given by a
8436             --  discriminant and we are in a derived type declaration we
8437             --  have a discriminant renaming. Establish link between new
8438             --  and old discriminant.
8439
8440             if Denotes_Discriminant (Discr_Expr (J)) then
8441                if Derived_Def then
8442                   Set_Corresponding_Discriminant
8443                     (Entity (Discr_Expr (J)), Discr);
8444                end if;
8445
8446             --  Force the evaluation of non-discriminant expressions.
8447             --  If we have found a discriminant in the constraint 3.4(26)
8448             --  and 3.8(18) demand that no range checks are performed are
8449             --  after evaluation. If the constraint is for a component
8450             --  definition that has a per-object constraint, expressions are
8451             --  evaluated but not checked either. In all other cases perform
8452             --  a range check.
8453
8454             else
8455                if Discrim_Present then
8456                   null;
8457
8458                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8459                  and then
8460                    Has_Per_Object_Constraint
8461                      (Defining_Identifier (Parent (Parent (Def))))
8462                then
8463                   null;
8464
8465                elsif Is_Access_Type (Etype (Discr)) then
8466                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8467
8468                else
8469                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8470                end if;
8471
8472                Force_Evaluation (Discr_Expr (J));
8473             end if;
8474
8475             --  Check that the designated type of an access discriminant's
8476             --  expression is not a class-wide type unless the discriminant's
8477             --  designated type is also class-wide.
8478
8479             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8480               and then not Is_Class_Wide_Type
8481                          (Designated_Type (Etype (Discr)))
8482               and then Etype (Discr_Expr (J)) /= Any_Type
8483               and then Is_Class_Wide_Type
8484                          (Designated_Type (Etype (Discr_Expr (J))))
8485             then
8486                Wrong_Type (Discr_Expr (J), Etype (Discr));
8487
8488             elsif Is_Access_Type (Etype (Discr))
8489               and then not Is_Access_Constant (Etype (Discr))
8490               and then Is_Access_Type (Etype (Discr_Expr (J)))
8491               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8492             then
8493                Error_Msg_NE
8494                  ("constraint for discriminant& must be access to variable",
8495                     Def, Discr);
8496             end if;
8497          end if;
8498
8499          Next_Discriminant (Discr);
8500       end loop;
8501
8502       return Elist;
8503    end Build_Discriminant_Constraints;
8504
8505    ---------------------------------
8506    -- Build_Discriminated_Subtype --
8507    ---------------------------------
8508
8509    procedure Build_Discriminated_Subtype
8510      (T           : Entity_Id;
8511       Def_Id      : Entity_Id;
8512       Elist       : Elist_Id;
8513       Related_Nod : Node_Id;
8514       For_Access  : Boolean := False)
8515    is
8516       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8517       Constrained : constant Boolean :=
8518                       (Has_Discrs
8519                          and then not Is_Empty_Elmt_List (Elist)
8520                          and then not Is_Class_Wide_Type (T))
8521                         or else Is_Constrained (T);
8522
8523    begin
8524       if Ekind (T) = E_Record_Type then
8525          if For_Access then
8526             Set_Ekind (Def_Id, E_Private_Subtype);
8527             Set_Is_For_Access_Subtype (Def_Id, True);
8528          else
8529             Set_Ekind (Def_Id, E_Record_Subtype);
8530          end if;
8531
8532          --  Inherit preelaboration flag from base, for types for which it
8533          --  may have been set: records, private types, protected types.
8534
8535          Set_Known_To_Have_Preelab_Init
8536            (Def_Id, Known_To_Have_Preelab_Init (T));
8537
8538       elsif Ekind (T) = E_Task_Type then
8539          Set_Ekind (Def_Id, E_Task_Subtype);
8540
8541       elsif Ekind (T) = E_Protected_Type then
8542          Set_Ekind (Def_Id, E_Protected_Subtype);
8543          Set_Known_To_Have_Preelab_Init
8544            (Def_Id, Known_To_Have_Preelab_Init (T));
8545
8546       elsif Is_Private_Type (T) then
8547          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8548          Set_Known_To_Have_Preelab_Init
8549            (Def_Id, Known_To_Have_Preelab_Init (T));
8550
8551       elsif Is_Class_Wide_Type (T) then
8552          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8553
8554       else
8555          --  Incomplete type. Attach subtype to list of dependents, to be
8556          --  completed with full view of parent type,  unless is it the
8557          --  designated subtype of a record component within an init_proc.
8558          --  This last case arises for a component of an access type whose
8559          --  designated type is incomplete (e.g. a Taft Amendment type).
8560          --  The designated subtype is within an inner scope, and needs no
8561          --  elaboration, because only the access type is needed in the
8562          --  initialization procedure.
8563
8564          Set_Ekind (Def_Id, Ekind (T));
8565
8566          if For_Access and then Within_Init_Proc then
8567             null;
8568          else
8569             Append_Elmt (Def_Id, Private_Dependents (T));
8570          end if;
8571       end if;
8572
8573       Set_Etype             (Def_Id, T);
8574       Init_Size_Align       (Def_Id);
8575       Set_Has_Discriminants (Def_Id, Has_Discrs);
8576       Set_Is_Constrained    (Def_Id, Constrained);
8577
8578       Set_First_Entity      (Def_Id, First_Entity   (T));
8579       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8580       Set_Has_Implicit_Dereference
8581                             (Def_Id, Has_Implicit_Dereference (T));
8582
8583       --  If the subtype is the completion of a private declaration, there may
8584       --  have been representation clauses for the partial view, and they must
8585       --  be preserved. Build_Derived_Type chains the inherited clauses with
8586       --  the ones appearing on the extension. If this comes from a subtype
8587       --  declaration, all clauses are inherited.
8588
8589       if No (First_Rep_Item (Def_Id)) then
8590          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8591       end if;
8592
8593       if Is_Tagged_Type (T) then
8594          Set_Is_Tagged_Type (Def_Id);
8595          Make_Class_Wide_Type (Def_Id);
8596       end if;
8597
8598       Set_Stored_Constraint (Def_Id, No_Elist);
8599
8600       if Has_Discrs then
8601          Set_Discriminant_Constraint (Def_Id, Elist);
8602          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8603       end if;
8604
8605       if Is_Tagged_Type (T) then
8606
8607          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8608          --  concurrent record type (which has the list of primitive
8609          --  operations).
8610
8611          if Ada_Version >= Ada_2005
8612            and then Is_Concurrent_Type (T)
8613          then
8614             Set_Corresponding_Record_Type (Def_Id,
8615                Corresponding_Record_Type (T));
8616          else
8617             Set_Direct_Primitive_Operations (Def_Id,
8618               Direct_Primitive_Operations (T));
8619          end if;
8620
8621          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8622       end if;
8623
8624       --  Subtypes introduced by component declarations do not need to be
8625       --  marked as delayed, and do not get freeze nodes, because the semantics
8626       --  verifies that the parents of the subtypes are frozen before the
8627       --  enclosing record is frozen.
8628
8629       if not Is_Type (Scope (Def_Id)) then
8630          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8631
8632          if Is_Private_Type (T)
8633            and then Present (Full_View (T))
8634          then
8635             Conditional_Delay (Def_Id, Full_View (T));
8636          else
8637             Conditional_Delay (Def_Id, T);
8638          end if;
8639       end if;
8640
8641       if Is_Record_Type (T) then
8642          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8643
8644          if Has_Discrs
8645             and then not Is_Empty_Elmt_List (Elist)
8646             and then not For_Access
8647          then
8648             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8649          elsif not For_Access then
8650             Set_Cloned_Subtype (Def_Id, T);
8651          end if;
8652       end if;
8653    end Build_Discriminated_Subtype;
8654
8655    ---------------------------
8656    -- Build_Itype_Reference --
8657    ---------------------------
8658
8659    procedure Build_Itype_Reference
8660      (Ityp : Entity_Id;
8661       Nod  : Node_Id)
8662    is
8663       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8664    begin
8665
8666       --  Itype references are only created for use by the back-end
8667
8668       if Inside_A_Generic then
8669          return;
8670       else
8671          Set_Itype (IR, Ityp);
8672          Insert_After (Nod, IR);
8673       end if;
8674    end Build_Itype_Reference;
8675
8676    ------------------------
8677    -- Build_Scalar_Bound --
8678    ------------------------
8679
8680    function Build_Scalar_Bound
8681      (Bound : Node_Id;
8682       Par_T : Entity_Id;
8683       Der_T : Entity_Id) return Node_Id
8684    is
8685       New_Bound : Entity_Id;
8686
8687    begin
8688       --  Note: not clear why this is needed, how can the original bound
8689       --  be unanalyzed at this point? and if it is, what business do we
8690       --  have messing around with it? and why is the base type of the
8691       --  parent type the right type for the resolution. It probably is
8692       --  not! It is OK for the new bound we are creating, but not for
8693       --  the old one??? Still if it never happens, no problem!
8694
8695       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8696
8697       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8698          New_Bound := New_Copy (Bound);
8699          Set_Etype (New_Bound, Der_T);
8700          Set_Analyzed (New_Bound);
8701
8702       elsif Is_Entity_Name (Bound) then
8703          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8704
8705       --  The following is almost certainly wrong. What business do we have
8706       --  relocating a node (Bound) that is presumably still attached to
8707       --  the tree elsewhere???
8708
8709       else
8710          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8711       end if;
8712
8713       Set_Etype (New_Bound, Der_T);
8714       return New_Bound;
8715    end Build_Scalar_Bound;
8716
8717    --------------------------------
8718    -- Build_Underlying_Full_View --
8719    --------------------------------
8720
8721    procedure Build_Underlying_Full_View
8722      (N   : Node_Id;
8723       Typ : Entity_Id;
8724       Par : Entity_Id)
8725    is
8726       Loc  : constant Source_Ptr := Sloc (N);
8727       Subt : constant Entity_Id :=
8728                Make_Defining_Identifier
8729                  (Loc, New_External_Name (Chars (Typ), 'S'));
8730
8731       Constr : Node_Id;
8732       Indic  : Node_Id;
8733       C      : Node_Id;
8734       Id     : Node_Id;
8735
8736       procedure Set_Discriminant_Name (Id : Node_Id);
8737       --  If the derived type has discriminants, they may rename discriminants
8738       --  of the parent. When building the full view of the parent, we need to
8739       --  recover the names of the original discriminants if the constraint is
8740       --  given by named associations.
8741
8742       ---------------------------
8743       -- Set_Discriminant_Name --
8744       ---------------------------
8745
8746       procedure Set_Discriminant_Name (Id : Node_Id) is
8747          Disc : Entity_Id;
8748
8749       begin
8750          Set_Original_Discriminant (Id, Empty);
8751
8752          if Has_Discriminants (Typ) then
8753             Disc := First_Discriminant (Typ);
8754             while Present (Disc) loop
8755                if Chars (Disc) = Chars (Id)
8756                  and then Present (Corresponding_Discriminant (Disc))
8757                then
8758                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
8759                end if;
8760                Next_Discriminant (Disc);
8761             end loop;
8762          end if;
8763       end Set_Discriminant_Name;
8764
8765    --  Start of processing for Build_Underlying_Full_View
8766
8767    begin
8768       if Nkind (N) = N_Full_Type_Declaration then
8769          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
8770
8771       elsif Nkind (N) = N_Subtype_Declaration then
8772          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
8773
8774       elsif Nkind (N) = N_Component_Declaration then
8775          Constr :=
8776            New_Copy_Tree
8777              (Constraint (Subtype_Indication (Component_Definition (N))));
8778
8779       else
8780          raise Program_Error;
8781       end if;
8782
8783       C := First (Constraints (Constr));
8784       while Present (C) loop
8785          if Nkind (C) = N_Discriminant_Association then
8786             Id := First (Selector_Names (C));
8787             while Present (Id) loop
8788                Set_Discriminant_Name (Id);
8789                Next (Id);
8790             end loop;
8791          end if;
8792
8793          Next (C);
8794       end loop;
8795
8796       Indic :=
8797         Make_Subtype_Declaration (Loc,
8798           Defining_Identifier => Subt,
8799           Subtype_Indication  =>
8800             Make_Subtype_Indication (Loc,
8801               Subtype_Mark => New_Reference_To (Par, Loc),
8802               Constraint   => New_Copy_Tree (Constr)));
8803
8804       --  If this is a component subtype for an outer itype, it is not
8805       --  a list member, so simply set the parent link for analysis: if
8806       --  the enclosing type does not need to be in a declarative list,
8807       --  neither do the components.
8808
8809       if Is_List_Member (N)
8810         and then Nkind (N) /= N_Component_Declaration
8811       then
8812          Insert_Before (N, Indic);
8813       else
8814          Set_Parent (Indic, Parent (N));
8815       end if;
8816
8817       Analyze (Indic);
8818       Set_Underlying_Full_View (Typ, Full_View (Subt));
8819    end Build_Underlying_Full_View;
8820
8821    -------------------------------
8822    -- Check_Abstract_Overriding --
8823    -------------------------------
8824
8825    procedure Check_Abstract_Overriding (T : Entity_Id) is
8826       Alias_Subp : Entity_Id;
8827       Elmt       : Elmt_Id;
8828       Op_List    : Elist_Id;
8829       Subp       : Entity_Id;
8830       Type_Def   : Node_Id;
8831
8832       procedure Check_Pragma_Implemented (Subp : Entity_Id);
8833       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
8834       --  which has pragma Implemented already set. Check whether Subp's entity
8835       --  kind conforms to the implementation kind of the overridden routine.
8836
8837       procedure Check_Pragma_Implemented
8838         (Subp       : Entity_Id;
8839          Iface_Subp : Entity_Id);
8840       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
8841       --  Iface_Subp and both entities have pragma Implemented already set on
8842       --  them. Check whether the two implementation kinds are conforming.
8843
8844       procedure Inherit_Pragma_Implemented
8845         (Subp       : Entity_Id;
8846          Iface_Subp : Entity_Id);
8847       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
8848       --  subprogram Iface_Subp which has been marked by pragma Implemented.
8849       --  Propagate the implementation kind of Iface_Subp to Subp.
8850
8851       ------------------------------
8852       -- Check_Pragma_Implemented --
8853       ------------------------------
8854
8855       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
8856          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
8857          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
8858          Contr_Typ   : Entity_Id;
8859
8860       begin
8861          --  Subp must have an alias since it is a hidden entity used to link
8862          --  an interface subprogram to its overriding counterpart.
8863
8864          pragma Assert (Present (Alias (Subp)));
8865
8866          --  Extract the type of the controlling formal
8867
8868          Contr_Typ := Etype (First_Formal (Alias (Subp)));
8869
8870          if Is_Concurrent_Record_Type (Contr_Typ) then
8871             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
8872          end if;
8873
8874          --  An interface subprogram whose implementation kind is By_Entry must
8875          --  be implemented by an entry.
8876
8877          if Impl_Kind = Name_By_Entry
8878            and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Entry
8879          then
8880             Error_Msg_Node_2 := Iface_Alias;
8881             Error_Msg_NE
8882               ("type & must implement abstract subprogram & with an entry",
8883                Alias (Subp), Contr_Typ);
8884
8885          elsif Impl_Kind = Name_By_Protected_Procedure then
8886
8887             --  An interface subprogram whose implementation kind is By_
8888             --  Protected_Procedure cannot be implemented by a primitive
8889             --  procedure of a task type.
8890
8891             if Ekind (Contr_Typ) /= E_Protected_Type then
8892                Error_Msg_Node_2 := Contr_Typ;
8893                Error_Msg_NE
8894                  ("interface subprogram & cannot be implemented by a " &
8895                   "primitive procedure of task type &", Alias (Subp),
8896                   Iface_Alias);
8897
8898             --  An interface subprogram whose implementation kind is By_
8899             --  Protected_Procedure must be implemented by a procedure.
8900
8901             elsif Is_Primitive_Wrapper (Alias (Subp))
8902               and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Procedure
8903             then
8904                Error_Msg_Node_2 := Iface_Alias;
8905                Error_Msg_NE
8906                  ("type & must implement abstract subprogram & with a " &
8907                   "procedure", Alias (Subp), Contr_Typ);
8908             end if;
8909          end if;
8910       end Check_Pragma_Implemented;
8911
8912       ------------------------------
8913       -- Check_Pragma_Implemented --
8914       ------------------------------
8915
8916       procedure Check_Pragma_Implemented
8917         (Subp       : Entity_Id;
8918          Iface_Subp : Entity_Id)
8919       is
8920          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
8921          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
8922
8923       begin
8924          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
8925          --  and overriding subprogram are different. In general this is an
8926          --  error except when the implementation kind of the overridden
8927          --  subprograms is By_Any.
8928
8929          if Iface_Kind /= Subp_Kind
8930            and then Iface_Kind /= Name_By_Any
8931          then
8932             if Iface_Kind = Name_By_Entry then
8933                Error_Msg_N
8934                  ("incompatible implementation kind, overridden subprogram " &
8935                   "is marked By_Entry", Subp);
8936             else
8937                Error_Msg_N
8938                  ("incompatible implementation kind, overridden subprogram " &
8939                   "is marked By_Protected_Procedure", Subp);
8940             end if;
8941          end if;
8942       end Check_Pragma_Implemented;
8943
8944       --------------------------------
8945       -- Inherit_Pragma_Implemented --
8946       --------------------------------
8947
8948       procedure Inherit_Pragma_Implemented
8949         (Subp       : Entity_Id;
8950          Iface_Subp : Entity_Id)
8951       is
8952          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
8953          Loc        : constant Source_Ptr := Sloc (Subp);
8954          Impl_Prag  : Node_Id;
8955
8956       begin
8957          --  Since the implementation kind is stored as a representation item
8958          --  rather than a flag, create a pragma node.
8959
8960          Impl_Prag :=
8961            Make_Pragma (Loc,
8962              Chars => Name_Implemented,
8963              Pragma_Argument_Associations => New_List (
8964                Make_Pragma_Argument_Association (Loc,
8965                  Expression =>
8966                    New_Reference_To (Subp, Loc)),
8967
8968                Make_Pragma_Argument_Association (Loc,
8969                  Expression => Make_Identifier (Loc, Iface_Kind))));
8970
8971          --  The pragma doesn't need to be analyzed because it is internally
8972          --  build. It is safe to directly register it as a rep item since we
8973          --  are only interested in the characters of the implementation kind.
8974
8975          Record_Rep_Item (Subp, Impl_Prag);
8976       end Inherit_Pragma_Implemented;
8977
8978    --  Start of processing for Check_Abstract_Overriding
8979
8980    begin
8981       Op_List := Primitive_Operations (T);
8982
8983       --  Loop to check primitive operations
8984
8985       Elmt := First_Elmt (Op_List);
8986       while Present (Elmt) loop
8987          Subp := Node (Elmt);
8988          Alias_Subp := Alias (Subp);
8989
8990          --  Inherited subprograms are identified by the fact that they do not
8991          --  come from source, and the associated source location is the
8992          --  location of the first subtype of the derived type.
8993
8994          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
8995          --  subprograms that "require overriding".
8996
8997          --  Special exception, do not complain about failure to override the
8998          --  stream routines _Input and _Output, as well as the primitive
8999          --  operations used in dispatching selects since we always provide
9000          --  automatic overridings for these subprograms.
9001
9002          --  Also ignore this rule for convention CIL since .NET libraries
9003          --  do bizarre things with interfaces???
9004
9005          --  The partial view of T may have been a private extension, for
9006          --  which inherited functions dispatching on result are abstract.
9007          --  If the full view is a null extension, there is no need for
9008          --  overriding in Ada 2005, but wrappers need to be built for them
9009          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
9010
9011          if Is_Null_Extension (T)
9012            and then Has_Controlling_Result (Subp)
9013            and then Ada_Version >= Ada_2005
9014            and then Present (Alias_Subp)
9015            and then not Comes_From_Source (Subp)
9016            and then not Is_Abstract_Subprogram (Alias_Subp)
9017            and then not Is_Access_Type (Etype (Subp))
9018          then
9019             null;
9020
9021          --  Ada 2005 (AI-251): Internal entities of interfaces need no
9022          --  processing because this check is done with the aliased
9023          --  entity
9024
9025          elsif Present (Interface_Alias (Subp)) then
9026             null;
9027
9028          elsif (Is_Abstract_Subprogram (Subp)
9029                  or else Requires_Overriding (Subp)
9030                  or else
9031                    (Has_Controlling_Result (Subp)
9032                      and then Present (Alias_Subp)
9033                      and then not Comes_From_Source (Subp)
9034                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
9035            and then not Is_TSS (Subp, TSS_Stream_Input)
9036            and then not Is_TSS (Subp, TSS_Stream_Output)
9037            and then not Is_Abstract_Type (T)
9038            and then Convention (T) /= Convention_CIL
9039            and then not Is_Predefined_Interface_Primitive (Subp)
9040
9041             --  Ada 2005 (AI-251): Do not consider hidden entities associated
9042             --  with abstract interface types because the check will be done
9043             --  with the aliased entity (otherwise we generate a duplicated
9044             --  error message).
9045
9046            and then not Present (Interface_Alias (Subp))
9047          then
9048             if Present (Alias_Subp) then
9049
9050                --  Only perform the check for a derived subprogram when the
9051                --  type has an explicit record extension. This avoids incorrect
9052                --  flagging of abstract subprograms for the case of a type
9053                --  without an extension that is derived from a formal type
9054                --  with a tagged actual (can occur within a private part).
9055
9056                --  Ada 2005 (AI-391): In the case of an inherited function with
9057                --  a controlling result of the type, the rule does not apply if
9058                --  the type is a null extension (unless the parent function
9059                --  itself is abstract, in which case the function must still be
9060                --  be overridden). The expander will generate an overriding
9061                --  wrapper function calling the parent subprogram (see
9062                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
9063
9064                Type_Def := Type_Definition (Parent (T));
9065
9066                if Nkind (Type_Def) = N_Derived_Type_Definition
9067                  and then Present (Record_Extension_Part (Type_Def))
9068                  and then
9069                    (Ada_Version < Ada_2005
9070                       or else not Is_Null_Extension (T)
9071                       or else Ekind (Subp) = E_Procedure
9072                       or else not Has_Controlling_Result (Subp)
9073                       or else Is_Abstract_Subprogram (Alias_Subp)
9074                       or else Requires_Overriding (Subp)
9075                       or else Is_Access_Type (Etype (Subp)))
9076                then
9077                   --  Avoid reporting error in case of abstract predefined
9078                   --  primitive inherited from interface type because the
9079                   --  body of internally generated predefined primitives
9080                   --  of tagged types are generated later by Freeze_Type
9081
9082                   if Is_Interface (Root_Type (T))
9083                     and then Is_Abstract_Subprogram (Subp)
9084                     and then Is_Predefined_Dispatching_Operation (Subp)
9085                     and then not Comes_From_Source (Ultimate_Alias (Subp))
9086                   then
9087                      null;
9088
9089                   else
9090                      Error_Msg_NE
9091                        ("type must be declared abstract or & overridden",
9092                         T, Subp);
9093
9094                      --  Traverse the whole chain of aliased subprograms to
9095                      --  complete the error notification. This is especially
9096                      --  useful for traceability of the chain of entities when
9097                      --  the subprogram corresponds with an interface
9098                      --  subprogram (which may be defined in another package).
9099
9100                      if Present (Alias_Subp) then
9101                         declare
9102                            E : Entity_Id;
9103
9104                         begin
9105                            E := Subp;
9106                            while Present (Alias (E)) loop
9107
9108                               --  Avoid reporting redundant errors on entities
9109                               --  inherited from interfaces
9110
9111                               if Sloc (E) /= Sloc (T) then
9112                                  Error_Msg_Sloc := Sloc (E);
9113                                  Error_Msg_NE
9114                                    ("\& has been inherited #", T, Subp);
9115                               end if;
9116
9117                               E := Alias (E);
9118                            end loop;
9119
9120                            Error_Msg_Sloc := Sloc (E);
9121
9122                            --  AI05-0068: report if there is an overriding
9123                            --  non-abstract subprogram that is invisible.
9124
9125                            if Is_Hidden (E)
9126                              and then not Is_Abstract_Subprogram (E)
9127                            then
9128                               Error_Msg_NE
9129                                 ("\& subprogram# is not visible",
9130                                  T, Subp);
9131
9132                            else
9133                               Error_Msg_NE
9134                                 ("\& has been inherited from subprogram #",
9135                                  T, Subp);
9136                            end if;
9137                         end;
9138                      end if;
9139                   end if;
9140
9141                --  Ada 2005 (AI-345): Protected or task type implementing
9142                --  abstract interfaces.
9143
9144                elsif Is_Concurrent_Record_Type (T)
9145                  and then Present (Interfaces (T))
9146                then
9147                   --  The controlling formal of Subp must be of mode "out",
9148                   --  "in out" or an access-to-variable to be overridden.
9149
9150                   if Ekind (First_Formal (Subp)) = E_In_Parameter
9151                     and then Ekind (Subp) /= E_Function
9152                   then
9153                      if not Is_Predefined_Dispatching_Operation (Subp)
9154                        and then Is_Protected_Type
9155                                   (Corresponding_Concurrent_Type (T))
9156                      then
9157                         Error_Msg_PT (T, Subp);
9158                      end if;
9159
9160                   --  Some other kind of overriding failure
9161
9162                   else
9163                      Error_Msg_NE
9164                        ("interface subprogram & must be overridden",
9165                         T, Subp);
9166
9167                      --  Examine primitive operations of synchronized type,
9168                      --  to find homonyms that have the wrong profile.
9169
9170                      declare
9171                         Prim : Entity_Id;
9172
9173                      begin
9174                         Prim :=
9175                           First_Entity (Corresponding_Concurrent_Type (T));
9176                         while Present (Prim) loop
9177                            if Chars (Prim) = Chars (Subp) then
9178                               Error_Msg_NE
9179                                 ("profile is not type conformant with "
9180                                    & "prefixed view profile of "
9181                                    & "inherited operation&", Prim, Subp);
9182                            end if;
9183
9184                            Next_Entity (Prim);
9185                         end loop;
9186                      end;
9187                   end if;
9188                end if;
9189
9190             else
9191                Error_Msg_Node_2 := T;
9192                Error_Msg_N
9193                  ("abstract subprogram& not allowed for type&", Subp);
9194
9195                --  Also post unconditional warning on the type (unconditional
9196                --  so that if there are more than one of these cases, we get
9197                --  them all, and not just the first one).
9198
9199                Error_Msg_Node_2 := Subp;
9200                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
9201             end if;
9202          end if;
9203
9204          --  Ada 2012 (AI05-0030): Perform some checks related to pragma
9205          --  Implemented
9206
9207          --  Subp is an expander-generated procedure which maps an interface
9208          --  alias to a protected wrapper. The interface alias is flagged by
9209          --  pragma Implemented. Ensure that Subp is a procedure when the
9210          --  implementation kind is By_Protected_Procedure or an entry when
9211          --  By_Entry.
9212
9213          if Ada_Version >= Ada_2012
9214            and then Is_Hidden (Subp)
9215            and then Present (Interface_Alias (Subp))
9216            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
9217          then
9218             Check_Pragma_Implemented (Subp);
9219          end if;
9220
9221          --  Subp is an interface primitive which overrides another interface
9222          --  primitive marked with pragma Implemented.
9223
9224          if Ada_Version >= Ada_2012
9225            and then Present (Overridden_Operation (Subp))
9226            and then Has_Rep_Pragma
9227                       (Overridden_Operation (Subp), Name_Implemented)
9228          then
9229             --  If the overriding routine is also marked by Implemented, check
9230             --  that the two implementation kinds are conforming.
9231
9232             if Has_Rep_Pragma (Subp, Name_Implemented) then
9233                Check_Pragma_Implemented
9234                  (Subp       => Subp,
9235                   Iface_Subp => Overridden_Operation (Subp));
9236
9237             --  Otherwise the overriding routine inherits the implementation
9238             --  kind from the overridden subprogram.
9239
9240             else
9241                Inherit_Pragma_Implemented
9242                  (Subp       => Subp,
9243                   Iface_Subp => Overridden_Operation (Subp));
9244             end if;
9245          end if;
9246
9247          Next_Elmt (Elmt);
9248       end loop;
9249    end Check_Abstract_Overriding;
9250
9251    ------------------------------------------------
9252    -- Check_Access_Discriminant_Requires_Limited --
9253    ------------------------------------------------
9254
9255    procedure Check_Access_Discriminant_Requires_Limited
9256      (D   : Node_Id;
9257       Loc : Node_Id)
9258    is
9259    begin
9260       --  A discriminant_specification for an access discriminant shall appear
9261       --  only in the declaration for a task or protected type, or for a type
9262       --  with the reserved word 'limited' in its definition or in one of its
9263       --  ancestors (RM 3.7(10)).
9264
9265       --  AI-0063: The proper condition is that type must be immutably limited,
9266       --  or else be a partial view.
9267
9268       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
9269          if Is_Immutably_Limited_Type (Current_Scope)
9270            or else
9271              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
9272                and then Limited_Present (Parent (Current_Scope)))
9273          then
9274             null;
9275
9276          else
9277             Error_Msg_N
9278               ("access discriminants allowed only for limited types", Loc);
9279          end if;
9280       end if;
9281    end Check_Access_Discriminant_Requires_Limited;
9282
9283    -----------------------------------
9284    -- Check_Aliased_Component_Types --
9285    -----------------------------------
9286
9287    procedure Check_Aliased_Component_Types (T : Entity_Id) is
9288       C : Entity_Id;
9289
9290    begin
9291       --  ??? Also need to check components of record extensions, but not
9292       --  components of protected types (which are always limited).
9293
9294       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
9295       --  types to be unconstrained. This is safe because it is illegal to
9296       --  create access subtypes to such types with explicit discriminant
9297       --  constraints.
9298
9299       if not Is_Limited_Type (T) then
9300          if Ekind (T) = E_Record_Type then
9301             C := First_Component (T);
9302             while Present (C) loop
9303                if Is_Aliased (C)
9304                  and then Has_Discriminants (Etype (C))
9305                  and then not Is_Constrained (Etype (C))
9306                  and then not In_Instance_Body
9307                  and then Ada_Version < Ada_2005
9308                then
9309                   Error_Msg_N
9310                     ("aliased component must be constrained (RM 3.6(11))",
9311                       C);
9312                end if;
9313
9314                Next_Component (C);
9315             end loop;
9316
9317          elsif Ekind (T) = E_Array_Type then
9318             if Has_Aliased_Components (T)
9319               and then Has_Discriminants (Component_Type (T))
9320               and then not Is_Constrained (Component_Type (T))
9321               and then not In_Instance_Body
9322               and then Ada_Version < Ada_2005
9323             then
9324                Error_Msg_N
9325                  ("aliased component type must be constrained (RM 3.6(11))",
9326                     T);
9327             end if;
9328          end if;
9329       end if;
9330    end Check_Aliased_Component_Types;
9331
9332    ----------------------
9333    -- Check_Completion --
9334    ----------------------
9335
9336    procedure Check_Completion (Body_Id : Node_Id := Empty) is
9337       E : Entity_Id;
9338
9339       procedure Post_Error;
9340       --  Post error message for lack of completion for entity E
9341
9342       ----------------
9343       -- Post_Error --
9344       ----------------
9345
9346       procedure Post_Error is
9347
9348          procedure Missing_Body;
9349          --  Output missing body message
9350
9351          ------------------
9352          -- Missing_Body --
9353          ------------------
9354
9355          procedure Missing_Body is
9356          begin
9357             --  Spec is in same unit, so we can post on spec
9358
9359             if In_Same_Source_Unit (Body_Id, E) then
9360                Error_Msg_N ("missing body for &", E);
9361
9362             --  Spec is in a separate unit, so we have to post on the body
9363
9364             else
9365                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
9366             end if;
9367          end Missing_Body;
9368
9369       --  Start of processing for Post_Error
9370
9371       begin
9372          if not Comes_From_Source (E) then
9373
9374             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
9375                --  It may be an anonymous protected type created for a
9376                --  single variable. Post error on variable, if present.
9377
9378                declare
9379                   Var : Entity_Id;
9380
9381                begin
9382                   Var := First_Entity (Current_Scope);
9383                   while Present (Var) loop
9384                      exit when Etype (Var) = E
9385                        and then Comes_From_Source (Var);
9386
9387                      Next_Entity (Var);
9388                   end loop;
9389
9390                   if Present (Var) then
9391                      E := Var;
9392                   end if;
9393                end;
9394             end if;
9395          end if;
9396
9397          --  If a generated entity has no completion, then either previous
9398          --  semantic errors have disabled the expansion phase, or else we had
9399          --  missing subunits, or else we are compiling without expansion,
9400          --  or else something is very wrong.
9401
9402          if not Comes_From_Source (E) then
9403             pragma Assert
9404               (Serious_Errors_Detected > 0
9405                 or else Configurable_Run_Time_Violations > 0
9406                 or else Subunits_Missing
9407                 or else not Expander_Active);
9408             return;
9409
9410          --  Here for source entity
9411
9412          else
9413             --  Here if no body to post the error message, so we post the error
9414             --  on the declaration that has no completion. This is not really
9415             --  the right place to post it, think about this later ???
9416
9417             if No (Body_Id) then
9418                if Is_Type (E) then
9419                   Error_Msg_NE
9420                     ("missing full declaration for }", Parent (E), E);
9421                else
9422                   Error_Msg_NE ("missing body for &", Parent (E), E);
9423                end if;
9424
9425             --  Package body has no completion for a declaration that appears
9426             --  in the corresponding spec. Post error on the body, with a
9427             --  reference to the non-completed declaration.
9428
9429             else
9430                Error_Msg_Sloc := Sloc (E);
9431
9432                if Is_Type (E) then
9433                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
9434
9435                elsif Is_Overloadable (E)
9436                  and then Current_Entity_In_Scope (E) /= E
9437                then
9438                   --  It may be that the completion is mistyped and appears as
9439                   --  a distinct overloading of the entity.
9440
9441                   declare
9442                      Candidate : constant Entity_Id :=
9443                                    Current_Entity_In_Scope (E);
9444                      Decl      : constant Node_Id :=
9445                                    Unit_Declaration_Node (Candidate);
9446
9447                   begin
9448                      if Is_Overloadable (Candidate)
9449                        and then Ekind (Candidate) = Ekind (E)
9450                        and then Nkind (Decl) = N_Subprogram_Body
9451                        and then Acts_As_Spec (Decl)
9452                      then
9453                         Check_Type_Conformant (Candidate, E);
9454
9455                      else
9456                         Missing_Body;
9457                      end if;
9458                   end;
9459
9460                else
9461                   Missing_Body;
9462                end if;
9463             end if;
9464          end if;
9465       end Post_Error;
9466
9467    --  Start of processing for Check_Completion
9468
9469    begin
9470       E := First_Entity (Current_Scope);
9471       while Present (E) loop
9472          if Is_Intrinsic_Subprogram (E) then
9473             null;
9474
9475          --  The following situation requires special handling: a child unit
9476          --  that appears in the context clause of the body of its parent:
9477
9478          --    procedure Parent.Child (...);
9479
9480          --    with Parent.Child;
9481          --    package body Parent is
9482
9483          --  Here Parent.Child appears as a local entity, but should not be
9484          --  flagged as requiring completion, because it is a compilation
9485          --  unit.
9486
9487          --  Ignore missing completion for a subprogram that does not come from
9488          --  source (including the _Call primitive operation of RAS types,
9489          --  which has to have the flag Comes_From_Source for other purposes):
9490          --  we assume that the expander will provide the missing completion.
9491          --  In case of previous errors, other expansion actions that provide
9492          --  bodies for null procedures with not be invoked, so inhibit message
9493          --  in those cases.
9494          --  Note that E_Operator is not in the list that follows, because
9495          --  this kind is reserved for predefined operators, that are
9496          --  intrinsic and do not need completion.
9497
9498          elsif     Ekind (E) = E_Function
9499            or else Ekind (E) = E_Procedure
9500            or else Ekind (E) = E_Generic_Function
9501            or else Ekind (E) = E_Generic_Procedure
9502          then
9503             if Has_Completion (E) then
9504                null;
9505
9506             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
9507                null;
9508
9509             elsif Is_Subprogram (E)
9510               and then (not Comes_From_Source (E)
9511                           or else Chars (E) = Name_uCall)
9512             then
9513                null;
9514
9515             elsif
9516                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
9517             then
9518                null;
9519
9520             elsif Nkind (Parent (E)) = N_Procedure_Specification
9521               and then Null_Present (Parent (E))
9522               and then Serious_Errors_Detected > 0
9523             then
9524                null;
9525
9526             else
9527                Post_Error;
9528             end if;
9529
9530          elsif Is_Entry (E) then
9531             if not Has_Completion (E) and then
9532               (Ekind (Scope (E)) = E_Protected_Object
9533                 or else Ekind (Scope (E)) = E_Protected_Type)
9534             then
9535                Post_Error;
9536             end if;
9537
9538          elsif Is_Package_Or_Generic_Package (E) then
9539             if Unit_Requires_Body (E) then
9540                if not Has_Completion (E)
9541                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
9542                                                        N_Compilation_Unit
9543                then
9544                   Post_Error;
9545                end if;
9546
9547             elsif not Is_Child_Unit (E) then
9548                May_Need_Implicit_Body (E);
9549             end if;
9550
9551          elsif Ekind (E) = E_Incomplete_Type
9552            and then No (Underlying_Type (E))
9553          then
9554             Post_Error;
9555
9556          elsif (Ekind (E) = E_Task_Type or else
9557                 Ekind (E) = E_Protected_Type)
9558            and then not Has_Completion (E)
9559          then
9560             Post_Error;
9561
9562          --  A single task declared in the current scope is a constant, verify
9563          --  that the body of its anonymous type is in the same scope. If the
9564          --  task is defined elsewhere, this may be a renaming declaration for
9565          --  which no completion is needed.
9566
9567          elsif Ekind (E) = E_Constant
9568            and then Ekind (Etype (E)) = E_Task_Type
9569            and then not Has_Completion (Etype (E))
9570            and then Scope (Etype (E)) = Current_Scope
9571          then
9572             Post_Error;
9573
9574          elsif Ekind (E) = E_Protected_Object
9575            and then not Has_Completion (Etype (E))
9576          then
9577             Post_Error;
9578
9579          elsif Ekind (E) = E_Record_Type then
9580             if Is_Tagged_Type (E) then
9581                Check_Abstract_Overriding (E);
9582                Check_Conventions (E);
9583             end if;
9584
9585             Check_Aliased_Component_Types (E);
9586
9587          elsif Ekind (E) = E_Array_Type then
9588             Check_Aliased_Component_Types (E);
9589
9590          end if;
9591
9592          Next_Entity (E);
9593       end loop;
9594    end Check_Completion;
9595
9596    ----------------------------
9597    -- Check_Delta_Expression --
9598    ----------------------------
9599
9600    procedure Check_Delta_Expression (E : Node_Id) is
9601    begin
9602       if not (Is_Real_Type (Etype (E))) then
9603          Wrong_Type (E, Any_Real);
9604
9605       elsif not Is_OK_Static_Expression (E) then
9606          Flag_Non_Static_Expr
9607            ("non-static expression used for delta value!", E);
9608
9609       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9610          Error_Msg_N ("delta expression must be positive", E);
9611
9612       else
9613          return;
9614       end if;
9615
9616       --  If any of above errors occurred, then replace the incorrect
9617       --  expression by the real 0.1, which should prevent further errors.
9618
9619       Rewrite (E,
9620         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9621       Analyze_And_Resolve (E, Standard_Float);
9622    end Check_Delta_Expression;
9623
9624    -----------------------------
9625    -- Check_Digits_Expression --
9626    -----------------------------
9627
9628    procedure Check_Digits_Expression (E : Node_Id) is
9629    begin
9630       if not (Is_Integer_Type (Etype (E))) then
9631          Wrong_Type (E, Any_Integer);
9632
9633       elsif not Is_OK_Static_Expression (E) then
9634          Flag_Non_Static_Expr
9635            ("non-static expression used for digits value!", E);
9636
9637       elsif Expr_Value (E) <= 0 then
9638          Error_Msg_N ("digits value must be greater than zero", E);
9639
9640       else
9641          return;
9642       end if;
9643
9644       --  If any of above errors occurred, then replace the incorrect
9645       --  expression by the integer 1, which should prevent further errors.
9646
9647       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9648       Analyze_And_Resolve (E, Standard_Integer);
9649
9650    end Check_Digits_Expression;
9651
9652    --------------------------
9653    -- Check_Initialization --
9654    --------------------------
9655
9656    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9657    begin
9658       if Is_Limited_Type (T)
9659         and then not In_Instance
9660         and then not In_Inlined_Body
9661       then
9662          if not OK_For_Limited_Init (T, Exp) then
9663
9664             --  In GNAT mode, this is just a warning, to allow it to be evilly
9665             --  turned off. Otherwise it is a real error.
9666
9667             if GNAT_Mode then
9668                Error_Msg_N
9669                  ("?cannot initialize entities of limited type!", Exp);
9670
9671             elsif Ada_Version < Ada_2005 then
9672                Error_Msg_N
9673                  ("cannot initialize entities of limited type", Exp);
9674                Explain_Limited_Type (T, Exp);
9675
9676             else
9677                --  Specialize error message according to kind of illegal
9678                --  initial expression.
9679
9680                if Nkind (Exp) = N_Type_Conversion
9681                  and then Nkind (Expression (Exp)) = N_Function_Call
9682                then
9683                   Error_Msg_N
9684                     ("illegal context for call"
9685                       & " to function with limited result", Exp);
9686
9687                else
9688                   Error_Msg_N
9689                     ("initialization of limited object requires aggregate "
9690                       & "or function call",  Exp);
9691                end if;
9692             end if;
9693          end if;
9694       end if;
9695    end Check_Initialization;
9696
9697    ----------------------
9698    -- Check_Interfaces --
9699    ----------------------
9700
9701    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
9702       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
9703
9704       Iface       : Node_Id;
9705       Iface_Def   : Node_Id;
9706       Iface_Typ   : Entity_Id;
9707       Parent_Node : Node_Id;
9708
9709       Is_Task : Boolean := False;
9710       --  Set True if parent type or any progenitor is a task interface
9711
9712       Is_Protected : Boolean := False;
9713       --  Set True if parent type or any progenitor is a protected interface
9714
9715       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
9716       --  Check that a progenitor is compatible with declaration.
9717       --  Error is posted on Error_Node.
9718
9719       ------------------
9720       -- Check_Ifaces --
9721       ------------------
9722
9723       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
9724          Iface_Id : constant Entity_Id :=
9725                       Defining_Identifier (Parent (Iface_Def));
9726          Type_Def : Node_Id;
9727
9728       begin
9729          if Nkind (N) = N_Private_Extension_Declaration then
9730             Type_Def := N;
9731          else
9732             Type_Def := Type_Definition (N);
9733          end if;
9734
9735          if Is_Task_Interface (Iface_Id) then
9736             Is_Task := True;
9737
9738          elsif Is_Protected_Interface (Iface_Id) then
9739             Is_Protected := True;
9740          end if;
9741
9742          if Is_Synchronized_Interface (Iface_Id) then
9743
9744             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
9745             --  extension derived from a synchronized interface must explicitly
9746             --  be declared synchronized, because the full view will be a
9747             --  synchronized type.
9748
9749             if Nkind (N) = N_Private_Extension_Declaration then
9750                if not Synchronized_Present (N) then
9751                   Error_Msg_NE
9752                     ("private extension of& must be explicitly synchronized",
9753                       N, Iface_Id);
9754                end if;
9755
9756             --  However, by 3.9.4(16/2), a full type that is a record extension
9757             --  is never allowed to derive from a synchronized interface (note
9758             --  that interfaces must be excluded from this check, because those
9759             --  are represented by derived type definitions in some cases).
9760
9761             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9762               and then not Interface_Present (Type_Definition (N))
9763             then
9764                Error_Msg_N ("record extension cannot derive from synchronized"
9765                              & " interface", Error_Node);
9766             end if;
9767          end if;
9768
9769          --  Check that the characteristics of the progenitor are compatible
9770          --  with the explicit qualifier in the declaration.
9771          --  The check only applies to qualifiers that come from source.
9772          --  Limited_Present also appears in the declaration of corresponding
9773          --  records, and the check does not apply to them.
9774
9775          if Limited_Present (Type_Def)
9776            and then not
9777              Is_Concurrent_Record_Type (Defining_Identifier (N))
9778          then
9779             if Is_Limited_Interface (Parent_Type)
9780               and then not Is_Limited_Interface (Iface_Id)
9781             then
9782                Error_Msg_NE
9783                  ("progenitor& must be limited interface",
9784                    Error_Node, Iface_Id);
9785
9786             elsif
9787               (Task_Present (Iface_Def)
9788                 or else Protected_Present (Iface_Def)
9789                 or else Synchronized_Present (Iface_Def))
9790               and then Nkind (N) /= N_Private_Extension_Declaration
9791               and then not Error_Posted (N)
9792             then
9793                Error_Msg_NE
9794                  ("progenitor& must be limited interface",
9795                    Error_Node, Iface_Id);
9796             end if;
9797
9798          --  Protected interfaces can only inherit from limited, synchronized
9799          --  or protected interfaces.
9800
9801          elsif Nkind (N) = N_Full_Type_Declaration
9802            and then  Protected_Present (Type_Def)
9803          then
9804             if Limited_Present (Iface_Def)
9805               or else Synchronized_Present (Iface_Def)
9806               or else Protected_Present (Iface_Def)
9807             then
9808                null;
9809
9810             elsif Task_Present (Iface_Def) then
9811                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9812                             & " from task interface", Error_Node);
9813
9814             else
9815                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9816                             & " from non-limited interface", Error_Node);
9817             end if;
9818
9819          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
9820          --  limited and synchronized.
9821
9822          elsif Synchronized_Present (Type_Def) then
9823             if Limited_Present (Iface_Def)
9824               or else Synchronized_Present (Iface_Def)
9825             then
9826                null;
9827
9828             elsif Protected_Present (Iface_Def)
9829               and then Nkind (N) /= N_Private_Extension_Declaration
9830             then
9831                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9832                             & " from protected interface", Error_Node);
9833
9834             elsif Task_Present (Iface_Def)
9835               and then Nkind (N) /= N_Private_Extension_Declaration
9836             then
9837                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9838                             & " from task interface", Error_Node);
9839
9840             elsif not Is_Limited_Interface (Iface_Id) then
9841                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9842                             & " from non-limited interface", Error_Node);
9843             end if;
9844
9845          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
9846          --  synchronized or task interfaces.
9847
9848          elsif Nkind (N) = N_Full_Type_Declaration
9849            and then Task_Present (Type_Def)
9850          then
9851             if Limited_Present (Iface_Def)
9852               or else Synchronized_Present (Iface_Def)
9853               or else Task_Present (Iface_Def)
9854             then
9855                null;
9856
9857             elsif Protected_Present (Iface_Def) then
9858                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9859                             & " protected interface", Error_Node);
9860
9861             else
9862                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9863                             & " non-limited interface", Error_Node);
9864             end if;
9865          end if;
9866       end Check_Ifaces;
9867
9868    --  Start of processing for Check_Interfaces
9869
9870    begin
9871       if Is_Interface (Parent_Type) then
9872          if Is_Task_Interface (Parent_Type) then
9873             Is_Task := True;
9874
9875          elsif Is_Protected_Interface (Parent_Type) then
9876             Is_Protected := True;
9877          end if;
9878       end if;
9879
9880       if Nkind (N) = N_Private_Extension_Declaration then
9881
9882          --  Check that progenitors are compatible with declaration
9883
9884          Iface := First (Interface_List (Def));
9885          while Present (Iface) loop
9886             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9887
9888             Parent_Node := Parent (Base_Type (Iface_Typ));
9889             Iface_Def   := Type_Definition (Parent_Node);
9890
9891             if not Is_Interface (Iface_Typ) then
9892                Diagnose_Interface (Iface, Iface_Typ);
9893
9894             else
9895                Check_Ifaces (Iface_Def, Iface);
9896             end if;
9897
9898             Next (Iface);
9899          end loop;
9900
9901          if Is_Task and Is_Protected then
9902             Error_Msg_N
9903               ("type cannot derive from task and protected interface", N);
9904          end if;
9905
9906          return;
9907       end if;
9908
9909       --  Full type declaration of derived type.
9910       --  Check compatibility with parent if it is interface type
9911
9912       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9913         and then Is_Interface (Parent_Type)
9914       then
9915          Parent_Node := Parent (Parent_Type);
9916
9917          --  More detailed checks for interface varieties
9918
9919          Check_Ifaces
9920            (Iface_Def  => Type_Definition (Parent_Node),
9921             Error_Node => Subtype_Indication (Type_Definition (N)));
9922       end if;
9923
9924       Iface := First (Interface_List (Def));
9925       while Present (Iface) loop
9926          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9927
9928          Parent_Node := Parent (Base_Type (Iface_Typ));
9929          Iface_Def   := Type_Definition (Parent_Node);
9930
9931          if not Is_Interface (Iface_Typ) then
9932             Diagnose_Interface (Iface, Iface_Typ);
9933
9934          else
9935             --  "The declaration of a specific descendant of an interface
9936             --   type freezes the interface type" RM 13.14
9937
9938             Freeze_Before (N, Iface_Typ);
9939             Check_Ifaces (Iface_Def, Error_Node => Iface);
9940          end if;
9941
9942          Next (Iface);
9943       end loop;
9944
9945       if Is_Task and Is_Protected then
9946          Error_Msg_N
9947            ("type cannot derive from task and protected interface", N);
9948       end if;
9949    end Check_Interfaces;
9950
9951    ------------------------------------
9952    -- Check_Or_Process_Discriminants --
9953    ------------------------------------
9954
9955    --  If an incomplete or private type declaration was already given for the
9956    --  type, the discriminants may have already been processed if they were
9957    --  present on the incomplete declaration. In this case a full conformance
9958    --  check has been performed in Find_Type_Name, and we then recheck here
9959    --  some properties that can't be checked on the partial view alone.
9960    --  Otherwise we call Process_Discriminants.
9961
9962    procedure Check_Or_Process_Discriminants
9963      (N    : Node_Id;
9964       T    : Entity_Id;
9965       Prev : Entity_Id := Empty)
9966    is
9967    begin
9968       if Has_Discriminants (T) then
9969
9970          --  Discriminants are already set on T if they were already present
9971          --  on the partial view. Make them visible to component declarations.
9972
9973          declare
9974             D : Entity_Id;
9975             --  Discriminant on T (full view) referencing expr on partial view
9976
9977             Prev_D : Entity_Id;
9978             --  Entity of corresponding discriminant on partial view
9979
9980             New_D : Node_Id;
9981             --  Discriminant specification for full view, expression is the
9982             --  syntactic copy on full view (which has been checked for
9983             --  conformance with partial view), only used here to post error
9984             --  message.
9985
9986          begin
9987             D     := First_Discriminant (T);
9988             New_D := First (Discriminant_Specifications (N));
9989             while Present (D) loop
9990                Prev_D := Current_Entity (D);
9991                Set_Current_Entity (D);
9992                Set_Is_Immediately_Visible (D);
9993                Set_Homonym (D, Prev_D);
9994
9995                --  Handle the case where there is an untagged partial view and
9996                --  the full view is tagged: must disallow discriminants with
9997                --  defaults, unless compiling for Ada 2012, which allows a
9998                --  limited tagged type to have defaulted discriminants (see
9999                --  AI05-0214). However, suppress the error here if it was
10000                --  already reported on the default expression of the partial
10001                --  view.
10002
10003                if Is_Tagged_Type (T)
10004                     and then Present (Expression (Parent (D)))
10005                     and then (not Is_Limited_Type (Current_Scope)
10006                                or else Ada_Version < Ada_2012)
10007                     and then not Error_Posted (Expression (Parent (D)))
10008                then
10009                   if Ada_Version >= Ada_2012 then
10010                      Error_Msg_N
10011                        ("discriminants of nonlimited tagged type cannot have"
10012                           & " defaults",
10013                         Expression (New_D));
10014                   else
10015                      Error_Msg_N
10016                        ("discriminants of tagged type cannot have defaults",
10017                         Expression (New_D));
10018                   end if;
10019                end if;
10020
10021                --  Ada 2005 (AI-230): Access discriminant allowed in
10022                --  non-limited record types.
10023
10024                if Ada_Version < Ada_2005 then
10025
10026                   --  This restriction gets applied to the full type here. It
10027                   --  has already been applied earlier to the partial view.
10028
10029                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
10030                end if;
10031
10032                Next_Discriminant (D);
10033                Next (New_D);
10034             end loop;
10035          end;
10036
10037       elsif Present (Discriminant_Specifications (N)) then
10038          Process_Discriminants (N, Prev);
10039       end if;
10040    end Check_Or_Process_Discriminants;
10041
10042    ----------------------
10043    -- Check_Real_Bound --
10044    ----------------------
10045
10046    procedure Check_Real_Bound (Bound : Node_Id) is
10047    begin
10048       if not Is_Real_Type (Etype (Bound)) then
10049          Error_Msg_N
10050            ("bound in real type definition must be of real type", Bound);
10051
10052       elsif not Is_OK_Static_Expression (Bound) then
10053          Flag_Non_Static_Expr
10054            ("non-static expression used for real type bound!", Bound);
10055
10056       else
10057          return;
10058       end if;
10059
10060       Rewrite
10061         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
10062       Analyze (Bound);
10063       Resolve (Bound, Standard_Float);
10064    end Check_Real_Bound;
10065
10066    ------------------------------
10067    -- Complete_Private_Subtype --
10068    ------------------------------
10069
10070    procedure Complete_Private_Subtype
10071      (Priv        : Entity_Id;
10072       Full        : Entity_Id;
10073       Full_Base   : Entity_Id;
10074       Related_Nod : Node_Id)
10075    is
10076       Save_Next_Entity : Entity_Id;
10077       Save_Homonym     : Entity_Id;
10078
10079    begin
10080       --  Set semantic attributes for (implicit) private subtype completion.
10081       --  If the full type has no discriminants, then it is a copy of the full
10082       --  view of the base. Otherwise, it is a subtype of the base with a
10083       --  possible discriminant constraint. Save and restore the original
10084       --  Next_Entity field of full to ensure that the calls to Copy_Node
10085       --  do not corrupt the entity chain.
10086
10087       --  Note that the type of the full view is the same entity as the type of
10088       --  the partial view. In this fashion, the subtype has access to the
10089       --  correct view of the parent.
10090
10091       Save_Next_Entity := Next_Entity (Full);
10092       Save_Homonym     := Homonym (Priv);
10093
10094       case Ekind (Full_Base) is
10095          when E_Record_Type    |
10096               E_Record_Subtype |
10097               Class_Wide_Kind  |
10098               Private_Kind     |
10099               Task_Kind        |
10100               Protected_Kind   =>
10101             Copy_Node (Priv, Full);
10102
10103             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
10104             Set_First_Entity       (Full, First_Entity (Full_Base));
10105             Set_Last_Entity        (Full, Last_Entity (Full_Base));
10106
10107          when others =>
10108             Copy_Node (Full_Base, Full);
10109             Set_Chars          (Full, Chars (Priv));
10110             Conditional_Delay  (Full, Priv);
10111             Set_Sloc           (Full, Sloc (Priv));
10112       end case;
10113
10114       Set_Next_Entity (Full, Save_Next_Entity);
10115       Set_Homonym     (Full, Save_Homonym);
10116       Set_Associated_Node_For_Itype (Full, Related_Nod);
10117
10118       --  Set common attributes for all subtypes: kind, convention, etc.
10119
10120       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
10121       Set_Convention (Full, Convention (Full_Base));
10122
10123       --  The Etype of the full view is inconsistent. Gigi needs to see the
10124       --  structural full view,  which is what the current scheme gives:
10125       --  the Etype of the full view is the etype of the full base. However,
10126       --  if the full base is a derived type, the full view then looks like
10127       --  a subtype of the parent, not a subtype of the full base. If instead
10128       --  we write:
10129
10130       --       Set_Etype (Full, Full_Base);
10131
10132       --  then we get inconsistencies in the front-end (confusion between
10133       --  views). Several outstanding bugs are related to this ???
10134
10135       Set_Is_First_Subtype (Full, False);
10136       Set_Scope            (Full, Scope (Priv));
10137       Set_Size_Info        (Full, Full_Base);
10138       Set_RM_Size          (Full, RM_Size (Full_Base));
10139       Set_Is_Itype         (Full);
10140
10141       --  A subtype of a private-type-without-discriminants, whose full-view
10142       --  has discriminants with default expressions, is not constrained!
10143
10144       if not Has_Discriminants (Priv) then
10145          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
10146
10147          if Has_Discriminants (Full_Base) then
10148             Set_Discriminant_Constraint
10149               (Full, Discriminant_Constraint (Full_Base));
10150
10151             --  The partial view may have been indefinite, the full view
10152             --  might not be.
10153
10154             Set_Has_Unknown_Discriminants
10155               (Full, Has_Unknown_Discriminants (Full_Base));
10156          end if;
10157       end if;
10158
10159       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
10160       Set_Depends_On_Private (Full, Has_Private_Component (Full));
10161
10162       --  Freeze the private subtype entity if its parent is delayed, and not
10163       --  already frozen. We skip this processing if the type is an anonymous
10164       --  subtype of a record component, or is the corresponding record of a
10165       --  protected type, since ???
10166
10167       if not Is_Type (Scope (Full)) then
10168          Set_Has_Delayed_Freeze (Full,
10169            Has_Delayed_Freeze (Full_Base)
10170              and then (not Is_Frozen (Full_Base)));
10171       end if;
10172
10173       Set_Freeze_Node (Full, Empty);
10174       Set_Is_Frozen (Full, False);
10175       Set_Full_View (Priv, Full);
10176
10177       if Has_Discriminants (Full) then
10178          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
10179          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
10180
10181          if Has_Unknown_Discriminants (Full) then
10182             Set_Discriminant_Constraint (Full, No_Elist);
10183          end if;
10184       end if;
10185
10186       if Ekind (Full_Base) = E_Record_Type
10187         and then Has_Discriminants (Full_Base)
10188         and then Has_Discriminants (Priv) -- might not, if errors
10189         and then not Has_Unknown_Discriminants (Priv)
10190         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
10191       then
10192          Create_Constrained_Components
10193            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
10194
10195       --  If the full base is itself derived from private, build a congruent
10196       --  subtype of its underlying type, for use by the back end. For a
10197       --  constrained record component, the declaration cannot be placed on
10198       --  the component list, but it must nevertheless be built an analyzed, to
10199       --  supply enough information for Gigi to compute the size of component.
10200
10201       elsif Ekind (Full_Base) in Private_Kind
10202         and then Is_Derived_Type (Full_Base)
10203         and then Has_Discriminants (Full_Base)
10204         and then (Ekind (Current_Scope) /= E_Record_Subtype)
10205       then
10206          if not Is_Itype (Priv)
10207            and then
10208              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
10209          then
10210             Build_Underlying_Full_View
10211               (Parent (Priv), Full, Etype (Full_Base));
10212
10213          elsif Nkind (Related_Nod) = N_Component_Declaration then
10214             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
10215          end if;
10216
10217       elsif Is_Record_Type (Full_Base) then
10218
10219          --  Show Full is simply a renaming of Full_Base
10220
10221          Set_Cloned_Subtype (Full, Full_Base);
10222       end if;
10223
10224       --  It is unsafe to share to bounds of a scalar type, because the Itype
10225       --  is elaborated on demand, and if a bound is non-static then different
10226       --  orders of elaboration in different units will lead to different
10227       --  external symbols.
10228
10229       if Is_Scalar_Type (Full_Base) then
10230          Set_Scalar_Range (Full,
10231            Make_Range (Sloc (Related_Nod),
10232              Low_Bound  =>
10233                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
10234              High_Bound =>
10235                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
10236
10237          --  This completion inherits the bounds of the full parent, but if
10238          --  the parent is an unconstrained floating point type, so is the
10239          --  completion.
10240
10241          if Is_Floating_Point_Type (Full_Base) then
10242             Set_Includes_Infinities
10243              (Scalar_Range (Full), Has_Infinities (Full_Base));
10244          end if;
10245       end if;
10246
10247       --  ??? It seems that a lot of fields are missing that should be copied
10248       --  from Full_Base to Full. Here are some that are introduced in a
10249       --  non-disruptive way but a cleanup is necessary.
10250
10251       if Is_Tagged_Type (Full_Base) then
10252          Set_Is_Tagged_Type (Full);
10253          Set_Direct_Primitive_Operations (Full,
10254            Direct_Primitive_Operations (Full_Base));
10255
10256          --  Inherit class_wide type of full_base in case the partial view was
10257          --  not tagged. Otherwise it has already been created when the private
10258          --  subtype was analyzed.
10259
10260          if No (Class_Wide_Type (Full)) then
10261             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
10262          end if;
10263
10264       --  If this is a subtype of a protected or task type, constrain its
10265       --  corresponding record, unless this is a subtype without constraints,
10266       --  i.e. a simple renaming as with an actual subtype in an instance.
10267
10268       elsif Is_Concurrent_Type (Full_Base) then
10269          if Has_Discriminants (Full)
10270            and then Present (Corresponding_Record_Type (Full_Base))
10271            and then
10272              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
10273          then
10274             Set_Corresponding_Record_Type (Full,
10275               Constrain_Corresponding_Record
10276                 (Full, Corresponding_Record_Type (Full_Base),
10277                   Related_Nod, Full_Base));
10278
10279          else
10280             Set_Corresponding_Record_Type (Full,
10281               Corresponding_Record_Type (Full_Base));
10282          end if;
10283       end if;
10284
10285       --  Link rep item chain, and also setting of Has_Predicates from private
10286       --  subtype to full subtype, since we will need these on the full subtype
10287       --  to create the predicate function. Note that the full subtype may
10288       --  already have rep items, inherited from the full view of the base
10289       --  type, so we must be sure not to overwrite these entries.
10290
10291       declare
10292          Append    : Boolean;
10293          Item      : Node_Id;
10294          Next_Item : Node_Id;
10295
10296       begin
10297          Item := First_Rep_Item (Full);
10298
10299          --  If no existing rep items on full type, we can just link directly
10300          --  to the list of items on the private type.
10301
10302          if No (Item) then
10303             Set_First_Rep_Item (Full, First_Rep_Item (Priv));
10304
10305          --  Otherwise, search to the end of items currently linked to the full
10306          --  subtype and append the private items to the end. However, if Priv
10307          --  and Full already have the same list of rep items, then the append
10308          --  is not done, as that would create a circularity.
10309
10310          elsif Item /= First_Rep_Item (Priv) then
10311             Append := True;
10312
10313             loop
10314                Next_Item := Next_Rep_Item (Item);
10315                exit when No (Next_Item);
10316                Item := Next_Item;
10317
10318                --  If the private view has aspect specifications, the full view
10319                --  inherits them. Since these aspects may already have been
10320                --  attached to the full view during derivation, do not append
10321                --  them if already present.
10322
10323                if Item = First_Rep_Item (Priv) then
10324                   Append := False;
10325                   exit;
10326                end if;
10327             end loop;
10328
10329             --  And link the private type items at the end of the chain
10330
10331             if Append then
10332                Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
10333             end if;
10334          end if;
10335       end;
10336
10337       --  Make sure Has_Predicates is set on full type if it is set on the
10338       --  private type. Note that it may already be set on the full type and
10339       --  if so, we don't want to unset it.
10340
10341       if Has_Predicates (Priv) then
10342          Set_Has_Predicates (Full);
10343       end if;
10344    end Complete_Private_Subtype;
10345
10346    ----------------------------
10347    -- Constant_Redeclaration --
10348    ----------------------------
10349
10350    procedure Constant_Redeclaration
10351      (Id : Entity_Id;
10352       N  : Node_Id;
10353       T  : out Entity_Id)
10354    is
10355       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
10356       Obj_Def : constant Node_Id := Object_Definition (N);
10357       New_T   : Entity_Id;
10358
10359       procedure Check_Possible_Deferred_Completion
10360         (Prev_Id      : Entity_Id;
10361          Prev_Obj_Def : Node_Id;
10362          Curr_Obj_Def : Node_Id);
10363       --  Determine whether the two object definitions describe the partial
10364       --  and the full view of a constrained deferred constant. Generate
10365       --  a subtype for the full view and verify that it statically matches
10366       --  the subtype of the partial view.
10367
10368       procedure Check_Recursive_Declaration (Typ : Entity_Id);
10369       --  If deferred constant is an access type initialized with an allocator,
10370       --  check whether there is an illegal recursion in the definition,
10371       --  through a default value of some record subcomponent. This is normally
10372       --  detected when generating init procs, but requires this additional
10373       --  mechanism when expansion is disabled.
10374
10375       ----------------------------------------
10376       -- Check_Possible_Deferred_Completion --
10377       ----------------------------------------
10378
10379       procedure Check_Possible_Deferred_Completion
10380         (Prev_Id      : Entity_Id;
10381          Prev_Obj_Def : Node_Id;
10382          Curr_Obj_Def : Node_Id)
10383       is
10384       begin
10385          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
10386            and then Present (Constraint (Prev_Obj_Def))
10387            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
10388            and then Present (Constraint (Curr_Obj_Def))
10389          then
10390             declare
10391                Loc    : constant Source_Ptr := Sloc (N);
10392                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
10393                Decl   : constant Node_Id    :=
10394                           Make_Subtype_Declaration (Loc,
10395                             Defining_Identifier => Def_Id,
10396                             Subtype_Indication  =>
10397                               Relocate_Node (Curr_Obj_Def));
10398
10399             begin
10400                Insert_Before_And_Analyze (N, Decl);
10401                Set_Etype (Id, Def_Id);
10402
10403                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
10404                   Error_Msg_Sloc := Sloc (Prev_Id);
10405                   Error_Msg_N ("subtype does not statically match deferred " &
10406                                "declaration#", N);
10407                end if;
10408             end;
10409          end if;
10410       end Check_Possible_Deferred_Completion;
10411
10412       ---------------------------------
10413       -- Check_Recursive_Declaration --
10414       ---------------------------------
10415
10416       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
10417          Comp : Entity_Id;
10418
10419       begin
10420          if Is_Record_Type (Typ) then
10421             Comp := First_Component (Typ);
10422             while Present (Comp) loop
10423                if Comes_From_Source (Comp) then
10424                   if Present (Expression (Parent (Comp)))
10425                     and then Is_Entity_Name (Expression (Parent (Comp)))
10426                     and then Entity (Expression (Parent (Comp))) = Prev
10427                   then
10428                      Error_Msg_Sloc := Sloc (Parent (Comp));
10429                      Error_Msg_NE
10430                        ("illegal circularity with declaration for&#",
10431                          N, Comp);
10432                      return;
10433
10434                   elsif Is_Record_Type (Etype (Comp)) then
10435                      Check_Recursive_Declaration (Etype (Comp));
10436                   end if;
10437                end if;
10438
10439                Next_Component (Comp);
10440             end loop;
10441          end if;
10442       end Check_Recursive_Declaration;
10443
10444    --  Start of processing for Constant_Redeclaration
10445
10446    begin
10447       if Nkind (Parent (Prev)) = N_Object_Declaration then
10448          if Nkind (Object_Definition
10449                      (Parent (Prev))) = N_Subtype_Indication
10450          then
10451             --  Find type of new declaration. The constraints of the two
10452             --  views must match statically, but there is no point in
10453             --  creating an itype for the full view.
10454
10455             if Nkind (Obj_Def) = N_Subtype_Indication then
10456                Find_Type (Subtype_Mark (Obj_Def));
10457                New_T := Entity (Subtype_Mark (Obj_Def));
10458
10459             else
10460                Find_Type (Obj_Def);
10461                New_T := Entity (Obj_Def);
10462             end if;
10463
10464             T := Etype (Prev);
10465
10466          else
10467             --  The full view may impose a constraint, even if the partial
10468             --  view does not, so construct the subtype.
10469
10470             New_T := Find_Type_Of_Object (Obj_Def, N);
10471             T     := New_T;
10472          end if;
10473
10474       else
10475          --  Current declaration is illegal, diagnosed below in Enter_Name
10476
10477          T := Empty;
10478          New_T := Any_Type;
10479       end if;
10480
10481       --  If previous full declaration or a renaming declaration exists, or if
10482       --  a homograph is present, let Enter_Name handle it, either with an
10483       --  error or with the removal of an overridden implicit subprogram.
10484
10485       if Ekind (Prev) /= E_Constant
10486         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
10487         or else Present (Expression (Parent (Prev)))
10488         or else Present (Full_View (Prev))
10489       then
10490          Enter_Name (Id);
10491
10492       --  Verify that types of both declarations match, or else that both types
10493       --  are anonymous access types whose designated subtypes statically match
10494       --  (as allowed in Ada 2005 by AI-385).
10495
10496       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
10497         and then
10498           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
10499              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
10500              or else Is_Access_Constant (Etype (New_T)) /=
10501                      Is_Access_Constant (Etype (Prev))
10502              or else Can_Never_Be_Null (Etype (New_T)) /=
10503                      Can_Never_Be_Null (Etype (Prev))
10504              or else Null_Exclusion_Present (Parent (Prev)) /=
10505                      Null_Exclusion_Present (Parent (Id))
10506              or else not Subtypes_Statically_Match
10507                            (Designated_Type (Etype (Prev)),
10508                             Designated_Type (Etype (New_T))))
10509       then
10510          Error_Msg_Sloc := Sloc (Prev);
10511          Error_Msg_N ("type does not match declaration#", N);
10512          Set_Full_View (Prev, Id);
10513          Set_Etype (Id, Any_Type);
10514
10515       elsif
10516         Null_Exclusion_Present (Parent (Prev))
10517           and then not Null_Exclusion_Present (N)
10518       then
10519          Error_Msg_Sloc := Sloc (Prev);
10520          Error_Msg_N ("null-exclusion does not match declaration#", N);
10521          Set_Full_View (Prev, Id);
10522          Set_Etype (Id, Any_Type);
10523
10524       --  If so, process the full constant declaration
10525
10526       else
10527          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
10528          --  the deferred declaration is constrained, then the subtype defined
10529          --  by the subtype_indication in the full declaration shall match it
10530          --  statically.
10531
10532          Check_Possible_Deferred_Completion
10533            (Prev_Id      => Prev,
10534             Prev_Obj_Def => Object_Definition (Parent (Prev)),
10535             Curr_Obj_Def => Obj_Def);
10536
10537          Set_Full_View (Prev, Id);
10538          Set_Is_Public (Id, Is_Public (Prev));
10539          Set_Is_Internal (Id);
10540          Append_Entity (Id, Current_Scope);
10541
10542          --  Check ALIASED present if present before (RM 7.4(7))
10543
10544          if Is_Aliased (Prev)
10545            and then not Aliased_Present (N)
10546          then
10547             Error_Msg_Sloc := Sloc (Prev);
10548             Error_Msg_N ("ALIASED required (see declaration#)", N);
10549          end if;
10550
10551          --  Check that placement is in private part and that the incomplete
10552          --  declaration appeared in the visible part.
10553
10554          if Ekind (Current_Scope) = E_Package
10555            and then not In_Private_Part (Current_Scope)
10556          then
10557             Error_Msg_Sloc := Sloc (Prev);
10558             Error_Msg_N
10559               ("full constant for declaration#"
10560                & " must be in private part", N);
10561
10562          elsif Ekind (Current_Scope) = E_Package
10563            and then
10564              List_Containing (Parent (Prev)) /=
10565                Visible_Declarations
10566                  (Specification (Unit_Declaration_Node (Current_Scope)))
10567          then
10568             Error_Msg_N
10569               ("deferred constant must be declared in visible part",
10570                  Parent (Prev));
10571          end if;
10572
10573          if Is_Access_Type (T)
10574            and then Nkind (Expression (N)) = N_Allocator
10575          then
10576             Check_Recursive_Declaration (Designated_Type (T));
10577          end if;
10578       end if;
10579    end Constant_Redeclaration;
10580
10581    ----------------------
10582    -- Constrain_Access --
10583    ----------------------
10584
10585    procedure Constrain_Access
10586      (Def_Id      : in out Entity_Id;
10587       S           : Node_Id;
10588       Related_Nod : Node_Id)
10589    is
10590       T             : constant Entity_Id := Entity (Subtype_Mark (S));
10591       Desig_Type    : constant Entity_Id := Designated_Type (T);
10592       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
10593       Constraint_OK : Boolean := True;
10594
10595       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
10596       --  Simple predicate to test for defaulted discriminants
10597       --  Shouldn't this be in sem_util???
10598
10599       ---------------------------------
10600       -- Has_Defaulted_Discriminants --
10601       ---------------------------------
10602
10603       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
10604       begin
10605          return Has_Discriminants (Typ)
10606           and then Present (First_Discriminant (Typ))
10607           and then Present
10608             (Discriminant_Default_Value (First_Discriminant (Typ)));
10609       end Has_Defaulted_Discriminants;
10610
10611    --  Start of processing for Constrain_Access
10612
10613    begin
10614       if Is_Array_Type (Desig_Type) then
10615          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
10616
10617       elsif (Is_Record_Type (Desig_Type)
10618               or else Is_Incomplete_Or_Private_Type (Desig_Type))
10619         and then not Is_Constrained (Desig_Type)
10620       then
10621          --  ??? The following code is a temporary kludge to ignore a
10622          --  discriminant constraint on access type if it is constraining
10623          --  the current record. Avoid creating the implicit subtype of the
10624          --  record we are currently compiling since right now, we cannot
10625          --  handle these. For now, just return the access type itself.
10626
10627          if Desig_Type = Current_Scope
10628            and then No (Def_Id)
10629          then
10630             Set_Ekind (Desig_Subtype, E_Record_Subtype);
10631             Def_Id := Entity (Subtype_Mark (S));
10632
10633             --  This call added to ensure that the constraint is analyzed
10634             --  (needed for a B test). Note that we still return early from
10635             --  this procedure to avoid recursive processing. ???
10636
10637             Constrain_Discriminated_Type
10638               (Desig_Subtype, S, Related_Nod, For_Access => True);
10639             return;
10640          end if;
10641
10642          if (Ekind (T) = E_General_Access_Type
10643               or else Ada_Version >= Ada_2005)
10644            and then Has_Private_Declaration (Desig_Type)
10645            and then In_Open_Scopes (Scope (Desig_Type))
10646            and then Has_Discriminants (Desig_Type)
10647          then
10648             --  Enforce rule that the constraint is illegal if there is
10649             --  an unconstrained view of the designated type. This means
10650             --  that the partial view (either a private type declaration or
10651             --  a derivation from a private type) has no discriminants.
10652             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
10653             --  by ACATS B371001).
10654
10655             --  Rule updated for Ada 2005: the private type is said to have
10656             --  a constrained partial view, given that objects of the type
10657             --  can be declared. Furthermore, the rule applies to all access
10658             --  types, unlike the rule concerning default discriminants.
10659
10660             declare
10661                Pack  : constant Node_Id :=
10662                          Unit_Declaration_Node (Scope (Desig_Type));
10663                Decls : List_Id;
10664                Decl  : Node_Id;
10665
10666             begin
10667                if Nkind (Pack) = N_Package_Declaration then
10668                   Decls := Visible_Declarations (Specification (Pack));
10669                   Decl := First (Decls);
10670                   while Present (Decl) loop
10671                      if (Nkind (Decl) = N_Private_Type_Declaration
10672                           and then
10673                             Chars (Defining_Identifier (Decl)) =
10674                                                      Chars (Desig_Type))
10675
10676                        or else
10677                         (Nkind (Decl) = N_Full_Type_Declaration
10678                           and then
10679                             Chars (Defining_Identifier (Decl)) =
10680                                                      Chars (Desig_Type)
10681                           and then Is_Derived_Type (Desig_Type)
10682                           and then
10683                             Has_Private_Declaration (Etype (Desig_Type)))
10684                      then
10685                         if No (Discriminant_Specifications (Decl)) then
10686                            Error_Msg_N
10687                             ("cannot constrain general access type if " &
10688                                "designated type has constrained partial view",
10689                                 S);
10690                         end if;
10691
10692                         exit;
10693                      end if;
10694
10695                      Next (Decl);
10696                   end loop;
10697                end if;
10698             end;
10699          end if;
10700
10701          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
10702            For_Access => True);
10703
10704       elsif (Is_Task_Type (Desig_Type)
10705               or else Is_Protected_Type (Desig_Type))
10706         and then not Is_Constrained (Desig_Type)
10707       then
10708          Constrain_Concurrent
10709            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
10710
10711       else
10712          Error_Msg_N ("invalid constraint on access type", S);
10713          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
10714          Constraint_OK := False;
10715       end if;
10716
10717       if No (Def_Id) then
10718          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
10719       else
10720          Set_Ekind (Def_Id, E_Access_Subtype);
10721       end if;
10722
10723       if Constraint_OK then
10724          Set_Etype (Def_Id, Base_Type (T));
10725
10726          if Is_Private_Type (Desig_Type) then
10727             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
10728          end if;
10729       else
10730          Set_Etype (Def_Id, Any_Type);
10731       end if;
10732
10733       Set_Size_Info                (Def_Id, T);
10734       Set_Is_Constrained           (Def_Id, Constraint_OK);
10735       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
10736       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
10737       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
10738
10739       Conditional_Delay (Def_Id, T);
10740
10741       --  AI-363 : Subtypes of general access types whose designated types have
10742       --  default discriminants are disallowed. In instances, the rule has to
10743       --  be checked against the actual, of which T is the subtype. In a
10744       --  generic body, the rule is checked assuming that the actual type has
10745       --  defaulted discriminants.
10746
10747       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
10748          if Ekind (Base_Type (T)) = E_General_Access_Type
10749            and then Has_Defaulted_Discriminants (Desig_Type)
10750          then
10751             if Ada_Version < Ada_2005 then
10752                Error_Msg_N
10753                  ("access subtype of general access type would not " &
10754                   "be allowed in Ada 2005?", S);
10755             else
10756                Error_Msg_N
10757                  ("access subtype of general access type not allowed", S);
10758             end if;
10759
10760             Error_Msg_N ("\discriminants have defaults", S);
10761
10762          elsif Is_Access_Type (T)
10763            and then Is_Generic_Type (Desig_Type)
10764            and then Has_Discriminants (Desig_Type)
10765            and then In_Package_Body (Current_Scope)
10766          then
10767             if Ada_Version < Ada_2005 then
10768                Error_Msg_N
10769                  ("access subtype would not be allowed in generic body " &
10770                   "in Ada 2005?", S);
10771             else
10772                Error_Msg_N
10773                  ("access subtype not allowed in generic body", S);
10774             end if;
10775
10776             Error_Msg_N
10777               ("\designated type is a discriminated formal", S);
10778          end if;
10779       end if;
10780    end Constrain_Access;
10781
10782    ---------------------
10783    -- Constrain_Array --
10784    ---------------------
10785
10786    procedure Constrain_Array
10787      (Def_Id      : in out Entity_Id;
10788       SI          : Node_Id;
10789       Related_Nod : Node_Id;
10790       Related_Id  : Entity_Id;
10791       Suffix      : Character)
10792    is
10793       C                     : constant Node_Id := Constraint (SI);
10794       Number_Of_Constraints : Nat := 0;
10795       Index                 : Node_Id;
10796       S, T                  : Entity_Id;
10797       Constraint_OK         : Boolean := True;
10798
10799    begin
10800       T := Entity (Subtype_Mark (SI));
10801
10802       if Ekind (T) in Access_Kind then
10803          T := Designated_Type (T);
10804       end if;
10805
10806       --  If an index constraint follows a subtype mark in a subtype indication
10807       --  then the type or subtype denoted by the subtype mark must not already
10808       --  impose an index constraint. The subtype mark must denote either an
10809       --  unconstrained array type or an access type whose designated type
10810       --  is such an array type... (RM 3.6.1)
10811
10812       if Is_Constrained (T) then
10813          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
10814          Constraint_OK := False;
10815
10816       else
10817          S := First (Constraints (C));
10818          while Present (S) loop
10819             Number_Of_Constraints := Number_Of_Constraints + 1;
10820             Next (S);
10821          end loop;
10822
10823          --  In either case, the index constraint must provide a discrete
10824          --  range for each index of the array type and the type of each
10825          --  discrete range must be the same as that of the corresponding
10826          --  index. (RM 3.6.1)
10827
10828          if Number_Of_Constraints /= Number_Dimensions (T) then
10829             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
10830             Constraint_OK := False;
10831
10832          else
10833             S := First (Constraints (C));
10834             Index := First_Index (T);
10835             Analyze (Index);
10836
10837             --  Apply constraints to each index type
10838
10839             for J in 1 .. Number_Of_Constraints loop
10840                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
10841                Next (Index);
10842                Next (S);
10843             end loop;
10844
10845          end if;
10846       end if;
10847
10848       if No (Def_Id) then
10849          Def_Id :=
10850            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
10851          Set_Parent (Def_Id, Related_Nod);
10852
10853       else
10854          Set_Ekind (Def_Id, E_Array_Subtype);
10855       end if;
10856
10857       Set_Size_Info      (Def_Id,                (T));
10858       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10859       Set_Etype          (Def_Id, Base_Type      (T));
10860
10861       if Constraint_OK then
10862          Set_First_Index (Def_Id, First (Constraints (C)));
10863       else
10864          Set_First_Index (Def_Id, First_Index (T));
10865       end if;
10866
10867       Set_Is_Constrained     (Def_Id, True);
10868       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
10869       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10870
10871       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
10872       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
10873
10874       --  A subtype does not inherit the packed_array_type of is parent. We
10875       --  need to initialize the attribute because if Def_Id is previously
10876       --  analyzed through a limited_with clause, it will have the attributes
10877       --  of an incomplete type, one of which is an Elist that overlaps the
10878       --  Packed_Array_Type field.
10879
10880       Set_Packed_Array_Type (Def_Id, Empty);
10881
10882       --  Build a freeze node if parent still needs one. Also make sure that
10883       --  the Depends_On_Private status is set because the subtype will need
10884       --  reprocessing at the time the base type does, and also we must set a
10885       --  conditional delay.
10886
10887       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
10888       Conditional_Delay (Def_Id, T);
10889    end Constrain_Array;
10890
10891    ------------------------------
10892    -- Constrain_Component_Type --
10893    ------------------------------
10894
10895    function Constrain_Component_Type
10896      (Comp            : Entity_Id;
10897       Constrained_Typ : Entity_Id;
10898       Related_Node    : Node_Id;
10899       Typ             : Entity_Id;
10900       Constraints     : Elist_Id) return Entity_Id
10901    is
10902       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
10903       Compon_Type : constant Entity_Id := Etype (Comp);
10904
10905       function Build_Constrained_Array_Type
10906         (Old_Type : Entity_Id) return Entity_Id;
10907       --  If Old_Type is an array type, one of whose indexes is constrained
10908       --  by a discriminant, build an Itype whose constraint replaces the
10909       --  discriminant with its value in the constraint.
10910
10911       function Build_Constrained_Discriminated_Type
10912         (Old_Type : Entity_Id) return Entity_Id;
10913       --  Ditto for record components
10914
10915       function Build_Constrained_Access_Type
10916         (Old_Type : Entity_Id) return Entity_Id;
10917       --  Ditto for access types. Makes use of previous two functions, to
10918       --  constrain designated type.
10919
10920       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
10921       --  T is an array or discriminated type, C is a list of constraints
10922       --  that apply to T. This routine builds the constrained subtype.
10923
10924       function Is_Discriminant (Expr : Node_Id) return Boolean;
10925       --  Returns True if Expr is a discriminant
10926
10927       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
10928       --  Find the value of discriminant Discrim in Constraint
10929
10930       -----------------------------------
10931       -- Build_Constrained_Access_Type --
10932       -----------------------------------
10933
10934       function Build_Constrained_Access_Type
10935         (Old_Type : Entity_Id) return Entity_Id
10936       is
10937          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
10938          Itype         : Entity_Id;
10939          Desig_Subtype : Entity_Id;
10940          Scop          : Entity_Id;
10941
10942       begin
10943          --  if the original access type was not embedded in the enclosing
10944          --  type definition, there is no need to produce a new access
10945          --  subtype. In fact every access type with an explicit constraint
10946          --  generates an itype whose scope is the enclosing record.
10947
10948          if not Is_Type (Scope (Old_Type)) then
10949             return Old_Type;
10950
10951          elsif Is_Array_Type (Desig_Type) then
10952             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
10953
10954          elsif Has_Discriminants (Desig_Type) then
10955
10956             --  This may be an access type to an enclosing record type for
10957             --  which we are constructing the constrained components. Return
10958             --  the enclosing record subtype. This is not always correct,
10959             --  but avoids infinite recursion. ???
10960
10961             Desig_Subtype := Any_Type;
10962
10963             for J in reverse 0 .. Scope_Stack.Last loop
10964                Scop := Scope_Stack.Table (J).Entity;
10965
10966                if Is_Type (Scop)
10967                  and then Base_Type (Scop) = Base_Type (Desig_Type)
10968                then
10969                   Desig_Subtype := Scop;
10970                end if;
10971
10972                exit when not Is_Type (Scop);
10973             end loop;
10974
10975             if Desig_Subtype = Any_Type then
10976                Desig_Subtype :=
10977                  Build_Constrained_Discriminated_Type (Desig_Type);
10978             end if;
10979
10980          else
10981             return Old_Type;
10982          end if;
10983
10984          if Desig_Subtype /= Desig_Type then
10985
10986             --  The Related_Node better be here or else we won't be able
10987             --  to attach new itypes to a node in the tree.
10988
10989             pragma Assert (Present (Related_Node));
10990
10991             Itype := Create_Itype (E_Access_Subtype, Related_Node);
10992
10993             Set_Etype                    (Itype, Base_Type      (Old_Type));
10994             Set_Size_Info                (Itype,                (Old_Type));
10995             Set_Directly_Designated_Type (Itype, Desig_Subtype);
10996             Set_Depends_On_Private       (Itype, Has_Private_Component
10997                                                                 (Old_Type));
10998             Set_Is_Access_Constant       (Itype, Is_Access_Constant
10999                                                                 (Old_Type));
11000
11001             --  The new itype needs freezing when it depends on a not frozen
11002             --  type and the enclosing subtype needs freezing.
11003
11004             if Has_Delayed_Freeze (Constrained_Typ)
11005               and then not Is_Frozen (Constrained_Typ)
11006             then
11007                Conditional_Delay (Itype, Base_Type (Old_Type));
11008             end if;
11009
11010             return Itype;
11011
11012          else
11013             return Old_Type;
11014          end if;
11015       end Build_Constrained_Access_Type;
11016
11017       ----------------------------------
11018       -- Build_Constrained_Array_Type --
11019       ----------------------------------
11020
11021       function Build_Constrained_Array_Type
11022         (Old_Type : Entity_Id) return Entity_Id
11023       is
11024          Lo_Expr     : Node_Id;
11025          Hi_Expr     : Node_Id;
11026          Old_Index   : Node_Id;
11027          Range_Node  : Node_Id;
11028          Constr_List : List_Id;
11029
11030          Need_To_Create_Itype : Boolean := False;
11031
11032       begin
11033          Old_Index := First_Index (Old_Type);
11034          while Present (Old_Index) loop
11035             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
11036
11037             if Is_Discriminant (Lo_Expr)
11038               or else Is_Discriminant (Hi_Expr)
11039             then
11040                Need_To_Create_Itype := True;
11041             end if;
11042
11043             Next_Index (Old_Index);
11044          end loop;
11045
11046          if Need_To_Create_Itype then
11047             Constr_List := New_List;
11048
11049             Old_Index := First_Index (Old_Type);
11050             while Present (Old_Index) loop
11051                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
11052
11053                if Is_Discriminant (Lo_Expr) then
11054                   Lo_Expr := Get_Discr_Value (Lo_Expr);
11055                end if;
11056
11057                if Is_Discriminant (Hi_Expr) then
11058                   Hi_Expr := Get_Discr_Value (Hi_Expr);
11059                end if;
11060
11061                Range_Node :=
11062                  Make_Range
11063                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
11064
11065                Append (Range_Node, To => Constr_List);
11066
11067                Next_Index (Old_Index);
11068             end loop;
11069
11070             return Build_Subtype (Old_Type, Constr_List);
11071
11072          else
11073             return Old_Type;
11074          end if;
11075       end Build_Constrained_Array_Type;
11076
11077       ------------------------------------------
11078       -- Build_Constrained_Discriminated_Type --
11079       ------------------------------------------
11080
11081       function Build_Constrained_Discriminated_Type
11082         (Old_Type : Entity_Id) return Entity_Id
11083       is
11084          Expr           : Node_Id;
11085          Constr_List    : List_Id;
11086          Old_Constraint : Elmt_Id;
11087
11088          Need_To_Create_Itype : Boolean := False;
11089
11090       begin
11091          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
11092          while Present (Old_Constraint) loop
11093             Expr := Node (Old_Constraint);
11094
11095             if Is_Discriminant (Expr) then
11096                Need_To_Create_Itype := True;
11097             end if;
11098
11099             Next_Elmt (Old_Constraint);
11100          end loop;
11101
11102          if Need_To_Create_Itype then
11103             Constr_List := New_List;
11104
11105             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
11106             while Present (Old_Constraint) loop
11107                Expr := Node (Old_Constraint);
11108
11109                if Is_Discriminant (Expr) then
11110                   Expr := Get_Discr_Value (Expr);
11111                end if;
11112
11113                Append (New_Copy_Tree (Expr), To => Constr_List);
11114
11115                Next_Elmt (Old_Constraint);
11116             end loop;
11117
11118             return Build_Subtype (Old_Type, Constr_List);
11119
11120          else
11121             return Old_Type;
11122          end if;
11123       end Build_Constrained_Discriminated_Type;
11124
11125       -------------------
11126       -- Build_Subtype --
11127       -------------------
11128
11129       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
11130          Indic       : Node_Id;
11131          Subtyp_Decl : Node_Id;
11132          Def_Id      : Entity_Id;
11133          Btyp        : Entity_Id := Base_Type (T);
11134
11135       begin
11136          --  The Related_Node better be here or else we won't be able to
11137          --  attach new itypes to a node in the tree.
11138
11139          pragma Assert (Present (Related_Node));
11140
11141          --  If the view of the component's type is incomplete or private
11142          --  with unknown discriminants, then the constraint must be applied
11143          --  to the full type.
11144
11145          if Has_Unknown_Discriminants (Btyp)
11146            and then Present (Underlying_Type (Btyp))
11147          then
11148             Btyp := Underlying_Type (Btyp);
11149          end if;
11150
11151          Indic :=
11152            Make_Subtype_Indication (Loc,
11153              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
11154              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
11155
11156          Def_Id := Create_Itype (Ekind (T), Related_Node);
11157
11158          Subtyp_Decl :=
11159            Make_Subtype_Declaration (Loc,
11160              Defining_Identifier => Def_Id,
11161              Subtype_Indication  => Indic);
11162
11163          Set_Parent (Subtyp_Decl, Parent (Related_Node));
11164
11165          --  Itypes must be analyzed with checks off (see package Itypes)
11166
11167          Analyze (Subtyp_Decl, Suppress => All_Checks);
11168
11169          return Def_Id;
11170       end Build_Subtype;
11171
11172       ---------------------
11173       -- Get_Discr_Value --
11174       ---------------------
11175
11176       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
11177          D : Entity_Id;
11178          E : Elmt_Id;
11179
11180       begin
11181          --  The discriminant may be declared for the type, in which case we
11182          --  find it by iterating over the list of discriminants. If the
11183          --  discriminant is inherited from a parent type, it appears as the
11184          --  corresponding discriminant of the current type. This will be the
11185          --  case when constraining an inherited component whose constraint is
11186          --  given by a discriminant of the parent.
11187
11188          D := First_Discriminant (Typ);
11189          E := First_Elmt (Constraints);
11190
11191          while Present (D) loop
11192             if D = Entity (Discrim)
11193               or else D = CR_Discriminant (Entity (Discrim))
11194               or else Corresponding_Discriminant (D) = Entity (Discrim)
11195             then
11196                return Node (E);
11197             end if;
11198
11199             Next_Discriminant (D);
11200             Next_Elmt (E);
11201          end loop;
11202
11203          --  The Corresponding_Discriminant mechanism is incomplete, because
11204          --  the correspondence between new and old discriminants is not one
11205          --  to one: one new discriminant can constrain several old ones. In
11206          --  that case, scan sequentially the stored_constraint, the list of
11207          --  discriminants of the parents, and the constraints.
11208          --  Previous code checked for the present of the Stored_Constraint
11209          --  list for the derived type, but did not use it at all. Should it
11210          --  be present when the component is a discriminated task type?
11211
11212          if Is_Derived_Type (Typ)
11213            and then Scope (Entity (Discrim)) = Etype (Typ)
11214          then
11215             D := First_Discriminant (Etype (Typ));
11216             E := First_Elmt (Constraints);
11217             while Present (D) loop
11218                if D = Entity (Discrim) then
11219                   return Node (E);
11220                end if;
11221
11222                Next_Discriminant (D);
11223                Next_Elmt (E);
11224             end loop;
11225          end if;
11226
11227          --  Something is wrong if we did not find the value
11228
11229          raise Program_Error;
11230       end Get_Discr_Value;
11231
11232       ---------------------
11233       -- Is_Discriminant --
11234       ---------------------
11235
11236       function Is_Discriminant (Expr : Node_Id) return Boolean is
11237          Discrim_Scope : Entity_Id;
11238
11239       begin
11240          if Denotes_Discriminant (Expr) then
11241             Discrim_Scope := Scope (Entity (Expr));
11242
11243             --  Either we have a reference to one of Typ's discriminants,
11244
11245             pragma Assert (Discrim_Scope = Typ
11246
11247                --  or to the discriminants of the parent type, in the case
11248                --  of a derivation of a tagged type with variants.
11249
11250                or else Discrim_Scope = Etype (Typ)
11251                or else Full_View (Discrim_Scope) = Etype (Typ)
11252
11253                --  or same as above for the case where the discriminants
11254                --  were declared in Typ's private view.
11255
11256                or else (Is_Private_Type (Discrim_Scope)
11257                         and then Chars (Discrim_Scope) = Chars (Typ))
11258
11259                --  or else we are deriving from the full view and the
11260                --  discriminant is declared in the private entity.
11261
11262                or else (Is_Private_Type (Typ)
11263                          and then Chars (Discrim_Scope) = Chars (Typ))
11264
11265                --  Or we are constrained the corresponding record of a
11266                --  synchronized type that completes a private declaration.
11267
11268                or else (Is_Concurrent_Record_Type (Typ)
11269                          and then
11270                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
11271
11272                --  or we have a class-wide type, in which case make sure the
11273                --  discriminant found belongs to the root type.
11274
11275                or else (Is_Class_Wide_Type (Typ)
11276                          and then Etype (Typ) = Discrim_Scope));
11277
11278             return True;
11279          end if;
11280
11281          --  In all other cases we have something wrong
11282
11283          return False;
11284       end Is_Discriminant;
11285
11286    --  Start of processing for Constrain_Component_Type
11287
11288    begin
11289       if Nkind (Parent (Comp)) = N_Component_Declaration
11290         and then Comes_From_Source (Parent (Comp))
11291         and then Comes_From_Source
11292           (Subtype_Indication (Component_Definition (Parent (Comp))))
11293         and then
11294           Is_Entity_Name
11295             (Subtype_Indication (Component_Definition (Parent (Comp))))
11296       then
11297          return Compon_Type;
11298
11299       elsif Is_Array_Type (Compon_Type) then
11300          return Build_Constrained_Array_Type (Compon_Type);
11301
11302       elsif Has_Discriminants (Compon_Type) then
11303          return Build_Constrained_Discriminated_Type (Compon_Type);
11304
11305       elsif Is_Access_Type (Compon_Type) then
11306          return Build_Constrained_Access_Type (Compon_Type);
11307
11308       else
11309          return Compon_Type;
11310       end if;
11311    end Constrain_Component_Type;
11312
11313    --------------------------
11314    -- Constrain_Concurrent --
11315    --------------------------
11316
11317    --  For concurrent types, the associated record value type carries the same
11318    --  discriminants, so when we constrain a concurrent type, we must constrain
11319    --  the corresponding record type as well.
11320
11321    procedure Constrain_Concurrent
11322      (Def_Id      : in out Entity_Id;
11323       SI          : Node_Id;
11324       Related_Nod : Node_Id;
11325       Related_Id  : Entity_Id;
11326       Suffix      : Character)
11327    is
11328       --  Retrieve Base_Type to ensure getting to the concurrent type in the
11329       --  case of a private subtype (needed when only doing semantic analysis).
11330
11331       T_Ent : Entity_Id := Base_Type (Entity (Subtype_Mark (SI)));
11332       T_Val : Entity_Id;
11333
11334    begin
11335       if Ekind (T_Ent) in Access_Kind then
11336          T_Ent := Designated_Type (T_Ent);
11337       end if;
11338
11339       T_Val := Corresponding_Record_Type (T_Ent);
11340
11341       if Present (T_Val) then
11342
11343          if No (Def_Id) then
11344             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11345          end if;
11346
11347          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11348
11349          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
11350          Set_Corresponding_Record_Type (Def_Id,
11351            Constrain_Corresponding_Record
11352              (Def_Id, T_Val, Related_Nod, Related_Id));
11353
11354       else
11355          --  If there is no associated record, expansion is disabled and this
11356          --  is a generic context. Create a subtype in any case, so that
11357          --  semantic analysis can proceed.
11358
11359          if No (Def_Id) then
11360             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11361          end if;
11362
11363          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11364       end if;
11365    end Constrain_Concurrent;
11366
11367    ------------------------------------
11368    -- Constrain_Corresponding_Record --
11369    ------------------------------------
11370
11371    function Constrain_Corresponding_Record
11372      (Prot_Subt   : Entity_Id;
11373       Corr_Rec    : Entity_Id;
11374       Related_Nod : Node_Id;
11375       Related_Id  : Entity_Id) return Entity_Id
11376    is
11377       T_Sub : constant Entity_Id :=
11378                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
11379
11380    begin
11381       Set_Etype             (T_Sub, Corr_Rec);
11382       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
11383       Set_Is_Constrained    (T_Sub, True);
11384       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
11385       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
11386
11387       --  As elsewhere, we do not want to create a freeze node for this itype
11388       --  if it is created for a constrained component of an enclosing record
11389       --  because references to outer discriminants will appear out of scope.
11390
11391       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
11392          Conditional_Delay (T_Sub, Corr_Rec);
11393       else
11394          Set_Is_Frozen (T_Sub);
11395       end if;
11396
11397       if Has_Discriminants (Prot_Subt) then -- False only if errors.
11398          Set_Discriminant_Constraint
11399            (T_Sub, Discriminant_Constraint (Prot_Subt));
11400          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
11401          Create_Constrained_Components
11402            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
11403       end if;
11404
11405       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
11406
11407       return T_Sub;
11408    end Constrain_Corresponding_Record;
11409
11410    -----------------------
11411    -- Constrain_Decimal --
11412    -----------------------
11413
11414    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
11415       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
11416       C           : constant Node_Id    := Constraint (S);
11417       Loc         : constant Source_Ptr := Sloc (C);
11418       Range_Expr  : Node_Id;
11419       Digits_Expr : Node_Id;
11420       Digits_Val  : Uint;
11421       Bound_Val   : Ureal;
11422
11423    begin
11424       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
11425
11426       if Nkind (C) = N_Range_Constraint then
11427          Range_Expr := Range_Expression (C);
11428          Digits_Val := Digits_Value (T);
11429
11430       else
11431          pragma Assert (Nkind (C) = N_Digits_Constraint);
11432
11433          Check_SPARK_Restriction ("digits constraint is not allowed", S);
11434
11435          Digits_Expr := Digits_Expression (C);
11436          Analyze_And_Resolve (Digits_Expr, Any_Integer);
11437
11438          Check_Digits_Expression (Digits_Expr);
11439          Digits_Val := Expr_Value (Digits_Expr);
11440
11441          if Digits_Val > Digits_Value (T) then
11442             Error_Msg_N
11443                ("digits expression is incompatible with subtype", C);
11444             Digits_Val := Digits_Value (T);
11445          end if;
11446
11447          if Present (Range_Constraint (C)) then
11448             Range_Expr := Range_Expression (Range_Constraint (C));
11449          else
11450             Range_Expr := Empty;
11451          end if;
11452       end if;
11453
11454       Set_Etype            (Def_Id, Base_Type        (T));
11455       Set_Size_Info        (Def_Id,                  (T));
11456       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11457       Set_Delta_Value      (Def_Id, Delta_Value      (T));
11458       Set_Scale_Value      (Def_Id, Scale_Value      (T));
11459       Set_Small_Value      (Def_Id, Small_Value      (T));
11460       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
11461       Set_Digits_Value     (Def_Id, Digits_Val);
11462
11463       --  Manufacture range from given digits value if no range present
11464
11465       if No (Range_Expr) then
11466          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
11467          Range_Expr :=
11468            Make_Range (Loc,
11469              Low_Bound =>
11470                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
11471              High_Bound =>
11472                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
11473       end if;
11474
11475       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
11476       Set_Discrete_RM_Size (Def_Id);
11477
11478       --  Unconditionally delay the freeze, since we cannot set size
11479       --  information in all cases correctly until the freeze point.
11480
11481       Set_Has_Delayed_Freeze (Def_Id);
11482    end Constrain_Decimal;
11483
11484    ----------------------------------
11485    -- Constrain_Discriminated_Type --
11486    ----------------------------------
11487
11488    procedure Constrain_Discriminated_Type
11489      (Def_Id      : Entity_Id;
11490       S           : Node_Id;
11491       Related_Nod : Node_Id;
11492       For_Access  : Boolean := False)
11493    is
11494       E     : constant Entity_Id := Entity (Subtype_Mark (S));
11495       T     : Entity_Id;
11496       C     : Node_Id;
11497       Elist : Elist_Id := New_Elmt_List;
11498
11499       procedure Fixup_Bad_Constraint;
11500       --  This is called after finding a bad constraint, and after having
11501       --  posted an appropriate error message. The mission is to leave the
11502       --  entity T in as reasonable state as possible!
11503
11504       --------------------------
11505       -- Fixup_Bad_Constraint --
11506       --------------------------
11507
11508       procedure Fixup_Bad_Constraint is
11509       begin
11510          --  Set a reasonable Ekind for the entity. For an incomplete type,
11511          --  we can't do much, but for other types, we can set the proper
11512          --  corresponding subtype kind.
11513
11514          if Ekind (T) = E_Incomplete_Type then
11515             Set_Ekind (Def_Id, Ekind (T));
11516          else
11517             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
11518          end if;
11519
11520          --  Set Etype to the known type, to reduce chances of cascaded errors
11521
11522          Set_Etype (Def_Id, E);
11523          Set_Error_Posted (Def_Id);
11524       end Fixup_Bad_Constraint;
11525
11526    --  Start of processing for Constrain_Discriminated_Type
11527
11528    begin
11529       C := Constraint (S);
11530
11531       --  A discriminant constraint is only allowed in a subtype indication,
11532       --  after a subtype mark. This subtype mark must denote either a type
11533       --  with discriminants, or an access type whose designated type is a
11534       --  type with discriminants. A discriminant constraint specifies the
11535       --  values of these discriminants (RM 3.7.2(5)).
11536
11537       T := Base_Type (Entity (Subtype_Mark (S)));
11538
11539       if Ekind (T) in Access_Kind then
11540          T := Designated_Type (T);
11541       end if;
11542
11543       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
11544       --  Avoid generating an error for access-to-incomplete subtypes.
11545
11546       if Ada_Version >= Ada_2005
11547         and then Ekind (T) = E_Incomplete_Type
11548         and then Nkind (Parent (S)) = N_Subtype_Declaration
11549         and then not Is_Itype (Def_Id)
11550       then
11551          --  A little sanity check, emit an error message if the type
11552          --  has discriminants to begin with. Type T may be a regular
11553          --  incomplete type or imported via a limited with clause.
11554
11555          if Has_Discriminants (T)
11556            or else
11557              (From_With_Type (T)
11558                 and then Present (Non_Limited_View (T))
11559                 and then Nkind (Parent (Non_Limited_View (T))) =
11560                            N_Full_Type_Declaration
11561                 and then Present (Discriminant_Specifications
11562                           (Parent (Non_Limited_View (T)))))
11563          then
11564             Error_Msg_N
11565               ("(Ada 2005) incomplete subtype may not be constrained", C);
11566          else
11567             Error_Msg_N ("invalid constraint: type has no discriminant", C);
11568          end if;
11569
11570          Fixup_Bad_Constraint;
11571          return;
11572
11573       --  Check that the type has visible discriminants. The type may be
11574       --  a private type with unknown discriminants whose full view has
11575       --  discriminants which are invisible.
11576
11577       elsif not Has_Discriminants (T)
11578         or else
11579           (Has_Unknown_Discriminants (T)
11580              and then Is_Private_Type (T))
11581       then
11582          Error_Msg_N ("invalid constraint: type has no discriminant", C);
11583          Fixup_Bad_Constraint;
11584          return;
11585
11586       elsif Is_Constrained (E)
11587         or else (Ekind (E) = E_Class_Wide_Subtype
11588                   and then Present (Discriminant_Constraint (E)))
11589       then
11590          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
11591          Fixup_Bad_Constraint;
11592          return;
11593       end if;
11594
11595       --  T may be an unconstrained subtype (e.g. a generic actual).
11596       --  Constraint applies to the base type.
11597
11598       T := Base_Type (T);
11599
11600       Elist := Build_Discriminant_Constraints (T, S);
11601
11602       --  If the list returned was empty we had an error in building the
11603       --  discriminant constraint. We have also already signalled an error
11604       --  in the incomplete type case
11605
11606       if Is_Empty_Elmt_List (Elist) then
11607          Fixup_Bad_Constraint;
11608          return;
11609       end if;
11610
11611       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
11612    end Constrain_Discriminated_Type;
11613
11614    ---------------------------
11615    -- Constrain_Enumeration --
11616    ---------------------------
11617
11618    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
11619       T : constant Entity_Id := Entity (Subtype_Mark (S));
11620       C : constant Node_Id   := Constraint (S);
11621
11622    begin
11623       Set_Ekind (Def_Id, E_Enumeration_Subtype);
11624
11625       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
11626
11627       Set_Etype             (Def_Id, Base_Type         (T));
11628       Set_Size_Info         (Def_Id,                   (T));
11629       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
11630       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11631
11632       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11633
11634       Set_Discrete_RM_Size (Def_Id);
11635    end Constrain_Enumeration;
11636
11637    ----------------------
11638    -- Constrain_Float --
11639    ----------------------
11640
11641    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
11642       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11643       C    : Node_Id;
11644       D    : Node_Id;
11645       Rais : Node_Id;
11646
11647    begin
11648       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
11649
11650       Set_Etype          (Def_Id, Base_Type      (T));
11651       Set_Size_Info      (Def_Id,                (T));
11652       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11653
11654       --  Process the constraint
11655
11656       C := Constraint (S);
11657
11658       --  Digits constraint present
11659
11660       if Nkind (C) = N_Digits_Constraint then
11661
11662          Check_SPARK_Restriction ("digits constraint is not allowed", S);
11663          Check_Restriction (No_Obsolescent_Features, C);
11664
11665          if Warn_On_Obsolescent_Feature then
11666             Error_Msg_N
11667               ("subtype digits constraint is an " &
11668                "obsolescent feature (RM J.3(8))?", C);
11669          end if;
11670
11671          D := Digits_Expression (C);
11672          Analyze_And_Resolve (D, Any_Integer);
11673          Check_Digits_Expression (D);
11674          Set_Digits_Value (Def_Id, Expr_Value (D));
11675
11676          --  Check that digits value is in range. Obviously we can do this
11677          --  at compile time, but it is strictly a runtime check, and of
11678          --  course there is an ACVC test that checks this!
11679
11680          if Digits_Value (Def_Id) > Digits_Value (T) then
11681             Error_Msg_Uint_1 := Digits_Value (T);
11682             Error_Msg_N ("?digits value is too large, maximum is ^", D);
11683             Rais :=
11684               Make_Raise_Constraint_Error (Sloc (D),
11685                 Reason => CE_Range_Check_Failed);
11686             Insert_Action (Declaration_Node (Def_Id), Rais);
11687          end if;
11688
11689          C := Range_Constraint (C);
11690
11691       --  No digits constraint present
11692
11693       else
11694          Set_Digits_Value (Def_Id, Digits_Value (T));
11695       end if;
11696
11697       --  Range constraint present
11698
11699       if Nkind (C) = N_Range_Constraint then
11700          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11701
11702       --  No range constraint present
11703
11704       else
11705          pragma Assert (No (C));
11706          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11707       end if;
11708
11709       Set_Is_Constrained (Def_Id);
11710    end Constrain_Float;
11711
11712    ---------------------
11713    -- Constrain_Index --
11714    ---------------------
11715
11716    procedure Constrain_Index
11717      (Index        : Node_Id;
11718       S            : Node_Id;
11719       Related_Nod  : Node_Id;
11720       Related_Id   : Entity_Id;
11721       Suffix       : Character;
11722       Suffix_Index : Nat)
11723    is
11724       Def_Id : Entity_Id;
11725       R      : Node_Id := Empty;
11726       T      : constant Entity_Id := Etype (Index);
11727
11728    begin
11729       if Nkind (S) = N_Range
11730         or else
11731           (Nkind (S) = N_Attribute_Reference
11732             and then Attribute_Name (S) = Name_Range)
11733       then
11734          --  A Range attribute will be transformed into N_Range by Resolve
11735
11736          Analyze (S);
11737          Set_Etype (S, T);
11738          R := S;
11739
11740          Process_Range_Expr_In_Decl (R, T, Empty_List);
11741
11742          if not Error_Posted (S)
11743            and then
11744              (Nkind (S) /= N_Range
11745                or else not Covers (T, (Etype (Low_Bound (S))))
11746                or else not Covers (T, (Etype (High_Bound (S)))))
11747          then
11748             if Base_Type (T) /= Any_Type
11749               and then Etype (Low_Bound (S)) /= Any_Type
11750               and then Etype (High_Bound (S)) /= Any_Type
11751             then
11752                Error_Msg_N ("range expected", S);
11753             end if;
11754          end if;
11755
11756       elsif Nkind (S) = N_Subtype_Indication then
11757
11758          --  The parser has verified that this is a discrete indication
11759
11760          Resolve_Discrete_Subtype_Indication (S, T);
11761          R := Range_Expression (Constraint (S));
11762
11763          --  Capture values of bounds and generate temporaries for them if
11764          --  needed, since checks may cause duplication of the expressions
11765          --  which must not be reevaluated.
11766
11767          if Expander_Active then
11768             Force_Evaluation (Low_Bound (R));
11769             Force_Evaluation (High_Bound (R));
11770          end if;
11771
11772       elsif Nkind (S) = N_Discriminant_Association then
11773
11774          --  Syntactically valid in subtype indication
11775
11776          Error_Msg_N ("invalid index constraint", S);
11777          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11778          return;
11779
11780       --  Subtype_Mark case, no anonymous subtypes to construct
11781
11782       else
11783          Analyze (S);
11784
11785          if Is_Entity_Name (S) then
11786             if not Is_Type (Entity (S)) then
11787                Error_Msg_N ("expect subtype mark for index constraint", S);
11788
11789             elsif Base_Type (Entity (S)) /= Base_Type (T) then
11790                Wrong_Type (S, Base_Type (T));
11791
11792             --  Check error of subtype with predicate in index constraint
11793
11794             else
11795                Bad_Predicated_Subtype_Use
11796                  ("subtype& has predicate, not allowed in index constraint",
11797                   S, Entity (S));
11798             end if;
11799
11800             return;
11801
11802          else
11803             Error_Msg_N ("invalid index constraint", S);
11804             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11805             return;
11806          end if;
11807       end if;
11808
11809       Def_Id :=
11810         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
11811
11812       Set_Etype (Def_Id, Base_Type (T));
11813
11814       if Is_Modular_Integer_Type (T) then
11815          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11816
11817       elsif Is_Integer_Type (T) then
11818          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11819
11820       else
11821          Set_Ekind (Def_Id, E_Enumeration_Subtype);
11822          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11823          Set_First_Literal     (Def_Id, First_Literal (T));
11824       end if;
11825
11826       Set_Size_Info      (Def_Id,                (T));
11827       Set_RM_Size        (Def_Id, RM_Size        (T));
11828       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11829
11830       Set_Scalar_Range   (Def_Id, R);
11831
11832       Set_Etype (S, Def_Id);
11833       Set_Discrete_RM_Size (Def_Id);
11834    end Constrain_Index;
11835
11836    -----------------------
11837    -- Constrain_Integer --
11838    -----------------------
11839
11840    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
11841       T : constant Entity_Id := Entity (Subtype_Mark (S));
11842       C : constant Node_Id   := Constraint (S);
11843
11844    begin
11845       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11846
11847       if Is_Modular_Integer_Type (T) then
11848          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11849       else
11850          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11851       end if;
11852
11853       Set_Etype            (Def_Id, Base_Type        (T));
11854       Set_Size_Info        (Def_Id,                  (T));
11855       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11856       Set_Discrete_RM_Size (Def_Id);
11857    end Constrain_Integer;
11858
11859    ------------------------------
11860    -- Constrain_Ordinary_Fixed --
11861    ------------------------------
11862
11863    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
11864       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11865       C    : Node_Id;
11866       D    : Node_Id;
11867       Rais : Node_Id;
11868
11869    begin
11870       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
11871       Set_Etype          (Def_Id, Base_Type        (T));
11872       Set_Size_Info      (Def_Id,                  (T));
11873       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
11874       Set_Small_Value    (Def_Id, Small_Value      (T));
11875
11876       --  Process the constraint
11877
11878       C := Constraint (S);
11879
11880       --  Delta constraint present
11881
11882       if Nkind (C) = N_Delta_Constraint then
11883
11884          Check_SPARK_Restriction ("delta constraint is not allowed", S);
11885          Check_Restriction (No_Obsolescent_Features, C);
11886
11887          if Warn_On_Obsolescent_Feature then
11888             Error_Msg_S
11889               ("subtype delta constraint is an " &
11890                "obsolescent feature (RM J.3(7))?");
11891          end if;
11892
11893          D := Delta_Expression (C);
11894          Analyze_And_Resolve (D, Any_Real);
11895          Check_Delta_Expression (D);
11896          Set_Delta_Value (Def_Id, Expr_Value_R (D));
11897
11898          --  Check that delta value is in range. Obviously we can do this
11899          --  at compile time, but it is strictly a runtime check, and of
11900          --  course there is an ACVC test that checks this!
11901
11902          if Delta_Value (Def_Id) < Delta_Value (T) then
11903             Error_Msg_N ("?delta value is too small", D);
11904             Rais :=
11905               Make_Raise_Constraint_Error (Sloc (D),
11906                 Reason => CE_Range_Check_Failed);
11907             Insert_Action (Declaration_Node (Def_Id), Rais);
11908          end if;
11909
11910          C := Range_Constraint (C);
11911
11912       --  No delta constraint present
11913
11914       else
11915          Set_Delta_Value (Def_Id, Delta_Value (T));
11916       end if;
11917
11918       --  Range constraint present
11919
11920       if Nkind (C) = N_Range_Constraint then
11921          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11922
11923       --  No range constraint present
11924
11925       else
11926          pragma Assert (No (C));
11927          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11928
11929       end if;
11930
11931       Set_Discrete_RM_Size (Def_Id);
11932
11933       --  Unconditionally delay the freeze, since we cannot set size
11934       --  information in all cases correctly until the freeze point.
11935
11936       Set_Has_Delayed_Freeze (Def_Id);
11937    end Constrain_Ordinary_Fixed;
11938
11939    -----------------------
11940    -- Contain_Interface --
11941    -----------------------
11942
11943    function Contain_Interface
11944      (Iface  : Entity_Id;
11945       Ifaces : Elist_Id) return Boolean
11946    is
11947       Iface_Elmt : Elmt_Id;
11948
11949    begin
11950       if Present (Ifaces) then
11951          Iface_Elmt := First_Elmt (Ifaces);
11952          while Present (Iface_Elmt) loop
11953             if Node (Iface_Elmt) = Iface then
11954                return True;
11955             end if;
11956
11957             Next_Elmt (Iface_Elmt);
11958          end loop;
11959       end if;
11960
11961       return False;
11962    end Contain_Interface;
11963
11964    ---------------------------
11965    -- Convert_Scalar_Bounds --
11966    ---------------------------
11967
11968    procedure Convert_Scalar_Bounds
11969      (N            : Node_Id;
11970       Parent_Type  : Entity_Id;
11971       Derived_Type : Entity_Id;
11972       Loc          : Source_Ptr)
11973    is
11974       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
11975
11976       Lo  : Node_Id;
11977       Hi  : Node_Id;
11978       Rng : Node_Id;
11979
11980    begin
11981       --  Defend against previous errors
11982
11983       if No (Scalar_Range (Derived_Type)) then
11984          return;
11985       end if;
11986
11987       Lo := Build_Scalar_Bound
11988               (Type_Low_Bound (Derived_Type),
11989                Parent_Type, Implicit_Base);
11990
11991       Hi := Build_Scalar_Bound
11992               (Type_High_Bound (Derived_Type),
11993                Parent_Type, Implicit_Base);
11994
11995       Rng :=
11996         Make_Range (Loc,
11997           Low_Bound  => Lo,
11998           High_Bound => Hi);
11999
12000       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
12001
12002       Set_Parent (Rng, N);
12003       Set_Scalar_Range (Derived_Type, Rng);
12004
12005       --  Analyze the bounds
12006
12007       Analyze_And_Resolve (Lo, Implicit_Base);
12008       Analyze_And_Resolve (Hi, Implicit_Base);
12009
12010       --  Analyze the range itself, except that we do not analyze it if
12011       --  the bounds are real literals, and we have a fixed-point type.
12012       --  The reason for this is that we delay setting the bounds in this
12013       --  case till we know the final Small and Size values (see circuit
12014       --  in Freeze.Freeze_Fixed_Point_Type for further details).
12015
12016       if Is_Fixed_Point_Type (Parent_Type)
12017         and then Nkind (Lo) = N_Real_Literal
12018         and then Nkind (Hi) = N_Real_Literal
12019       then
12020          return;
12021
12022       --  Here we do the analysis of the range
12023
12024       --  Note: we do this manually, since if we do a normal Analyze and
12025       --  Resolve call, there are problems with the conversions used for
12026       --  the derived type range.
12027
12028       else
12029          Set_Etype    (Rng, Implicit_Base);
12030          Set_Analyzed (Rng, True);
12031       end if;
12032    end Convert_Scalar_Bounds;
12033
12034    -------------------
12035    -- Copy_And_Swap --
12036    -------------------
12037
12038    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
12039    begin
12040       --  Initialize new full declaration entity by copying the pertinent
12041       --  fields of the corresponding private declaration entity.
12042
12043       --  We temporarily set Ekind to a value appropriate for a type to
12044       --  avoid assert failures in Einfo from checking for setting type
12045       --  attributes on something that is not a type. Ekind (Priv) is an
12046       --  appropriate choice, since it allowed the attributes to be set
12047       --  in the first place. This Ekind value will be modified later.
12048
12049       Set_Ekind (Full, Ekind (Priv));
12050
12051       --  Also set Etype temporarily to Any_Type, again, in the absence
12052       --  of errors, it will be properly reset, and if there are errors,
12053       --  then we want a value of Any_Type to remain.
12054
12055       Set_Etype (Full, Any_Type);
12056
12057       --  Now start copying attributes
12058
12059       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
12060
12061       if Has_Discriminants (Full) then
12062          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
12063          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
12064       end if;
12065
12066       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
12067       Set_Homonym                    (Full, Homonym                 (Priv));
12068       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
12069       Set_Is_Public                  (Full, Is_Public               (Priv));
12070       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
12071       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
12072       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
12073       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
12074       Set_Has_Pragma_Unreferenced_Objects
12075                                      (Full, Has_Pragma_Unreferenced_Objects
12076                                                                     (Priv));
12077
12078       Conditional_Delay              (Full,                          Priv);
12079
12080       if Is_Tagged_Type (Full) then
12081          Set_Direct_Primitive_Operations (Full,
12082            Direct_Primitive_Operations (Priv));
12083
12084          if Is_Base_Type (Priv) then
12085             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
12086          end if;
12087       end if;
12088
12089       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
12090       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
12091       Set_Scope                      (Full, Scope                   (Priv));
12092       Set_Next_Entity                (Full, Next_Entity             (Priv));
12093       Set_First_Entity               (Full, First_Entity            (Priv));
12094       Set_Last_Entity                (Full, Last_Entity             (Priv));
12095
12096       --  If access types have been recorded for later handling, keep them in
12097       --  the full view so that they get handled when the full view freeze
12098       --  node is expanded.
12099
12100       if Present (Freeze_Node (Priv))
12101         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
12102       then
12103          Ensure_Freeze_Node (Full);
12104          Set_Access_Types_To_Process
12105            (Freeze_Node (Full),
12106             Access_Types_To_Process (Freeze_Node (Priv)));
12107       end if;
12108
12109       --  Swap the two entities. Now Private is the full type entity and Full
12110       --  is the private one. They will be swapped back at the end of the
12111       --  private part. This swapping ensures that the entity that is visible
12112       --  in the private part is the full declaration.
12113
12114       Exchange_Entities (Priv, Full);
12115       Append_Entity (Full, Scope (Full));
12116    end Copy_And_Swap;
12117
12118    -------------------------------------
12119    -- Copy_Array_Base_Type_Attributes --
12120    -------------------------------------
12121
12122    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
12123    begin
12124       Set_Component_Alignment      (T1, Component_Alignment      (T2));
12125       Set_Component_Type           (T1, Component_Type           (T2));
12126       Set_Component_Size           (T1, Component_Size           (T2));
12127       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
12128       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
12129       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
12130       Set_Has_Task                 (T1, Has_Task                 (T2));
12131       Set_Is_Packed                (T1, Is_Packed                (T2));
12132       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
12133       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
12134       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
12135    end Copy_Array_Base_Type_Attributes;
12136
12137    -----------------------------------
12138    -- Copy_Array_Subtype_Attributes --
12139    -----------------------------------
12140
12141    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
12142    begin
12143       Set_Size_Info (T1, T2);
12144
12145       Set_First_Index          (T1, First_Index           (T2));
12146       Set_Is_Aliased           (T1, Is_Aliased            (T2));
12147       Set_Is_Atomic            (T1, Is_Atomic             (T2));
12148       Set_Is_Volatile          (T1, Is_Volatile           (T2));
12149       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
12150       Set_Is_Constrained       (T1, Is_Constrained        (T2));
12151       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
12152       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
12153       Set_Convention           (T1, Convention            (T2));
12154       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
12155       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
12156       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
12157    end Copy_Array_Subtype_Attributes;
12158
12159    -----------------------------------
12160    -- Create_Constrained_Components --
12161    -----------------------------------
12162
12163    procedure Create_Constrained_Components
12164      (Subt        : Entity_Id;
12165       Decl_Node   : Node_Id;
12166       Typ         : Entity_Id;
12167       Constraints : Elist_Id)
12168    is
12169       Loc         : constant Source_Ptr := Sloc (Subt);
12170       Comp_List   : constant Elist_Id   := New_Elmt_List;
12171       Parent_Type : constant Entity_Id  := Etype (Typ);
12172       Assoc_List  : constant List_Id    := New_List;
12173       Discr_Val   : Elmt_Id;
12174       Errors      : Boolean;
12175       New_C       : Entity_Id;
12176       Old_C       : Entity_Id;
12177       Is_Static   : Boolean := True;
12178
12179       procedure Collect_Fixed_Components (Typ : Entity_Id);
12180       --  Collect parent type components that do not appear in a variant part
12181
12182       procedure Create_All_Components;
12183       --  Iterate over Comp_List to create the components of the subtype
12184
12185       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
12186       --  Creates a new component from Old_Compon, copying all the fields from
12187       --  it, including its Etype, inserts the new component in the Subt entity
12188       --  chain and returns the new component.
12189
12190       function Is_Variant_Record (T : Entity_Id) return Boolean;
12191       --  If true, and discriminants are static, collect only components from
12192       --  variants selected by discriminant values.
12193
12194       ------------------------------
12195       -- Collect_Fixed_Components --
12196       ------------------------------
12197
12198       procedure Collect_Fixed_Components (Typ : Entity_Id) is
12199       begin
12200       --  Build association list for discriminants, and find components of the
12201       --  variant part selected by the values of the discriminants.
12202
12203          Old_C := First_Discriminant (Typ);
12204          Discr_Val := First_Elmt (Constraints);
12205          while Present (Old_C) loop
12206             Append_To (Assoc_List,
12207               Make_Component_Association (Loc,
12208                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
12209                  Expression => New_Copy (Node (Discr_Val))));
12210
12211             Next_Elmt (Discr_Val);
12212             Next_Discriminant (Old_C);
12213          end loop;
12214
12215          --  The tag and the possible parent component are unconditionally in
12216          --  the subtype.
12217
12218          if Is_Tagged_Type (Typ)
12219            or else Has_Controlled_Component (Typ)
12220          then
12221             Old_C := First_Component (Typ);
12222             while Present (Old_C) loop
12223                if Chars ((Old_C)) = Name_uTag
12224                  or else Chars ((Old_C)) = Name_uParent
12225                then
12226                   Append_Elmt (Old_C, Comp_List);
12227                end if;
12228
12229                Next_Component (Old_C);
12230             end loop;
12231          end if;
12232       end Collect_Fixed_Components;
12233
12234       ---------------------------
12235       -- Create_All_Components --
12236       ---------------------------
12237
12238       procedure Create_All_Components is
12239          Comp : Elmt_Id;
12240
12241       begin
12242          Comp := First_Elmt (Comp_List);
12243          while Present (Comp) loop
12244             Old_C := Node (Comp);
12245             New_C := Create_Component (Old_C);
12246
12247             Set_Etype
12248               (New_C,
12249                Constrain_Component_Type
12250                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12251             Set_Is_Public (New_C, Is_Public (Subt));
12252
12253             Next_Elmt (Comp);
12254          end loop;
12255       end Create_All_Components;
12256
12257       ----------------------
12258       -- Create_Component --
12259       ----------------------
12260
12261       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
12262          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
12263
12264       begin
12265          if Ekind (Old_Compon) = E_Discriminant
12266            and then Is_Completely_Hidden (Old_Compon)
12267          then
12268             --  This is a shadow discriminant created for a discriminant of
12269             --  the parent type, which needs to be present in the subtype.
12270             --  Give the shadow discriminant an internal name that cannot
12271             --  conflict with that of visible components.
12272
12273             Set_Chars (New_Compon, New_Internal_Name ('C'));
12274          end if;
12275
12276          --  Set the parent so we have a proper link for freezing etc. This is
12277          --  not a real parent pointer, since of course our parent does not own
12278          --  up to us and reference us, we are an illegitimate child of the
12279          --  original parent!
12280
12281          Set_Parent (New_Compon, Parent (Old_Compon));
12282
12283          --  If the old component's Esize was already determined and is a
12284          --  static value, then the new component simply inherits it. Otherwise
12285          --  the old component's size may require run-time determination, but
12286          --  the new component's size still might be statically determinable
12287          --  (if, for example it has a static constraint). In that case we want
12288          --  Layout_Type to recompute the component's size, so we reset its
12289          --  size and positional fields.
12290
12291          if Frontend_Layout_On_Target
12292            and then not Known_Static_Esize (Old_Compon)
12293          then
12294             Set_Esize (New_Compon, Uint_0);
12295             Init_Normalized_First_Bit    (New_Compon);
12296             Init_Normalized_Position     (New_Compon);
12297             Init_Normalized_Position_Max (New_Compon);
12298          end if;
12299
12300          --  We do not want this node marked as Comes_From_Source, since
12301          --  otherwise it would get first class status and a separate cross-
12302          --  reference line would be generated. Illegitimate children do not
12303          --  rate such recognition.
12304
12305          Set_Comes_From_Source (New_Compon, False);
12306
12307          --  But it is a real entity, and a birth certificate must be properly
12308          --  registered by entering it into the entity list.
12309
12310          Enter_Name (New_Compon);
12311
12312          return New_Compon;
12313       end Create_Component;
12314
12315       -----------------------
12316       -- Is_Variant_Record --
12317       -----------------------
12318
12319       function Is_Variant_Record (T : Entity_Id) return Boolean is
12320       begin
12321          return Nkind (Parent (T)) = N_Full_Type_Declaration
12322            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
12323            and then Present (Component_List (Type_Definition (Parent (T))))
12324            and then
12325              Present
12326                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
12327       end Is_Variant_Record;
12328
12329    --  Start of processing for Create_Constrained_Components
12330
12331    begin
12332       pragma Assert (Subt /= Base_Type (Subt));
12333       pragma Assert (Typ = Base_Type (Typ));
12334
12335       Set_First_Entity (Subt, Empty);
12336       Set_Last_Entity  (Subt, Empty);
12337
12338       --  Check whether constraint is fully static, in which case we can
12339       --  optimize the list of components.
12340
12341       Discr_Val := First_Elmt (Constraints);
12342       while Present (Discr_Val) loop
12343          if not Is_OK_Static_Expression (Node (Discr_Val)) then
12344             Is_Static := False;
12345             exit;
12346          end if;
12347
12348          Next_Elmt (Discr_Val);
12349       end loop;
12350
12351       Set_Has_Static_Discriminants (Subt, Is_Static);
12352
12353       Push_Scope (Subt);
12354
12355       --  Inherit the discriminants of the parent type
12356
12357       Add_Discriminants : declare
12358          Num_Disc : Int;
12359          Num_Gird : Int;
12360
12361       begin
12362          Num_Disc := 0;
12363          Old_C := First_Discriminant (Typ);
12364
12365          while Present (Old_C) loop
12366             Num_Disc := Num_Disc + 1;
12367             New_C := Create_Component (Old_C);
12368             Set_Is_Public (New_C, Is_Public (Subt));
12369             Next_Discriminant (Old_C);
12370          end loop;
12371
12372          --  For an untagged derived subtype, the number of discriminants may
12373          --  be smaller than the number of inherited discriminants, because
12374          --  several of them may be renamed by a single new discriminant or
12375          --  constrained. In this case, add the hidden discriminants back into
12376          --  the subtype, because they need to be present if the optimizer of
12377          --  the GCC 4.x back-end decides to break apart assignments between
12378          --  objects using the parent view into member-wise assignments.
12379
12380          Num_Gird := 0;
12381
12382          if Is_Derived_Type (Typ)
12383            and then not Is_Tagged_Type (Typ)
12384          then
12385             Old_C := First_Stored_Discriminant (Typ);
12386
12387             while Present (Old_C) loop
12388                Num_Gird := Num_Gird + 1;
12389                Next_Stored_Discriminant (Old_C);
12390             end loop;
12391          end if;
12392
12393          if Num_Gird > Num_Disc then
12394
12395             --  Find out multiple uses of new discriminants, and add hidden
12396             --  components for the extra renamed discriminants. We recognize
12397             --  multiple uses through the Corresponding_Discriminant of a
12398             --  new discriminant: if it constrains several old discriminants,
12399             --  this field points to the last one in the parent type. The
12400             --  stored discriminants of the derived type have the same name
12401             --  as those of the parent.
12402
12403             declare
12404                Constr    : Elmt_Id;
12405                New_Discr : Entity_Id;
12406                Old_Discr : Entity_Id;
12407
12408             begin
12409                Constr    := First_Elmt (Stored_Constraint (Typ));
12410                Old_Discr := First_Stored_Discriminant (Typ);
12411                while Present (Constr) loop
12412                   if Is_Entity_Name (Node (Constr))
12413                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
12414                   then
12415                      New_Discr := Entity (Node (Constr));
12416
12417                      if Chars (Corresponding_Discriminant (New_Discr)) /=
12418                         Chars (Old_Discr)
12419                      then
12420                         --  The new discriminant has been used to rename a
12421                         --  subsequent old discriminant. Introduce a shadow
12422                         --  component for the current old discriminant.
12423
12424                         New_C := Create_Component (Old_Discr);
12425                         Set_Original_Record_Component (New_C, Old_Discr);
12426                      end if;
12427
12428                   else
12429                      --  The constraint has eliminated the old discriminant.
12430                      --  Introduce a shadow component.
12431
12432                      New_C := Create_Component (Old_Discr);
12433                      Set_Original_Record_Component (New_C, Old_Discr);
12434                   end if;
12435
12436                   Next_Elmt (Constr);
12437                   Next_Stored_Discriminant (Old_Discr);
12438                end loop;
12439             end;
12440          end if;
12441       end Add_Discriminants;
12442
12443       if Is_Static
12444         and then Is_Variant_Record (Typ)
12445       then
12446          Collect_Fixed_Components (Typ);
12447
12448          Gather_Components (
12449            Typ,
12450            Component_List (Type_Definition (Parent (Typ))),
12451            Governed_By   => Assoc_List,
12452            Into          => Comp_List,
12453            Report_Errors => Errors);
12454          pragma Assert (not Errors);
12455
12456          Create_All_Components;
12457
12458       --  If the subtype declaration is created for a tagged type derivation
12459       --  with constraints, we retrieve the record definition of the parent
12460       --  type to select the components of the proper variant.
12461
12462       elsif Is_Static
12463         and then Is_Tagged_Type (Typ)
12464         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
12465         and then
12466           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
12467         and then Is_Variant_Record (Parent_Type)
12468       then
12469          Collect_Fixed_Components (Typ);
12470
12471          Gather_Components (
12472            Typ,
12473            Component_List (Type_Definition (Parent (Parent_Type))),
12474            Governed_By   => Assoc_List,
12475            Into          => Comp_List,
12476            Report_Errors => Errors);
12477          pragma Assert (not Errors);
12478
12479          --  If the tagged derivation has a type extension, collect all the
12480          --  new components therein.
12481
12482          if Present
12483               (Record_Extension_Part (Type_Definition (Parent (Typ))))
12484          then
12485             Old_C := First_Component (Typ);
12486             while Present (Old_C) loop
12487                if Original_Record_Component (Old_C) = Old_C
12488                 and then Chars (Old_C) /= Name_uTag
12489                 and then Chars (Old_C) /= Name_uParent
12490                then
12491                   Append_Elmt (Old_C, Comp_List);
12492                end if;
12493
12494                Next_Component (Old_C);
12495             end loop;
12496          end if;
12497
12498          Create_All_Components;
12499
12500       else
12501          --  If discriminants are not static, or if this is a multi-level type
12502          --  extension, we have to include all components of the parent type.
12503
12504          Old_C := First_Component (Typ);
12505          while Present (Old_C) loop
12506             New_C := Create_Component (Old_C);
12507
12508             Set_Etype
12509               (New_C,
12510                Constrain_Component_Type
12511                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12512             Set_Is_Public (New_C, Is_Public (Subt));
12513
12514             Next_Component (Old_C);
12515          end loop;
12516       end if;
12517
12518       End_Scope;
12519    end Create_Constrained_Components;
12520
12521    ------------------------------------------
12522    -- Decimal_Fixed_Point_Type_Declaration --
12523    ------------------------------------------
12524
12525    procedure Decimal_Fixed_Point_Type_Declaration
12526      (T   : Entity_Id;
12527       Def : Node_Id)
12528    is
12529       Loc           : constant Source_Ptr := Sloc (Def);
12530       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
12531       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
12532       Implicit_Base : Entity_Id;
12533       Digs_Val      : Uint;
12534       Delta_Val     : Ureal;
12535       Scale_Val     : Uint;
12536       Bound_Val     : Ureal;
12537
12538    begin
12539       Check_SPARK_Restriction
12540         ("decimal fixed point type is not allowed", Def);
12541       Check_Restriction (No_Fixed_Point, Def);
12542
12543       --  Create implicit base type
12544
12545       Implicit_Base :=
12546         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
12547       Set_Etype (Implicit_Base, Implicit_Base);
12548
12549       --  Analyze and process delta expression
12550
12551       Analyze_And_Resolve (Delta_Expr, Universal_Real);
12552
12553       Check_Delta_Expression (Delta_Expr);
12554       Delta_Val := Expr_Value_R (Delta_Expr);
12555
12556       --  Check delta is power of 10, and determine scale value from it
12557
12558       declare
12559          Val : Ureal;
12560
12561       begin
12562          Scale_Val := Uint_0;
12563          Val := Delta_Val;
12564
12565          if Val < Ureal_1 then
12566             while Val < Ureal_1 loop
12567                Val := Val * Ureal_10;
12568                Scale_Val := Scale_Val + 1;
12569             end loop;
12570
12571             if Scale_Val > 18 then
12572                Error_Msg_N ("scale exceeds maximum value of 18", Def);
12573                Scale_Val := UI_From_Int (+18);
12574             end if;
12575
12576          else
12577             while Val > Ureal_1 loop
12578                Val := Val / Ureal_10;
12579                Scale_Val := Scale_Val - 1;
12580             end loop;
12581
12582             if Scale_Val < -18 then
12583                Error_Msg_N ("scale is less than minimum value of -18", Def);
12584                Scale_Val := UI_From_Int (-18);
12585             end if;
12586          end if;
12587
12588          if Val /= Ureal_1 then
12589             Error_Msg_N ("delta expression must be a power of 10", Def);
12590             Delta_Val := Ureal_10 ** (-Scale_Val);
12591          end if;
12592       end;
12593
12594       --  Set delta, scale and small (small = delta for decimal type)
12595
12596       Set_Delta_Value (Implicit_Base, Delta_Val);
12597       Set_Scale_Value (Implicit_Base, Scale_Val);
12598       Set_Small_Value (Implicit_Base, Delta_Val);
12599
12600       --  Analyze and process digits expression
12601
12602       Analyze_And_Resolve (Digs_Expr, Any_Integer);
12603       Check_Digits_Expression (Digs_Expr);
12604       Digs_Val := Expr_Value (Digs_Expr);
12605
12606       if Digs_Val > 18 then
12607          Digs_Val := UI_From_Int (+18);
12608          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
12609       end if;
12610
12611       Set_Digits_Value (Implicit_Base, Digs_Val);
12612       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
12613
12614       --  Set range of base type from digits value for now. This will be
12615       --  expanded to represent the true underlying base range by Freeze.
12616
12617       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
12618
12619       --  Note: We leave size as zero for now, size will be set at freeze
12620       --  time. We have to do this for ordinary fixed-point, because the size
12621       --  depends on the specified small, and we might as well do the same for
12622       --  decimal fixed-point.
12623
12624       pragma Assert (Esize (Implicit_Base) = Uint_0);
12625
12626       --  If there are bounds given in the declaration use them as the
12627       --  bounds of the first named subtype.
12628
12629       if Present (Real_Range_Specification (Def)) then
12630          declare
12631             RRS      : constant Node_Id := Real_Range_Specification (Def);
12632             Low      : constant Node_Id := Low_Bound (RRS);
12633             High     : constant Node_Id := High_Bound (RRS);
12634             Low_Val  : Ureal;
12635             High_Val : Ureal;
12636
12637          begin
12638             Analyze_And_Resolve (Low, Any_Real);
12639             Analyze_And_Resolve (High, Any_Real);
12640             Check_Real_Bound (Low);
12641             Check_Real_Bound (High);
12642             Low_Val := Expr_Value_R (Low);
12643             High_Val := Expr_Value_R (High);
12644
12645             if Low_Val < (-Bound_Val) then
12646                Error_Msg_N
12647                  ("range low bound too small for digits value", Low);
12648                Low_Val := -Bound_Val;
12649             end if;
12650
12651             if High_Val > Bound_Val then
12652                Error_Msg_N
12653                  ("range high bound too large for digits value", High);
12654                High_Val := Bound_Val;
12655             end if;
12656
12657             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
12658          end;
12659
12660       --  If no explicit range, use range that corresponds to given
12661       --  digits value. This will end up as the final range for the
12662       --  first subtype.
12663
12664       else
12665          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
12666       end if;
12667
12668       --  Complete entity for first subtype
12669
12670       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
12671       Set_Etype          (T, Implicit_Base);
12672       Set_Size_Info      (T, Implicit_Base);
12673       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
12674       Set_Digits_Value   (T, Digs_Val);
12675       Set_Delta_Value    (T, Delta_Val);
12676       Set_Small_Value    (T, Delta_Val);
12677       Set_Scale_Value    (T, Scale_Val);
12678       Set_Is_Constrained (T);
12679    end Decimal_Fixed_Point_Type_Declaration;
12680
12681    -----------------------------------
12682    -- Derive_Progenitor_Subprograms --
12683    -----------------------------------
12684
12685    procedure Derive_Progenitor_Subprograms
12686      (Parent_Type : Entity_Id;
12687       Tagged_Type : Entity_Id)
12688    is
12689       E          : Entity_Id;
12690       Elmt       : Elmt_Id;
12691       Iface      : Entity_Id;
12692       Iface_Elmt : Elmt_Id;
12693       Iface_Subp : Entity_Id;
12694       New_Subp   : Entity_Id := Empty;
12695       Prim_Elmt  : Elmt_Id;
12696       Subp       : Entity_Id;
12697       Typ        : Entity_Id;
12698
12699    begin
12700       pragma Assert (Ada_Version >= Ada_2005
12701         and then Is_Record_Type (Tagged_Type)
12702         and then Is_Tagged_Type (Tagged_Type)
12703         and then Has_Interfaces (Tagged_Type));
12704
12705       --  Step 1: Transfer to the full-view primitives associated with the
12706       --  partial-view that cover interface primitives. Conceptually this
12707       --  work should be done later by Process_Full_View; done here to
12708       --  simplify its implementation at later stages. It can be safely
12709       --  done here because interfaces must be visible in the partial and
12710       --  private view (RM 7.3(7.3/2)).
12711
12712       --  Small optimization: This work is only required if the parent is
12713       --  abstract. If the tagged type is not abstract, it cannot have
12714       --  abstract primitives (the only entities in the list of primitives of
12715       --  non-abstract tagged types that can reference abstract primitives
12716       --  through its Alias attribute are the internal entities that have
12717       --  attribute Interface_Alias, and these entities are generated later
12718       --  by Add_Internal_Interface_Entities).
12719
12720       if In_Private_Part (Current_Scope)
12721         and then Is_Abstract_Type (Parent_Type)
12722       then
12723          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
12724          while Present (Elmt) loop
12725             Subp := Node (Elmt);
12726
12727             --  At this stage it is not possible to have entities in the list
12728             --  of primitives that have attribute Interface_Alias
12729
12730             pragma Assert (No (Interface_Alias (Subp)));
12731
12732             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
12733
12734             if Is_Interface (Typ) then
12735                E := Find_Primitive_Covering_Interface
12736                       (Tagged_Type => Tagged_Type,
12737                        Iface_Prim  => Subp);
12738
12739                if Present (E)
12740                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
12741                then
12742                   Replace_Elmt (Elmt, E);
12743                   Remove_Homonym (Subp);
12744                end if;
12745             end if;
12746
12747             Next_Elmt (Elmt);
12748          end loop;
12749       end if;
12750
12751       --  Step 2: Add primitives of progenitors that are not implemented by
12752       --  parents of Tagged_Type
12753
12754       if Present (Interfaces (Base_Type (Tagged_Type))) then
12755          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
12756          while Present (Iface_Elmt) loop
12757             Iface := Node (Iface_Elmt);
12758
12759             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
12760             while Present (Prim_Elmt) loop
12761                Iface_Subp := Node (Prim_Elmt);
12762
12763                --  Exclude derivation of predefined primitives except those
12764                --  that come from source. Required to catch declarations of
12765                --  equality operators of interfaces. For example:
12766
12767                --     type Iface is interface;
12768                --     function "=" (Left, Right : Iface) return Boolean;
12769
12770                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
12771                  or else Comes_From_Source (Iface_Subp)
12772                then
12773                   E := Find_Primitive_Covering_Interface
12774                          (Tagged_Type => Tagged_Type,
12775                           Iface_Prim  => Iface_Subp);
12776
12777                   --  If not found we derive a new primitive leaving its alias
12778                   --  attribute referencing the interface primitive
12779
12780                   if No (E) then
12781                      Derive_Subprogram
12782                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12783
12784                   --  Ada 2012 (AI05-0197): If the covering primitive's name
12785                   --  differs from the name of the interface primitive then it
12786                   --  is a private primitive inherited from a parent type. In
12787                   --  such case, given that Tagged_Type covers the interface,
12788                   --  the inherited private primitive becomes visible. For such
12789                   --  purpose we add a new entity that renames the inherited
12790                   --  private primitive.
12791
12792                   elsif Chars (E) /= Chars (Iface_Subp) then
12793                      pragma Assert (Has_Suffix (E, 'P'));
12794                      Derive_Subprogram
12795                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12796                      Set_Alias (New_Subp, E);
12797                      Set_Is_Abstract_Subprogram (New_Subp,
12798                        Is_Abstract_Subprogram (E));
12799
12800                   --  Propagate to the full view interface entities associated
12801                   --  with the partial view
12802
12803                   elsif In_Private_Part (Current_Scope)
12804                     and then Present (Alias (E))
12805                     and then Alias (E) = Iface_Subp
12806                     and then
12807                       List_Containing (Parent (E)) /=
12808                         Private_Declarations
12809                           (Specification
12810                             (Unit_Declaration_Node (Current_Scope)))
12811                   then
12812                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
12813                   end if;
12814                end if;
12815
12816                Next_Elmt (Prim_Elmt);
12817             end loop;
12818
12819             Next_Elmt (Iface_Elmt);
12820          end loop;
12821       end if;
12822    end Derive_Progenitor_Subprograms;
12823
12824    -----------------------
12825    -- Derive_Subprogram --
12826    -----------------------
12827
12828    procedure Derive_Subprogram
12829      (New_Subp     : in out Entity_Id;
12830       Parent_Subp  : Entity_Id;
12831       Derived_Type : Entity_Id;
12832       Parent_Type  : Entity_Id;
12833       Actual_Subp  : Entity_Id := Empty)
12834    is
12835       Formal : Entity_Id;
12836       --  Formal parameter of parent primitive operation
12837
12838       Formal_Of_Actual : Entity_Id;
12839       --  Formal parameter of actual operation, when the derivation is to
12840       --  create a renaming for a primitive operation of an actual in an
12841       --  instantiation.
12842
12843       New_Formal : Entity_Id;
12844       --  Formal of inherited operation
12845
12846       Visible_Subp : Entity_Id := Parent_Subp;
12847
12848       function Is_Private_Overriding return Boolean;
12849       --  If Subp is a private overriding of a visible operation, the inherited
12850       --  operation derives from the overridden op (even though its body is the
12851       --  overriding one) and the inherited operation is visible now. See
12852       --  sem_disp to see the full details of the handling of the overridden
12853       --  subprogram, which is removed from the list of primitive operations of
12854       --  the type. The overridden subprogram is saved locally in Visible_Subp,
12855       --  and used to diagnose abstract operations that need overriding in the
12856       --  derived type.
12857
12858       procedure Replace_Type (Id, New_Id : Entity_Id);
12859       --  When the type is an anonymous access type, create a new access type
12860       --  designating the derived type.
12861
12862       procedure Set_Derived_Name;
12863       --  This procedure sets the appropriate Chars name for New_Subp. This
12864       --  is normally just a copy of the parent name. An exception arises for
12865       --  type support subprograms, where the name is changed to reflect the
12866       --  name of the derived type, e.g. if type foo is derived from type bar,
12867       --  then a procedure barDA is derived with a name fooDA.
12868
12869       ---------------------------
12870       -- Is_Private_Overriding --
12871       ---------------------------
12872
12873       function Is_Private_Overriding return Boolean is
12874          Prev : Entity_Id;
12875
12876       begin
12877          --  If the parent is not a dispatching operation there is no
12878          --  need to investigate overridings
12879
12880          if not Is_Dispatching_Operation (Parent_Subp) then
12881             return False;
12882          end if;
12883
12884          --  The visible operation that is overridden is a homonym of the
12885          --  parent subprogram. We scan the homonym chain to find the one
12886          --  whose alias is the subprogram we are deriving.
12887
12888          Prev := Current_Entity (Parent_Subp);
12889          while Present (Prev) loop
12890             if Ekind (Prev) = Ekind (Parent_Subp)
12891               and then Alias (Prev) = Parent_Subp
12892               and then Scope (Parent_Subp) = Scope (Prev)
12893               and then not Is_Hidden (Prev)
12894             then
12895                Visible_Subp := Prev;
12896                return True;
12897             end if;
12898
12899             Prev := Homonym (Prev);
12900          end loop;
12901
12902          return False;
12903       end Is_Private_Overriding;
12904
12905       ------------------
12906       -- Replace_Type --
12907       ------------------
12908
12909       procedure Replace_Type (Id, New_Id : Entity_Id) is
12910          Acc_Type : Entity_Id;
12911          Par      : constant Node_Id := Parent (Derived_Type);
12912
12913       begin
12914          --  When the type is an anonymous access type, create a new access
12915          --  type designating the derived type. This itype must be elaborated
12916          --  at the point of the derivation, not on subsequent calls that may
12917          --  be out of the proper scope for Gigi, so we insert a reference to
12918          --  it after the derivation.
12919
12920          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
12921             declare
12922                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
12923
12924             begin
12925                if Ekind (Desig_Typ) = E_Record_Type_With_Private
12926                  and then Present (Full_View (Desig_Typ))
12927                  and then not Is_Private_Type (Parent_Type)
12928                then
12929                   Desig_Typ := Full_View (Desig_Typ);
12930                end if;
12931
12932                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
12933
12934                   --  Ada 2005 (AI-251): Handle also derivations of abstract
12935                   --  interface primitives.
12936
12937                  or else (Is_Interface (Desig_Typ)
12938                           and then not Is_Class_Wide_Type (Desig_Typ))
12939                then
12940                   Acc_Type := New_Copy (Etype (Id));
12941                   Set_Etype (Acc_Type, Acc_Type);
12942                   Set_Scope (Acc_Type, New_Subp);
12943
12944                   --  Compute size of anonymous access type
12945
12946                   if Is_Array_Type (Desig_Typ)
12947                     and then not Is_Constrained (Desig_Typ)
12948                   then
12949                      Init_Size (Acc_Type, 2 * System_Address_Size);
12950                   else
12951                      Init_Size (Acc_Type, System_Address_Size);
12952                   end if;
12953
12954                   Init_Alignment (Acc_Type);
12955                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
12956
12957                   Set_Etype (New_Id, Acc_Type);
12958                   Set_Scope (New_Id, New_Subp);
12959
12960                   --  Create a reference to it
12961                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
12962
12963                else
12964                   Set_Etype (New_Id, Etype (Id));
12965                end if;
12966             end;
12967
12968          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
12969            or else
12970              (Ekind (Etype (Id)) = E_Record_Type_With_Private
12971                and then Present (Full_View (Etype (Id)))
12972                and then
12973                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
12974          then
12975             --  Constraint checks on formals are generated during expansion,
12976             --  based on the signature of the original subprogram. The bounds
12977             --  of the derived type are not relevant, and thus we can use
12978             --  the base type for the formals. However, the return type may be
12979             --  used in a context that requires that the proper static bounds
12980             --  be used (a case statement, for example)  and for those cases
12981             --  we must use the derived type (first subtype), not its base.
12982
12983             --  If the derived_type_definition has no constraints, we know that
12984             --  the derived type has the same constraints as the first subtype
12985             --  of the parent, and we can also use it rather than its base,
12986             --  which can lead to more efficient code.
12987
12988             if Etype (Id) = Parent_Type then
12989                if Is_Scalar_Type (Parent_Type)
12990                  and then
12991                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
12992                then
12993                   Set_Etype (New_Id, Derived_Type);
12994
12995                elsif Nkind (Par) = N_Full_Type_Declaration
12996                  and then
12997                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
12998                  and then
12999                    Is_Entity_Name
13000                      (Subtype_Indication (Type_Definition (Par)))
13001                then
13002                   Set_Etype (New_Id, Derived_Type);
13003
13004                else
13005                   Set_Etype (New_Id, Base_Type (Derived_Type));
13006                end if;
13007
13008             else
13009                Set_Etype (New_Id, Base_Type (Derived_Type));
13010             end if;
13011
13012          else
13013             Set_Etype (New_Id, Etype (Id));
13014          end if;
13015       end Replace_Type;
13016
13017       ----------------------
13018       -- Set_Derived_Name --
13019       ----------------------
13020
13021       procedure Set_Derived_Name is
13022          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
13023       begin
13024          if Nm = TSS_Null then
13025             Set_Chars (New_Subp, Chars (Parent_Subp));
13026          else
13027             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
13028          end if;
13029       end Set_Derived_Name;
13030
13031    --  Start of processing for Derive_Subprogram
13032
13033    begin
13034       New_Subp :=
13035          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
13036       Set_Ekind (New_Subp, Ekind (Parent_Subp));
13037       Set_Contract (New_Subp, Make_Contract (Sloc (New_Subp)));
13038
13039       --  Check whether the inherited subprogram is a private operation that
13040       --  should be inherited but not yet made visible. Such subprograms can
13041       --  become visible at a later point (e.g., the private part of a public
13042       --  child unit) via Declare_Inherited_Private_Subprograms. If the
13043       --  following predicate is true, then this is not such a private
13044       --  operation and the subprogram simply inherits the name of the parent
13045       --  subprogram. Note the special check for the names of controlled
13046       --  operations, which are currently exempted from being inherited with
13047       --  a hidden name because they must be findable for generation of
13048       --  implicit run-time calls.
13049
13050       if not Is_Hidden (Parent_Subp)
13051         or else Is_Internal (Parent_Subp)
13052         or else Is_Private_Overriding
13053         or else Is_Internal_Name (Chars (Parent_Subp))
13054         or else Chars (Parent_Subp) = Name_Initialize
13055         or else Chars (Parent_Subp) = Name_Adjust
13056         or else Chars (Parent_Subp) = Name_Finalize
13057       then
13058          Set_Derived_Name;
13059
13060       --  An inherited dispatching equality will be overridden by an internally
13061       --  generated one, or by an explicit one, so preserve its name and thus
13062       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
13063       --  private operation it may become invisible if the full view has
13064       --  progenitors, and the dispatch table will be malformed.
13065       --  We check that the type is limited to handle the anomalous declaration
13066       --  of Limited_Controlled, which is derived from a non-limited type, and
13067       --  which is handled specially elsewhere as well.
13068
13069       elsif Chars (Parent_Subp) = Name_Op_Eq
13070         and then Is_Dispatching_Operation (Parent_Subp)
13071         and then Etype (Parent_Subp) = Standard_Boolean
13072         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
13073         and then
13074           Etype (First_Formal (Parent_Subp)) =
13075             Etype (Next_Formal (First_Formal (Parent_Subp)))
13076       then
13077          Set_Derived_Name;
13078
13079       --  If parent is hidden, this can be a regular derivation if the
13080       --  parent is immediately visible in a non-instantiating context,
13081       --  or if we are in the private part of an instance. This test
13082       --  should still be refined ???
13083
13084       --  The test for In_Instance_Not_Visible avoids inheriting the derived
13085       --  operation as a non-visible operation in cases where the parent
13086       --  subprogram might not be visible now, but was visible within the
13087       --  original generic, so it would be wrong to make the inherited
13088       --  subprogram non-visible now. (Not clear if this test is fully
13089       --  correct; are there any cases where we should declare the inherited
13090       --  operation as not visible to avoid it being overridden, e.g., when
13091       --  the parent type is a generic actual with private primitives ???)
13092
13093       --  (they should be treated the same as other private inherited
13094       --  subprograms, but it's not clear how to do this cleanly). ???
13095
13096       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
13097               and then Is_Immediately_Visible (Parent_Subp)
13098               and then not In_Instance)
13099         or else In_Instance_Not_Visible
13100       then
13101          Set_Derived_Name;
13102
13103       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
13104       --  overrides an interface primitive because interface primitives
13105       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
13106
13107       elsif Ada_Version >= Ada_2005
13108          and then Is_Dispatching_Operation (Parent_Subp)
13109          and then Covers_Some_Interface (Parent_Subp)
13110       then
13111          Set_Derived_Name;
13112
13113       --  Otherwise, the type is inheriting a private operation, so enter
13114       --  it with a special name so it can't be overridden.
13115
13116       else
13117          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
13118       end if;
13119
13120       Set_Parent (New_Subp, Parent (Derived_Type));
13121
13122       if Present (Actual_Subp) then
13123          Replace_Type (Actual_Subp, New_Subp);
13124       else
13125          Replace_Type (Parent_Subp, New_Subp);
13126       end if;
13127
13128       Conditional_Delay (New_Subp, Parent_Subp);
13129
13130       --  If we are creating a renaming for a primitive operation of an
13131       --  actual of a generic derived type, we must examine the signature
13132       --  of the actual primitive, not that of the generic formal, which for
13133       --  example may be an interface. However the name and initial value
13134       --  of the inherited operation are those of the formal primitive.
13135
13136       Formal := First_Formal (Parent_Subp);
13137
13138       if Present (Actual_Subp) then
13139          Formal_Of_Actual := First_Formal (Actual_Subp);
13140       else
13141          Formal_Of_Actual := Empty;
13142       end if;
13143
13144       while Present (Formal) loop
13145          New_Formal := New_Copy (Formal);
13146
13147          --  Normally we do not go copying parents, but in the case of
13148          --  formals, we need to link up to the declaration (which is the
13149          --  parameter specification), and it is fine to link up to the
13150          --  original formal's parameter specification in this case.
13151
13152          Set_Parent (New_Formal, Parent (Formal));
13153          Append_Entity (New_Formal, New_Subp);
13154
13155          if Present (Formal_Of_Actual) then
13156             Replace_Type (Formal_Of_Actual, New_Formal);
13157             Next_Formal (Formal_Of_Actual);
13158          else
13159             Replace_Type (Formal, New_Formal);
13160          end if;
13161
13162          Next_Formal (Formal);
13163       end loop;
13164
13165       --  If this derivation corresponds to a tagged generic actual, then
13166       --  primitive operations rename those of the actual. Otherwise the
13167       --  primitive operations rename those of the parent type, If the parent
13168       --  renames an intrinsic operator, so does the new subprogram. We except
13169       --  concatenation, which is always properly typed, and does not get
13170       --  expanded as other intrinsic operations.
13171
13172       if No (Actual_Subp) then
13173          if Is_Intrinsic_Subprogram (Parent_Subp) then
13174             Set_Is_Intrinsic_Subprogram (New_Subp);
13175
13176             if Present (Alias (Parent_Subp))
13177               and then Chars (Parent_Subp) /= Name_Op_Concat
13178             then
13179                Set_Alias (New_Subp, Alias (Parent_Subp));
13180             else
13181                Set_Alias (New_Subp, Parent_Subp);
13182             end if;
13183
13184          else
13185             Set_Alias (New_Subp, Parent_Subp);
13186          end if;
13187
13188       else
13189          Set_Alias (New_Subp, Actual_Subp);
13190       end if;
13191
13192       --  Derived subprograms of a tagged type must inherit the convention
13193       --  of the parent subprogram (a requirement of AI-117). Derived
13194       --  subprograms of untagged types simply get convention Ada by default.
13195
13196       if Is_Tagged_Type (Derived_Type) then
13197          Set_Convention (New_Subp, Convention (Parent_Subp));
13198       end if;
13199
13200       --  Predefined controlled operations retain their name even if the parent
13201       --  is hidden (see above), but they are not primitive operations if the
13202       --  ancestor is not visible, for example if the parent is a private
13203       --  extension completed with a controlled extension. Note that a full
13204       --  type that is controlled can break privacy: the flag Is_Controlled is
13205       --  set on both views of the type.
13206
13207       if Is_Controlled (Parent_Type)
13208         and then
13209           (Chars (Parent_Subp) = Name_Initialize
13210             or else Chars (Parent_Subp) = Name_Adjust
13211             or else Chars (Parent_Subp) = Name_Finalize)
13212         and then Is_Hidden (Parent_Subp)
13213         and then not Is_Visibly_Controlled (Parent_Type)
13214       then
13215          Set_Is_Hidden (New_Subp);
13216       end if;
13217
13218       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
13219       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
13220
13221       if Ekind (Parent_Subp) = E_Procedure then
13222          Set_Is_Valued_Procedure
13223            (New_Subp, Is_Valued_Procedure (Parent_Subp));
13224       else
13225          Set_Has_Controlling_Result
13226            (New_Subp, Has_Controlling_Result (Parent_Subp));
13227       end if;
13228
13229       --  No_Return must be inherited properly. If this is overridden in the
13230       --  case of a dispatching operation, then a check is made in Sem_Disp
13231       --  that the overriding operation is also No_Return (no such check is
13232       --  required for the case of non-dispatching operation.
13233
13234       Set_No_Return (New_Subp, No_Return (Parent_Subp));
13235
13236       --  A derived function with a controlling result is abstract. If the
13237       --  Derived_Type is a nonabstract formal generic derived type, then
13238       --  inherited operations are not abstract: the required check is done at
13239       --  instantiation time. If the derivation is for a generic actual, the
13240       --  function is not abstract unless the actual is.
13241
13242       if Is_Generic_Type (Derived_Type)
13243         and then not Is_Abstract_Type (Derived_Type)
13244       then
13245          null;
13246
13247       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
13248       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
13249
13250       elsif Ada_Version >= Ada_2005
13251         and then (Is_Abstract_Subprogram (Alias (New_Subp))
13252                    or else (Is_Tagged_Type (Derived_Type)
13253                             and then Etype (New_Subp) = Derived_Type
13254                             and then not Is_Null_Extension (Derived_Type))
13255                    or else (Is_Tagged_Type (Derived_Type)
13256                             and then Ekind (Etype (New_Subp)) =
13257                                                        E_Anonymous_Access_Type
13258                             and then Designated_Type (Etype (New_Subp)) =
13259                                                        Derived_Type
13260                             and then not Is_Null_Extension (Derived_Type)))
13261         and then No (Actual_Subp)
13262       then
13263          if not Is_Tagged_Type (Derived_Type)
13264            or else Is_Abstract_Type (Derived_Type)
13265            or else Is_Abstract_Subprogram (Alias (New_Subp))
13266          then
13267             Set_Is_Abstract_Subprogram (New_Subp);
13268          else
13269             Set_Requires_Overriding (New_Subp);
13270          end if;
13271
13272       elsif Ada_Version < Ada_2005
13273         and then (Is_Abstract_Subprogram (Alias (New_Subp))
13274                    or else (Is_Tagged_Type (Derived_Type)
13275                              and then Etype (New_Subp) = Derived_Type
13276                              and then No (Actual_Subp)))
13277       then
13278          Set_Is_Abstract_Subprogram (New_Subp);
13279
13280       --  AI05-0097 : an inherited operation that dispatches on result is
13281       --  abstract if the derived type is abstract, even if the parent type
13282       --  is concrete and the derived type is a null extension.
13283
13284       elsif Has_Controlling_Result (Alias (New_Subp))
13285         and then Is_Abstract_Type (Etype (New_Subp))
13286       then
13287          Set_Is_Abstract_Subprogram (New_Subp);
13288
13289       --  Finally, if the parent type is abstract we must verify that all
13290       --  inherited operations are either non-abstract or overridden, or that
13291       --  the derived type itself is abstract (this check is performed at the
13292       --  end of a package declaration, in Check_Abstract_Overriding). A
13293       --  private overriding in the parent type will not be visible in the
13294       --  derivation if we are not in an inner package or in a child unit of
13295       --  the parent type, in which case the abstractness of the inherited
13296       --  operation is carried to the new subprogram.
13297
13298       elsif Is_Abstract_Type (Parent_Type)
13299         and then not In_Open_Scopes (Scope (Parent_Type))
13300         and then Is_Private_Overriding
13301         and then Is_Abstract_Subprogram (Visible_Subp)
13302       then
13303          if No (Actual_Subp) then
13304             Set_Alias (New_Subp, Visible_Subp);
13305             Set_Is_Abstract_Subprogram (New_Subp, True);
13306
13307          else
13308             --  If this is a derivation for an instance of a formal derived
13309             --  type, abstractness comes from the primitive operation of the
13310             --  actual, not from the operation inherited from the ancestor.
13311
13312             Set_Is_Abstract_Subprogram
13313               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
13314          end if;
13315       end if;
13316
13317       New_Overloaded_Entity (New_Subp, Derived_Type);
13318
13319       --  Check for case of a derived subprogram for the instantiation of a
13320       --  formal derived tagged type, if so mark the subprogram as dispatching
13321       --  and inherit the dispatching attributes of the actual subprogram. The
13322       --  derived subprogram is effectively renaming of the actual subprogram,
13323       --  so it needs to have the same attributes as the actual.
13324
13325       if Present (Actual_Subp)
13326         and then Is_Dispatching_Operation (Actual_Subp)
13327       then
13328          Set_Is_Dispatching_Operation (New_Subp);
13329
13330          if Present (DTC_Entity (Actual_Subp)) then
13331             Set_DTC_Entity (New_Subp, DTC_Entity (Actual_Subp));
13332             Set_DT_Position (New_Subp, DT_Position (Actual_Subp));
13333          end if;
13334       end if;
13335
13336       --  Indicate that a derived subprogram does not require a body and that
13337       --  it does not require processing of default expressions.
13338
13339       Set_Has_Completion (New_Subp);
13340       Set_Default_Expressions_Processed (New_Subp);
13341
13342       if Ekind (New_Subp) = E_Function then
13343          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
13344       end if;
13345    end Derive_Subprogram;
13346
13347    ------------------------
13348    -- Derive_Subprograms --
13349    ------------------------
13350
13351    procedure Derive_Subprograms
13352      (Parent_Type    : Entity_Id;
13353       Derived_Type   : Entity_Id;
13354       Generic_Actual : Entity_Id := Empty)
13355    is
13356       Op_List : constant Elist_Id :=
13357                   Collect_Primitive_Operations (Parent_Type);
13358
13359       function Check_Derived_Type return Boolean;
13360       --  Check that all the entities derived from Parent_Type are found in
13361       --  the list of primitives of Derived_Type exactly in the same order.
13362
13363       procedure Derive_Interface_Subprogram
13364         (New_Subp    : in out Entity_Id;
13365          Subp        : Entity_Id;
13366          Actual_Subp : Entity_Id);
13367       --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
13368       --  (which is an interface primitive). If Generic_Actual is present then
13369       --  Actual_Subp is the actual subprogram corresponding with the generic
13370       --  subprogram Subp.
13371
13372       function Check_Derived_Type return Boolean is
13373          E        : Entity_Id;
13374          Elmt     : Elmt_Id;
13375          List     : Elist_Id;
13376          New_Subp : Entity_Id;
13377          Op_Elmt  : Elmt_Id;
13378          Subp     : Entity_Id;
13379
13380       begin
13381          --  Traverse list of entities in the current scope searching for
13382          --  an incomplete type whose full-view is derived type
13383
13384          E := First_Entity (Scope (Derived_Type));
13385          while Present (E)
13386            and then E /= Derived_Type
13387          loop
13388             if Ekind (E) = E_Incomplete_Type
13389               and then Present (Full_View (E))
13390               and then Full_View (E) = Derived_Type
13391             then
13392                --  Disable this test if Derived_Type completes an incomplete
13393                --  type because in such case more primitives can be added
13394                --  later to the list of primitives of Derived_Type by routine
13395                --  Process_Incomplete_Dependents
13396
13397                return True;
13398             end if;
13399
13400             E := Next_Entity (E);
13401          end loop;
13402
13403          List := Collect_Primitive_Operations (Derived_Type);
13404          Elmt := First_Elmt (List);
13405
13406          Op_Elmt := First_Elmt (Op_List);
13407          while Present (Op_Elmt) loop
13408             Subp     := Node (Op_Elmt);
13409             New_Subp := Node (Elmt);
13410
13411             --  At this early stage Derived_Type has no entities with attribute
13412             --  Interface_Alias. In addition, such primitives are always
13413             --  located at the end of the list of primitives of Parent_Type.
13414             --  Therefore, if found we can safely stop processing pending
13415             --  entities.
13416
13417             exit when Present (Interface_Alias (Subp));
13418
13419             --  Handle hidden entities
13420
13421             if not Is_Predefined_Dispatching_Operation (Subp)
13422               and then Is_Hidden (Subp)
13423             then
13424                if Present (New_Subp)
13425                  and then Primitive_Names_Match (Subp, New_Subp)
13426                then
13427                   Next_Elmt (Elmt);
13428                end if;
13429
13430             else
13431                if not Present (New_Subp)
13432                  or else Ekind (Subp) /= Ekind (New_Subp)
13433                  or else not Primitive_Names_Match (Subp, New_Subp)
13434                then
13435                   return False;
13436                end if;
13437
13438                Next_Elmt (Elmt);
13439             end if;
13440
13441             Next_Elmt (Op_Elmt);
13442          end loop;
13443
13444          return True;
13445       end Check_Derived_Type;
13446
13447       ---------------------------------
13448       -- Derive_Interface_Subprogram --
13449       ---------------------------------
13450
13451       procedure Derive_Interface_Subprogram
13452         (New_Subp    : in out Entity_Id;
13453          Subp        : Entity_Id;
13454          Actual_Subp : Entity_Id)
13455       is
13456          Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
13457          Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
13458
13459       begin
13460          pragma Assert (Is_Interface (Iface_Type));
13461
13462          Derive_Subprogram
13463            (New_Subp     => New_Subp,
13464             Parent_Subp  => Iface_Subp,
13465             Derived_Type => Derived_Type,
13466             Parent_Type  => Iface_Type,
13467             Actual_Subp  => Actual_Subp);
13468
13469          --  Given that this new interface entity corresponds with a primitive
13470          --  of the parent that was not overridden we must leave it associated
13471          --  with its parent primitive to ensure that it will share the same
13472          --  dispatch table slot when overridden.
13473
13474          if No (Actual_Subp) then
13475             Set_Alias (New_Subp, Subp);
13476
13477          --  For instantiations this is not needed since the previous call to
13478          --  Derive_Subprogram leaves the entity well decorated.
13479
13480          else
13481             pragma Assert (Alias (New_Subp) = Actual_Subp);
13482             null;
13483          end if;
13484       end Derive_Interface_Subprogram;
13485
13486       --  Local variables
13487
13488       Alias_Subp   : Entity_Id;
13489       Act_List     : Elist_Id;
13490       Act_Elmt     : Elmt_Id   := No_Elmt;
13491       Act_Subp     : Entity_Id := Empty;
13492       Elmt         : Elmt_Id;
13493       Need_Search  : Boolean   := False;
13494       New_Subp     : Entity_Id := Empty;
13495       Parent_Base  : Entity_Id;
13496       Subp         : Entity_Id;
13497
13498    --  Start of processing for Derive_Subprograms
13499
13500    begin
13501       if Ekind (Parent_Type) = E_Record_Type_With_Private
13502         and then Has_Discriminants (Parent_Type)
13503         and then Present (Full_View (Parent_Type))
13504       then
13505          Parent_Base := Full_View (Parent_Type);
13506       else
13507          Parent_Base := Parent_Type;
13508       end if;
13509
13510       if Present (Generic_Actual) then
13511          Act_List := Collect_Primitive_Operations (Generic_Actual);
13512          Act_Elmt := First_Elmt (Act_List);
13513       end if;
13514
13515       --  Derive primitives inherited from the parent. Note that if the generic
13516       --  actual is present, this is not really a type derivation, it is a
13517       --  completion within an instance.
13518
13519       --  Case 1: Derived_Type does not implement interfaces
13520
13521       if not Is_Tagged_Type (Derived_Type)
13522         or else (not Has_Interfaces (Derived_Type)
13523                   and then not (Present (Generic_Actual)
13524                                   and then
13525                                 Has_Interfaces (Generic_Actual)))
13526       then
13527          Elmt := First_Elmt (Op_List);
13528          while Present (Elmt) loop
13529             Subp := Node (Elmt);
13530
13531             --  Literals are derived earlier in the process of building the
13532             --  derived type, and are skipped here.
13533
13534             if Ekind (Subp) = E_Enumeration_Literal then
13535                null;
13536
13537             --  The actual is a direct descendant and the common primitive
13538             --  operations appear in the same order.
13539
13540             --  If the generic parent type is present, the derived type is an
13541             --  instance of a formal derived type, and within the instance its
13542             --  operations are those of the actual. We derive from the formal
13543             --  type but make the inherited operations aliases of the
13544             --  corresponding operations of the actual.
13545
13546             else
13547                pragma Assert (No (Node (Act_Elmt))
13548                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
13549                             and then
13550                           Type_Conformant (Subp, Node (Act_Elmt),
13551                                            Skip_Controlling_Formals => True)));
13552
13553                Derive_Subprogram
13554                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
13555
13556                if Present (Act_Elmt) then
13557                   Next_Elmt (Act_Elmt);
13558                end if;
13559             end if;
13560
13561             Next_Elmt (Elmt);
13562          end loop;
13563
13564       --  Case 2: Derived_Type implements interfaces
13565
13566       else
13567          --  If the parent type has no predefined primitives we remove
13568          --  predefined primitives from the list of primitives of generic
13569          --  actual to simplify the complexity of this algorithm.
13570
13571          if Present (Generic_Actual) then
13572             declare
13573                Has_Predefined_Primitives : Boolean := False;
13574
13575             begin
13576                --  Check if the parent type has predefined primitives
13577
13578                Elmt := First_Elmt (Op_List);
13579                while Present (Elmt) loop
13580                   Subp := Node (Elmt);
13581
13582                   if Is_Predefined_Dispatching_Operation (Subp)
13583                     and then not Comes_From_Source (Ultimate_Alias (Subp))
13584                   then
13585                      Has_Predefined_Primitives := True;
13586                      exit;
13587                   end if;
13588
13589                   Next_Elmt (Elmt);
13590                end loop;
13591
13592                --  Remove predefined primitives of Generic_Actual. We must use
13593                --  an auxiliary list because in case of tagged types the value
13594                --  returned by Collect_Primitive_Operations is the value stored
13595                --  in its Primitive_Operations attribute (and we don't want to
13596                --  modify its current contents).
13597
13598                if not Has_Predefined_Primitives then
13599                   declare
13600                      Aux_List : constant Elist_Id := New_Elmt_List;
13601
13602                   begin
13603                      Elmt := First_Elmt (Act_List);
13604                      while Present (Elmt) loop
13605                         Subp := Node (Elmt);
13606
13607                         if not Is_Predefined_Dispatching_Operation (Subp)
13608                           or else Comes_From_Source (Subp)
13609                         then
13610                            Append_Elmt (Subp, Aux_List);
13611                         end if;
13612
13613                         Next_Elmt (Elmt);
13614                      end loop;
13615
13616                      Act_List := Aux_List;
13617                   end;
13618                end if;
13619
13620                Act_Elmt := First_Elmt (Act_List);
13621                Act_Subp := Node (Act_Elmt);
13622             end;
13623          end if;
13624
13625          --  Stage 1: If the generic actual is not present we derive the
13626          --  primitives inherited from the parent type. If the generic parent
13627          --  type is present, the derived type is an instance of a formal
13628          --  derived type, and within the instance its operations are those of
13629          --  the actual. We derive from the formal type but make the inherited
13630          --  operations aliases of the corresponding operations of the actual.
13631
13632          Elmt := First_Elmt (Op_List);
13633          while Present (Elmt) loop
13634             Subp       := Node (Elmt);
13635             Alias_Subp := Ultimate_Alias (Subp);
13636
13637             --  Do not derive internal entities of the parent that link
13638             --  interface primitives with their covering primitive. These
13639             --  entities will be added to this type when frozen.
13640
13641             if Present (Interface_Alias (Subp)) then
13642                goto Continue;
13643             end if;
13644
13645             --  If the generic actual is present find the corresponding
13646             --  operation in the generic actual. If the parent type is a
13647             --  direct ancestor of the derived type then, even if it is an
13648             --  interface, the operations are inherited from the primary
13649             --  dispatch table and are in the proper order. If we detect here
13650             --  that primitives are not in the same order we traverse the list
13651             --  of primitive operations of the actual to find the one that
13652             --  implements the interface primitive.
13653
13654             if Need_Search
13655               or else
13656                 (Present (Generic_Actual)
13657                   and then Present (Act_Subp)
13658                   and then not
13659                     (Primitive_Names_Match (Subp, Act_Subp)
13660                        and then
13661                      Type_Conformant (Subp, Act_Subp,
13662                                       Skip_Controlling_Formals => True)))
13663             then
13664                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
13665                                                Use_Full_View => True));
13666
13667                --  Remember that we need searching for all pending primitives
13668
13669                Need_Search := True;
13670
13671                --  Handle entities associated with interface primitives
13672
13673                if Present (Alias_Subp)
13674                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13675                  and then not Is_Predefined_Dispatching_Operation (Subp)
13676                then
13677                   --  Search for the primitive in the homonym chain
13678
13679                   Act_Subp :=
13680                     Find_Primitive_Covering_Interface
13681                       (Tagged_Type => Generic_Actual,
13682                        Iface_Prim  => Alias_Subp);
13683
13684                   --  Previous search may not locate primitives covering
13685                   --  interfaces defined in generics units or instantiations.
13686                   --  (it fails if the covering primitive has formals whose
13687                   --  type is also defined in generics or instantiations).
13688                   --  In such case we search in the list of primitives of the
13689                   --  generic actual for the internal entity that links the
13690                   --  interface primitive and the covering primitive.
13691
13692                   if No (Act_Subp)
13693                     and then Is_Generic_Type (Parent_Type)
13694                   then
13695                      --  This code has been designed to handle only generic
13696                      --  formals that implement interfaces that are defined
13697                      --  in a generic unit or instantiation. If this code is
13698                      --  needed for other cases we must review it because
13699                      --  (given that it relies on Original_Location to locate
13700                      --  the primitive of Generic_Actual that covers the
13701                      --  interface) it could leave linked through attribute
13702                      --  Alias entities of unrelated instantiations).
13703
13704                      pragma Assert
13705                        (Is_Generic_Unit
13706                           (Scope (Find_Dispatching_Type (Alias_Subp)))
13707                        or else
13708                         Instantiation_Depth
13709                           (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
13710
13711                      declare
13712                         Iface_Prim_Loc : constant Source_Ptr :=
13713                                          Original_Location (Sloc (Alias_Subp));
13714                         Elmt      : Elmt_Id;
13715                         Prim      : Entity_Id;
13716                      begin
13717                         Elmt :=
13718                           First_Elmt (Primitive_Operations (Generic_Actual));
13719
13720                         Search : while Present (Elmt) loop
13721                            Prim := Node (Elmt);
13722
13723                            if Present (Interface_Alias (Prim))
13724                              and then Original_Location
13725                                         (Sloc (Interface_Alias (Prim)))
13726                                        = Iface_Prim_Loc
13727                            then
13728                               Act_Subp := Alias (Prim);
13729                               exit Search;
13730                            end if;
13731
13732                            Next_Elmt (Elmt);
13733                         end loop Search;
13734                      end;
13735                   end if;
13736
13737                   pragma Assert (Present (Act_Subp)
13738                     or else Is_Abstract_Type (Generic_Actual)
13739                     or else Serious_Errors_Detected > 0);
13740
13741                --  Handle predefined primitives plus the rest of user-defined
13742                --  primitives
13743
13744                else
13745                   Act_Elmt := First_Elmt (Act_List);
13746                   while Present (Act_Elmt) loop
13747                      Act_Subp := Node (Act_Elmt);
13748
13749                      exit when Primitive_Names_Match (Subp, Act_Subp)
13750                        and then Type_Conformant
13751                                   (Subp, Act_Subp,
13752                                    Skip_Controlling_Formals => True)
13753                        and then No (Interface_Alias (Act_Subp));
13754
13755                      Next_Elmt (Act_Elmt);
13756                   end loop;
13757
13758                   if No (Act_Elmt) then
13759                      Act_Subp := Empty;
13760                   end if;
13761                end if;
13762             end if;
13763
13764             --   Case 1: If the parent is a limited interface then it has the
13765             --   predefined primitives of synchronized interfaces. However, the
13766             --   actual type may be a non-limited type and hence it does not
13767             --   have such primitives.
13768
13769             if Present (Generic_Actual)
13770               and then not Present (Act_Subp)
13771               and then Is_Limited_Interface (Parent_Base)
13772               and then Is_Predefined_Interface_Primitive (Subp)
13773             then
13774                null;
13775
13776             --  Case 2: Inherit entities associated with interfaces that were
13777             --  not covered by the parent type. We exclude here null interface
13778             --  primitives because they do not need special management.
13779
13780             --  We also exclude interface operations that are renamings. If the
13781             --  subprogram is an explicit renaming of an interface primitive,
13782             --  it is a regular primitive operation, and the presence of its
13783             --  alias is not relevant: it has to be derived like any other
13784             --  primitive.
13785
13786             elsif Present (Alias (Subp))
13787               and then Nkind (Unit_Declaration_Node (Subp)) /=
13788                                             N_Subprogram_Renaming_Declaration
13789               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13790               and then not
13791                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
13792                   and then Null_Present (Parent (Alias_Subp)))
13793             then
13794                --  If this is an abstract private type then we transfer the
13795                --  derivation of the interface primitive from the partial view
13796                --  to the full view. This is safe because all the interfaces
13797                --  must be visible in the partial view. Done to avoid adding
13798                --  a new interface derivation to the private part of the
13799                --  enclosing package; otherwise this new derivation would be
13800                --  decorated as hidden when the analysis of the enclosing
13801                --  package completes.
13802
13803                if Is_Abstract_Type (Derived_Type)
13804                  and then In_Private_Part (Current_Scope)
13805                  and then Has_Private_Declaration (Derived_Type)
13806                then
13807                   declare
13808                      Partial_View : Entity_Id;
13809                      Elmt         : Elmt_Id;
13810                      Ent          : Entity_Id;
13811
13812                   begin
13813                      Partial_View := First_Entity (Current_Scope);
13814                      loop
13815                         exit when No (Partial_View)
13816                           or else (Has_Private_Declaration (Partial_View)
13817                                      and then
13818                                    Full_View (Partial_View) = Derived_Type);
13819
13820                         Next_Entity (Partial_View);
13821                      end loop;
13822
13823                      --  If the partial view was not found then the source code
13824                      --  has errors and the derivation is not needed.
13825
13826                      if Present (Partial_View) then
13827                         Elmt :=
13828                           First_Elmt (Primitive_Operations (Partial_View));
13829                         while Present (Elmt) loop
13830                            Ent := Node (Elmt);
13831
13832                            if Present (Alias (Ent))
13833                              and then Ultimate_Alias (Ent) = Alias (Subp)
13834                            then
13835                               Append_Elmt
13836                                 (Ent, Primitive_Operations (Derived_Type));
13837                               exit;
13838                            end if;
13839
13840                            Next_Elmt (Elmt);
13841                         end loop;
13842
13843                         --  If the interface primitive was not found in the
13844                         --  partial view then this interface primitive was
13845                         --  overridden. We add a derivation to activate in
13846                         --  Derive_Progenitor_Subprograms the machinery to
13847                         --  search for it.
13848
13849                         if No (Elmt) then
13850                            Derive_Interface_Subprogram
13851                              (New_Subp    => New_Subp,
13852                               Subp        => Subp,
13853                               Actual_Subp => Act_Subp);
13854                         end if;
13855                      end if;
13856                   end;
13857                else
13858                   Derive_Interface_Subprogram
13859                     (New_Subp     => New_Subp,
13860                      Subp         => Subp,
13861                      Actual_Subp  => Act_Subp);
13862                end if;
13863
13864             --  Case 3: Common derivation
13865
13866             else
13867                Derive_Subprogram
13868                  (New_Subp     => New_Subp,
13869                   Parent_Subp  => Subp,
13870                   Derived_Type => Derived_Type,
13871                   Parent_Type  => Parent_Base,
13872                   Actual_Subp  => Act_Subp);
13873             end if;
13874
13875             --  No need to update Act_Elm if we must search for the
13876             --  corresponding operation in the generic actual
13877
13878             if not Need_Search
13879               and then Present (Act_Elmt)
13880             then
13881                Next_Elmt (Act_Elmt);
13882                Act_Subp := Node (Act_Elmt);
13883             end if;
13884
13885             <<Continue>>
13886             Next_Elmt (Elmt);
13887          end loop;
13888
13889          --  Inherit additional operations from progenitors. If the derived
13890          --  type is a generic actual, there are not new primitive operations
13891          --  for the type because it has those of the actual, and therefore
13892          --  nothing needs to be done. The renamings generated above are not
13893          --  primitive operations, and their purpose is simply to make the
13894          --  proper operations visible within an instantiation.
13895
13896          if No (Generic_Actual) then
13897             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
13898          end if;
13899       end if;
13900
13901       --  Final check: Direct descendants must have their primitives in the
13902       --  same order. We exclude from this test untagged types and instances
13903       --  of formal derived types. We skip this test if we have already
13904       --  reported serious errors in the sources.
13905
13906       pragma Assert (not Is_Tagged_Type (Derived_Type)
13907         or else Present (Generic_Actual)
13908         or else Serious_Errors_Detected > 0
13909         or else Check_Derived_Type);
13910    end Derive_Subprograms;
13911
13912    --------------------------------
13913    -- Derived_Standard_Character --
13914    --------------------------------
13915
13916    procedure Derived_Standard_Character
13917      (N            : Node_Id;
13918       Parent_Type  : Entity_Id;
13919       Derived_Type : Entity_Id)
13920    is
13921       Loc           : constant Source_Ptr := Sloc (N);
13922       Def           : constant Node_Id    := Type_Definition (N);
13923       Indic         : constant Node_Id    := Subtype_Indication (Def);
13924       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
13925       Implicit_Base : constant Entity_Id  :=
13926                         Create_Itype
13927                           (E_Enumeration_Type, N, Derived_Type, 'B');
13928
13929       Lo : Node_Id;
13930       Hi : Node_Id;
13931
13932    begin
13933       Discard_Node (Process_Subtype (Indic, N));
13934
13935       Set_Etype     (Implicit_Base, Parent_Base);
13936       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
13937       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
13938
13939       Set_Is_Character_Type  (Implicit_Base, True);
13940       Set_Has_Delayed_Freeze (Implicit_Base);
13941
13942       --  The bounds of the implicit base are the bounds of the parent base.
13943       --  Note that their type is the parent base.
13944
13945       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
13946       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
13947
13948       Set_Scalar_Range (Implicit_Base,
13949         Make_Range (Loc,
13950           Low_Bound  => Lo,
13951           High_Bound => Hi));
13952
13953       Conditional_Delay (Derived_Type, Parent_Type);
13954
13955       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
13956       Set_Etype (Derived_Type, Implicit_Base);
13957       Set_Size_Info         (Derived_Type, Parent_Type);
13958
13959       if Unknown_RM_Size (Derived_Type) then
13960          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
13961       end if;
13962
13963       Set_Is_Character_Type (Derived_Type, True);
13964
13965       if Nkind (Indic) /= N_Subtype_Indication then
13966
13967          --  If no explicit constraint, the bounds are those
13968          --  of the parent type.
13969
13970          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
13971          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
13972          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
13973       end if;
13974
13975       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
13976
13977       --  Because the implicit base is used in the conversion of the bounds, we
13978       --  have to freeze it now. This is similar to what is done for numeric
13979       --  types, and it equally suspicious, but otherwise a non-static bound
13980       --  will have a reference to an unfrozen type, which is rejected by Gigi
13981       --  (???). This requires specific care for definition of stream
13982       --  attributes. For details, see comments at the end of
13983       --  Build_Derived_Numeric_Type.
13984
13985       Freeze_Before (N, Implicit_Base);
13986    end Derived_Standard_Character;
13987
13988    ------------------------------
13989    -- Derived_Type_Declaration --
13990    ------------------------------
13991
13992    procedure Derived_Type_Declaration
13993      (T             : Entity_Id;
13994       N             : Node_Id;
13995       Is_Completion : Boolean)
13996    is
13997       Parent_Type  : Entity_Id;
13998
13999       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
14000       --  Check whether the parent type is a generic formal, or derives
14001       --  directly or indirectly from one.
14002
14003       ------------------------
14004       -- Comes_From_Generic --
14005       ------------------------
14006
14007       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
14008       begin
14009          if Is_Generic_Type (Typ) then
14010             return True;
14011
14012          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
14013             return True;
14014
14015          elsif Is_Private_Type (Typ)
14016            and then Present (Full_View (Typ))
14017            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
14018          then
14019             return True;
14020
14021          elsif Is_Generic_Actual_Type (Typ) then
14022             return True;
14023
14024          else
14025             return False;
14026          end if;
14027       end Comes_From_Generic;
14028
14029       --  Local variables
14030
14031       Def          : constant Node_Id := Type_Definition (N);
14032       Iface_Def    : Node_Id;
14033       Indic        : constant Node_Id := Subtype_Indication (Def);
14034       Extension    : constant Node_Id := Record_Extension_Part (Def);
14035       Parent_Node  : Node_Id;
14036       Taggd        : Boolean;
14037
14038    --  Start of processing for Derived_Type_Declaration
14039
14040    begin
14041       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
14042
14043       --  Ada 2005 (AI-251): In case of interface derivation check that the
14044       --  parent is also an interface.
14045
14046       if Interface_Present (Def) then
14047          Check_SPARK_Restriction ("interface is not allowed", Def);
14048
14049          if not Is_Interface (Parent_Type) then
14050             Diagnose_Interface (Indic, Parent_Type);
14051
14052          else
14053             Parent_Node := Parent (Base_Type (Parent_Type));
14054             Iface_Def   := Type_Definition (Parent_Node);
14055
14056             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
14057             --  other limited interfaces.
14058
14059             if Limited_Present (Def) then
14060                if Limited_Present (Iface_Def) then
14061                   null;
14062
14063                elsif Protected_Present (Iface_Def) then
14064                   Error_Msg_NE
14065                     ("descendant of& must be declared"
14066                        & " as a protected interface",
14067                          N, Parent_Type);
14068
14069                elsif Synchronized_Present (Iface_Def) then
14070                   Error_Msg_NE
14071                     ("descendant of& must be declared"
14072                        & " as a synchronized interface",
14073                          N, Parent_Type);
14074
14075                elsif Task_Present (Iface_Def) then
14076                   Error_Msg_NE
14077                     ("descendant of& must be declared as a task interface",
14078                        N, Parent_Type);
14079
14080                else
14081                   Error_Msg_N
14082                     ("(Ada 2005) limited interface cannot "
14083                      & "inherit from non-limited interface", Indic);
14084                end if;
14085
14086             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
14087             --  from non-limited or limited interfaces.
14088
14089             elsif not Protected_Present (Def)
14090               and then not Synchronized_Present (Def)
14091               and then not Task_Present (Def)
14092             then
14093                if Limited_Present (Iface_Def) then
14094                   null;
14095
14096                elsif Protected_Present (Iface_Def) then
14097                   Error_Msg_NE
14098                     ("descendant of& must be declared"
14099                        & " as a protected interface",
14100                          N, Parent_Type);
14101
14102                elsif Synchronized_Present (Iface_Def) then
14103                   Error_Msg_NE
14104                     ("descendant of& must be declared"
14105                        & " as a synchronized interface",
14106                          N, Parent_Type);
14107
14108                elsif Task_Present (Iface_Def) then
14109                   Error_Msg_NE
14110                     ("descendant of& must be declared as a task interface",
14111                        N, Parent_Type);
14112                else
14113                   null;
14114                end if;
14115             end if;
14116          end if;
14117       end if;
14118
14119       if Is_Tagged_Type (Parent_Type)
14120         and then Is_Concurrent_Type (Parent_Type)
14121         and then not Is_Interface (Parent_Type)
14122       then
14123          Error_Msg_N
14124            ("parent type of a record extension cannot be "
14125             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
14126          Set_Etype (T, Any_Type);
14127          return;
14128       end if;
14129
14130       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
14131       --  interfaces
14132
14133       if Is_Tagged_Type (Parent_Type)
14134         and then Is_Non_Empty_List (Interface_List (Def))
14135       then
14136          declare
14137             Intf : Node_Id;
14138             T    : Entity_Id;
14139
14140          begin
14141             Intf := First (Interface_List (Def));
14142             while Present (Intf) loop
14143                T := Find_Type_Of_Subtype_Indic (Intf);
14144
14145                if not Is_Interface (T) then
14146                   Diagnose_Interface (Intf, T);
14147
14148                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
14149                --  a limited type from having a nonlimited progenitor.
14150
14151                elsif (Limited_Present (Def)
14152                        or else (not Is_Interface (Parent_Type)
14153                                  and then Is_Limited_Type (Parent_Type)))
14154                  and then not Is_Limited_Interface (T)
14155                then
14156                   Error_Msg_NE
14157                    ("progenitor interface& of limited type must be limited",
14158                      N, T);
14159                end if;
14160
14161                Next (Intf);
14162             end loop;
14163          end;
14164       end if;
14165
14166       if Parent_Type = Any_Type
14167         or else Etype (Parent_Type) = Any_Type
14168         or else (Is_Class_Wide_Type (Parent_Type)
14169                    and then Etype (Parent_Type) = T)
14170       then
14171          --  If Parent_Type is undefined or illegal, make new type into a
14172          --  subtype of Any_Type, and set a few attributes to prevent cascaded
14173          --  errors. If this is a self-definition, emit error now.
14174
14175          if T = Parent_Type
14176            or else T = Etype (Parent_Type)
14177          then
14178             Error_Msg_N ("type cannot be used in its own definition", Indic);
14179          end if;
14180
14181          Set_Ekind        (T, Ekind (Parent_Type));
14182          Set_Etype        (T, Any_Type);
14183          Set_Scalar_Range (T, Scalar_Range (Any_Type));
14184
14185          if Is_Tagged_Type (T)
14186            and then Is_Record_Type (T)
14187          then
14188             Set_Direct_Primitive_Operations (T, New_Elmt_List);
14189          end if;
14190
14191          return;
14192       end if;
14193
14194       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
14195       --  an interface is special because the list of interfaces in the full
14196       --  view can be given in any order. For example:
14197
14198       --     type A is interface;
14199       --     type B is interface and A;
14200       --     type D is new B with private;
14201       --   private
14202       --     type D is new A and B with null record; -- 1 --
14203
14204       --  In this case we perform the following transformation of -1-:
14205
14206       --     type D is new B and A with null record;
14207
14208       --  If the parent of the full-view covers the parent of the partial-view
14209       --  we have two possible cases:
14210
14211       --     1) They have the same parent
14212       --     2) The parent of the full-view implements some further interfaces
14213
14214       --  In both cases we do not need to perform the transformation. In the
14215       --  first case the source program is correct and the transformation is
14216       --  not needed; in the second case the source program does not fulfill
14217       --  the no-hidden interfaces rule (AI-396) and the error will be reported
14218       --  later.
14219
14220       --  This transformation not only simplifies the rest of the analysis of
14221       --  this type declaration but also simplifies the correct generation of
14222       --  the object layout to the expander.
14223
14224       if In_Private_Part (Current_Scope)
14225         and then Is_Interface (Parent_Type)
14226       then
14227          declare
14228             Iface               : Node_Id;
14229             Partial_View        : Entity_Id;
14230             Partial_View_Parent : Entity_Id;
14231             New_Iface           : Node_Id;
14232
14233          begin
14234             --  Look for the associated private type declaration
14235
14236             Partial_View := First_Entity (Current_Scope);
14237             loop
14238                exit when No (Partial_View)
14239                  or else (Has_Private_Declaration (Partial_View)
14240                            and then Full_View (Partial_View) = T);
14241
14242                Next_Entity (Partial_View);
14243             end loop;
14244
14245             --  If the partial view was not found then the source code has
14246             --  errors and the transformation is not needed.
14247
14248             if Present (Partial_View) then
14249                Partial_View_Parent := Etype (Partial_View);
14250
14251                --  If the parent of the full-view covers the parent of the
14252                --  partial-view we have nothing else to do.
14253
14254                if Interface_Present_In_Ancestor
14255                     (Parent_Type, Partial_View_Parent)
14256                then
14257                   null;
14258
14259                --  Traverse the list of interfaces of the full-view to look
14260                --  for the parent of the partial-view and perform the tree
14261                --  transformation.
14262
14263                else
14264                   Iface := First (Interface_List (Def));
14265                   while Present (Iface) loop
14266                      if Etype (Iface) = Etype (Partial_View) then
14267                         Rewrite (Subtype_Indication (Def),
14268                           New_Copy (Subtype_Indication
14269                                      (Parent (Partial_View))));
14270
14271                         New_Iface :=
14272                           Make_Identifier (Sloc (N), Chars (Parent_Type));
14273                         Append (New_Iface, Interface_List (Def));
14274
14275                         --  Analyze the transformed code
14276
14277                         Derived_Type_Declaration (T, N, Is_Completion);
14278                         return;
14279                      end if;
14280
14281                      Next (Iface);
14282                   end loop;
14283                end if;
14284             end if;
14285          end;
14286       end if;
14287
14288       --  Only composite types other than array types are allowed to have
14289       --  discriminants. In SPARK, no types are allowed to have discriminants.
14290
14291       if Present (Discriminant_Specifications (N)) then
14292          if (Is_Elementary_Type (Parent_Type)
14293               or else Is_Array_Type (Parent_Type))
14294            and then not Error_Posted (N)
14295          then
14296             Error_Msg_N
14297               ("elementary or array type cannot have discriminants",
14298                Defining_Identifier (First (Discriminant_Specifications (N))));
14299             Set_Has_Discriminants (T, False);
14300          else
14301             Check_SPARK_Restriction ("discriminant type is not allowed", N);
14302          end if;
14303       end if;
14304
14305       --  In Ada 83, a derived type defined in a package specification cannot
14306       --  be used for further derivation until the end of its visible part.
14307       --  Note that derivation in the private part of the package is allowed.
14308
14309       if Ada_Version = Ada_83
14310         and then Is_Derived_Type (Parent_Type)
14311         and then In_Visible_Part (Scope (Parent_Type))
14312       then
14313          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
14314             Error_Msg_N
14315               ("(Ada 83): premature use of type for derivation", Indic);
14316          end if;
14317       end if;
14318
14319       --  Check for early use of incomplete or private type
14320
14321       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
14322          Error_Msg_N ("premature derivation of incomplete type", Indic);
14323          return;
14324
14325       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
14326               and then not Comes_From_Generic (Parent_Type))
14327         or else Has_Private_Component (Parent_Type)
14328       then
14329          --  The ancestor type of a formal type can be incomplete, in which
14330          --  case only the operations of the partial view are available in the
14331          --  generic. Subsequent checks may be required when the full view is
14332          --  analyzed to verify that a derivation from a tagged type has an
14333          --  extension.
14334
14335          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
14336             null;
14337
14338          elsif No (Underlying_Type (Parent_Type))
14339            or else Has_Private_Component (Parent_Type)
14340          then
14341             Error_Msg_N
14342               ("premature derivation of derived or private type", Indic);
14343
14344             --  Flag the type itself as being in error, this prevents some
14345             --  nasty problems with subsequent uses of the malformed type.
14346
14347             Set_Error_Posted (T);
14348
14349          --  Check that within the immediate scope of an untagged partial
14350          --  view it's illegal to derive from the partial view if the
14351          --  full view is tagged. (7.3(7))
14352
14353          --  We verify that the Parent_Type is a partial view by checking
14354          --  that it is not a Full_Type_Declaration (i.e. a private type or
14355          --  private extension declaration), to distinguish a partial view
14356          --  from  a derivation from a private type which also appears as
14357          --  E_Private_Type. If the parent base type is not declared in an
14358          --  enclosing scope there is no need to check.
14359
14360          elsif Present (Full_View (Parent_Type))
14361            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
14362            and then not Is_Tagged_Type (Parent_Type)
14363            and then Is_Tagged_Type (Full_View (Parent_Type))
14364            and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
14365          then
14366             Error_Msg_N
14367               ("premature derivation from type with tagged full view",
14368                 Indic);
14369          end if;
14370       end if;
14371
14372       --  Check that form of derivation is appropriate
14373
14374       Taggd := Is_Tagged_Type (Parent_Type);
14375
14376       --  Perhaps the parent type should be changed to the class-wide type's
14377       --  specific type in this case to prevent cascading errors ???
14378
14379       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
14380          Error_Msg_N ("parent type must not be a class-wide type", Indic);
14381          return;
14382       end if;
14383
14384       if Present (Extension) and then not Taggd then
14385          Error_Msg_N
14386            ("type derived from untagged type cannot have extension", Indic);
14387
14388       elsif No (Extension) and then Taggd then
14389
14390          --  If this declaration is within a private part (or body) of a
14391          --  generic instantiation then the derivation is allowed (the parent
14392          --  type can only appear tagged in this case if it's a generic actual
14393          --  type, since it would otherwise have been rejected in the analysis
14394          --  of the generic template).
14395
14396          if not Is_Generic_Actual_Type (Parent_Type)
14397            or else In_Visible_Part (Scope (Parent_Type))
14398          then
14399             if Is_Class_Wide_Type (Parent_Type) then
14400                Error_Msg_N
14401                  ("parent type must not be a class-wide type", Indic);
14402
14403                --  Use specific type to prevent cascaded errors.
14404
14405                Parent_Type := Etype (Parent_Type);
14406
14407             else
14408                Error_Msg_N
14409                  ("type derived from tagged type must have extension", Indic);
14410             end if;
14411          end if;
14412       end if;
14413
14414       --  AI-443: Synchronized formal derived types require a private
14415       --  extension. There is no point in checking the ancestor type or
14416       --  the progenitors since the construct is wrong to begin with.
14417
14418       if Ada_Version >= Ada_2005
14419         and then Is_Generic_Type (T)
14420         and then Present (Original_Node (N))
14421       then
14422          declare
14423             Decl : constant Node_Id := Original_Node (N);
14424
14425          begin
14426             if Nkind (Decl) = N_Formal_Type_Declaration
14427               and then Nkind (Formal_Type_Definition (Decl)) =
14428                          N_Formal_Derived_Type_Definition
14429               and then Synchronized_Present (Formal_Type_Definition (Decl))
14430               and then No (Extension)
14431
14432                --  Avoid emitting a duplicate error message
14433
14434               and then not Error_Posted (Indic)
14435             then
14436                Error_Msg_N
14437                  ("synchronized derived type must have extension", N);
14438             end if;
14439          end;
14440       end if;
14441
14442       if Null_Exclusion_Present (Def)
14443         and then not Is_Access_Type (Parent_Type)
14444       then
14445          Error_Msg_N ("null exclusion can only apply to an access type", N);
14446       end if;
14447
14448       --  Avoid deriving parent primitives of underlying record views
14449
14450       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
14451         Derive_Subps => not Is_Underlying_Record_View (T));
14452
14453       --  AI-419: The parent type of an explicitly limited derived type must
14454       --  be a limited type or a limited interface.
14455
14456       if Limited_Present (Def) then
14457          Set_Is_Limited_Record (T);
14458
14459          if Is_Interface (T) then
14460             Set_Is_Limited_Interface (T);
14461          end if;
14462
14463          if not Is_Limited_Type (Parent_Type)
14464            and then
14465              (not Is_Interface (Parent_Type)
14466                or else not Is_Limited_Interface (Parent_Type))
14467          then
14468             --  AI05-0096: a derivation in the private part of an instance is
14469             --  legal if the generic formal is untagged limited, and the actual
14470             --  is non-limited.
14471
14472             if Is_Generic_Actual_Type (Parent_Type)
14473               and then In_Private_Part (Current_Scope)
14474               and then
14475                 not Is_Tagged_Type
14476                       (Generic_Parent_Type (Parent (Parent_Type)))
14477             then
14478                null;
14479
14480             else
14481                Error_Msg_NE
14482                  ("parent type& of limited type must be limited",
14483                   N, Parent_Type);
14484             end if;
14485          end if;
14486       end if;
14487
14488       --  In SPARK, there are no derived type definitions other than type
14489       --  extensions of tagged record types.
14490
14491       if No (Extension) then
14492          Check_SPARK_Restriction ("derived type is not allowed", N);
14493       end if;
14494    end Derived_Type_Declaration;
14495
14496    ------------------------
14497    -- Diagnose_Interface --
14498    ------------------------
14499
14500    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
14501    begin
14502       if not Is_Interface (E)
14503         and then  E /= Any_Type
14504       then
14505          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
14506       end if;
14507    end Diagnose_Interface;
14508
14509    ----------------------------------
14510    -- Enumeration_Type_Declaration --
14511    ----------------------------------
14512
14513    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14514       Ev     : Uint;
14515       L      : Node_Id;
14516       R_Node : Node_Id;
14517       B_Node : Node_Id;
14518
14519    begin
14520       --  Create identifier node representing lower bound
14521
14522       B_Node := New_Node (N_Identifier, Sloc (Def));
14523       L := First (Literals (Def));
14524       Set_Chars (B_Node, Chars (L));
14525       Set_Entity (B_Node,  L);
14526       Set_Etype (B_Node, T);
14527       Set_Is_Static_Expression (B_Node, True);
14528
14529       R_Node := New_Node (N_Range, Sloc (Def));
14530       Set_Low_Bound  (R_Node, B_Node);
14531
14532       Set_Ekind (T, E_Enumeration_Type);
14533       Set_First_Literal (T, L);
14534       Set_Etype (T, T);
14535       Set_Is_Constrained (T);
14536
14537       Ev := Uint_0;
14538
14539       --  Loop through literals of enumeration type setting pos and rep values
14540       --  except that if the Ekind is already set, then it means the literal
14541       --  was already constructed (case of a derived type declaration and we
14542       --  should not disturb the Pos and Rep values.
14543
14544       while Present (L) loop
14545          if Ekind (L) /= E_Enumeration_Literal then
14546             Set_Ekind (L, E_Enumeration_Literal);
14547             Set_Enumeration_Pos (L, Ev);
14548             Set_Enumeration_Rep (L, Ev);
14549             Set_Is_Known_Valid  (L, True);
14550          end if;
14551
14552          Set_Etype (L, T);
14553          New_Overloaded_Entity (L);
14554          Generate_Definition (L);
14555          Set_Convention (L, Convention_Intrinsic);
14556
14557          --  Case of character literal
14558
14559          if Nkind (L) = N_Defining_Character_Literal then
14560             Set_Is_Character_Type (T, True);
14561
14562             --  Check violation of No_Wide_Characters
14563
14564             if Restriction_Check_Required (No_Wide_Characters) then
14565                Get_Name_String (Chars (L));
14566
14567                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
14568                   Check_Restriction (No_Wide_Characters, L);
14569                end if;
14570             end if;
14571          end if;
14572
14573          Ev := Ev + 1;
14574          Next (L);
14575       end loop;
14576
14577       --  Now create a node representing upper bound
14578
14579       B_Node := New_Node (N_Identifier, Sloc (Def));
14580       Set_Chars (B_Node, Chars (Last (Literals (Def))));
14581       Set_Entity (B_Node,  Last (Literals (Def)));
14582       Set_Etype (B_Node, T);
14583       Set_Is_Static_Expression (B_Node, True);
14584
14585       Set_High_Bound (R_Node, B_Node);
14586
14587       --  Initialize various fields of the type. Some of this information
14588       --  may be overwritten later through rep.clauses.
14589
14590       Set_Scalar_Range    (T, R_Node);
14591       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
14592       Set_Enum_Esize      (T);
14593       Set_Enum_Pos_To_Rep (T, Empty);
14594
14595       --  Set Discard_Names if configuration pragma set, or if there is
14596       --  a parameterless pragma in the current declarative region
14597
14598       if Global_Discard_Names
14599         or else Discard_Names (Scope (T))
14600       then
14601          Set_Discard_Names (T);
14602       end if;
14603
14604       --  Process end label if there is one
14605
14606       if Present (Def) then
14607          Process_End_Label (Def, 'e', T);
14608       end if;
14609    end Enumeration_Type_Declaration;
14610
14611    ---------------------------------
14612    -- Expand_To_Stored_Constraint --
14613    ---------------------------------
14614
14615    function Expand_To_Stored_Constraint
14616      (Typ        : Entity_Id;
14617       Constraint : Elist_Id) return Elist_Id
14618    is
14619       Explicitly_Discriminated_Type : Entity_Id;
14620       Expansion    : Elist_Id;
14621       Discriminant : Entity_Id;
14622
14623       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
14624       --  Find the nearest type that actually specifies discriminants
14625
14626       ---------------------------------
14627       -- Type_With_Explicit_Discrims --
14628       ---------------------------------
14629
14630       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
14631          Typ : constant E := Base_Type (Id);
14632
14633       begin
14634          if Ekind (Typ) in Incomplete_Or_Private_Kind then
14635             if Present (Full_View (Typ)) then
14636                return Type_With_Explicit_Discrims (Full_View (Typ));
14637             end if;
14638
14639          else
14640             if Has_Discriminants (Typ) then
14641                return Typ;
14642             end if;
14643          end if;
14644
14645          if Etype (Typ) = Typ then
14646             return Empty;
14647          elsif Has_Discriminants (Typ) then
14648             return Typ;
14649          else
14650             return Type_With_Explicit_Discrims (Etype (Typ));
14651          end if;
14652
14653       end Type_With_Explicit_Discrims;
14654
14655    --  Start of processing for Expand_To_Stored_Constraint
14656
14657    begin
14658       if No (Constraint)
14659         or else Is_Empty_Elmt_List (Constraint)
14660       then
14661          return No_Elist;
14662       end if;
14663
14664       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
14665
14666       if No (Explicitly_Discriminated_Type) then
14667          return No_Elist;
14668       end if;
14669
14670       Expansion := New_Elmt_List;
14671
14672       Discriminant :=
14673          First_Stored_Discriminant (Explicitly_Discriminated_Type);
14674       while Present (Discriminant) loop
14675          Append_Elmt (
14676            Get_Discriminant_Value (
14677              Discriminant, Explicitly_Discriminated_Type, Constraint),
14678            Expansion);
14679          Next_Stored_Discriminant (Discriminant);
14680       end loop;
14681
14682       return Expansion;
14683    end Expand_To_Stored_Constraint;
14684
14685    ---------------------------
14686    -- Find_Hidden_Interface --
14687    ---------------------------
14688
14689    function Find_Hidden_Interface
14690      (Src  : Elist_Id;
14691       Dest : Elist_Id) return Entity_Id
14692    is
14693       Iface      : Entity_Id;
14694       Iface_Elmt : Elmt_Id;
14695
14696    begin
14697       if Present (Src) and then Present (Dest) then
14698          Iface_Elmt := First_Elmt (Src);
14699          while Present (Iface_Elmt) loop
14700             Iface := Node (Iface_Elmt);
14701
14702             if Is_Interface (Iface)
14703               and then not Contain_Interface (Iface, Dest)
14704             then
14705                return Iface;
14706             end if;
14707
14708             Next_Elmt (Iface_Elmt);
14709          end loop;
14710       end if;
14711
14712       return Empty;
14713    end Find_Hidden_Interface;
14714
14715    --------------------
14716    -- Find_Type_Name --
14717    --------------------
14718
14719    function Find_Type_Name (N : Node_Id) return Entity_Id is
14720       Id       : constant Entity_Id := Defining_Identifier (N);
14721       Prev     : Entity_Id;
14722       New_Id   : Entity_Id;
14723       Prev_Par : Node_Id;
14724
14725       procedure Tag_Mismatch;
14726       --  Diagnose a tagged partial view whose full view is untagged.
14727       --  We post the message on the full view, with a reference to
14728       --  the previous partial view. The partial view can be private
14729       --  or incomplete, and these are handled in a different manner,
14730       --  so we determine the position of the error message from the
14731       --  respective slocs of both.
14732
14733       ------------------
14734       -- Tag_Mismatch --
14735       ------------------
14736
14737       procedure Tag_Mismatch is
14738       begin
14739          if Sloc (Prev) < Sloc (Id) then
14740             if Ada_Version >= Ada_2012
14741               and then Nkind (N) = N_Private_Type_Declaration
14742             then
14743                Error_Msg_NE
14744                  ("declaration of private } must be a tagged type ", Id, Prev);
14745             else
14746                Error_Msg_NE
14747                  ("full declaration of } must be a tagged type ", Id, Prev);
14748             end if;
14749          else
14750             if Ada_Version >= Ada_2012
14751               and then Nkind (N) = N_Private_Type_Declaration
14752             then
14753                Error_Msg_NE
14754                  ("declaration of private } must be a tagged type ", Prev, Id);
14755             else
14756                Error_Msg_NE
14757                  ("full declaration of } must be a tagged type ", Prev, Id);
14758             end if;
14759          end if;
14760       end Tag_Mismatch;
14761
14762    --  Start of processing for Find_Type_Name
14763
14764    begin
14765       --  Find incomplete declaration, if one was given
14766
14767       Prev := Current_Entity_In_Scope (Id);
14768
14769       --  New type declaration
14770
14771       if No (Prev) then
14772          Enter_Name (Id);
14773          return Id;
14774
14775       --  Previous declaration exists
14776
14777       else
14778          Prev_Par := Parent (Prev);
14779
14780          --  Error if not incomplete/private case except if previous
14781          --  declaration is implicit, etc. Enter_Name will emit error if
14782          --  appropriate.
14783
14784          if not Is_Incomplete_Or_Private_Type (Prev) then
14785             Enter_Name (Id);
14786             New_Id := Id;
14787
14788          --  Check invalid completion of private or incomplete type
14789
14790          elsif not Nkind_In (N, N_Full_Type_Declaration,
14791                                 N_Task_Type_Declaration,
14792                                 N_Protected_Type_Declaration)
14793            and then
14794              (Ada_Version < Ada_2012
14795                 or else not Is_Incomplete_Type (Prev)
14796                 or else not Nkind_In (N, N_Private_Type_Declaration,
14797                                          N_Private_Extension_Declaration))
14798          then
14799             --  Completion must be a full type declarations (RM 7.3(4))
14800
14801             Error_Msg_Sloc := Sloc (Prev);
14802             Error_Msg_NE ("invalid completion of }", Id, Prev);
14803
14804             --  Set scope of Id to avoid cascaded errors. Entity is never
14805             --  examined again, except when saving globals in generics.
14806
14807             Set_Scope (Id, Current_Scope);
14808             New_Id := Id;
14809
14810             --  If this is a repeated incomplete declaration, no further
14811             --  checks are possible.
14812
14813             if Nkind (N) = N_Incomplete_Type_Declaration then
14814                return Prev;
14815             end if;
14816
14817          --  Case of full declaration of incomplete type
14818
14819          elsif Ekind (Prev) = E_Incomplete_Type
14820            and then (Ada_Version < Ada_2012
14821                       or else No (Full_View (Prev))
14822                       or else not Is_Private_Type (Full_View (Prev)))
14823          then
14824
14825             --  Indicate that the incomplete declaration has a matching full
14826             --  declaration. The defining occurrence of the incomplete
14827             --  declaration remains the visible one, and the procedure
14828             --  Get_Full_View dereferences it whenever the type is used.
14829
14830             if Present (Full_View (Prev)) then
14831                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14832             end if;
14833
14834             Set_Full_View (Prev, Id);
14835             Append_Entity (Id, Current_Scope);
14836             Set_Is_Public (Id, Is_Public (Prev));
14837             Set_Is_Internal (Id);
14838             New_Id := Prev;
14839
14840             --  If the incomplete view is tagged, a class_wide type has been
14841             --  created already. Use it for the private type as well, in order
14842             --  to prevent multiple incompatible class-wide types that may be
14843             --  created for self-referential anonymous access components.
14844
14845             if Is_Tagged_Type (Prev)
14846               and then Present (Class_Wide_Type (Prev))
14847             then
14848                Set_Ekind (Id, Ekind (Prev));         --  will be reset later
14849                Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
14850                Set_Etype (Class_Wide_Type (Id), Id);
14851             end if;
14852
14853          --  Case of full declaration of private type
14854
14855          else
14856             --  If the private type was a completion of an incomplete type then
14857             --  update Prev to reference the private type
14858
14859             if Ada_Version >= Ada_2012
14860               and then Ekind (Prev) = E_Incomplete_Type
14861               and then Present (Full_View (Prev))
14862               and then Is_Private_Type (Full_View (Prev))
14863             then
14864                Prev := Full_View (Prev);
14865                Prev_Par := Parent (Prev);
14866             end if;
14867
14868             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
14869                if Etype (Prev) /= Prev then
14870
14871                   --  Prev is a private subtype or a derived type, and needs
14872                   --  no completion.
14873
14874                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14875                   New_Id := Id;
14876
14877                elsif Ekind (Prev) = E_Private_Type
14878                  and then Nkind_In (N, N_Task_Type_Declaration,
14879                                        N_Protected_Type_Declaration)
14880                then
14881                   Error_Msg_N
14882                    ("completion of nonlimited type cannot be limited", N);
14883
14884                elsif Ekind (Prev) = E_Record_Type_With_Private
14885                  and then Nkind_In (N, N_Task_Type_Declaration,
14886                                        N_Protected_Type_Declaration)
14887                then
14888                   if not Is_Limited_Record (Prev) then
14889                      Error_Msg_N
14890                         ("completion of nonlimited type cannot be limited", N);
14891
14892                   elsif No (Interface_List (N)) then
14893                      Error_Msg_N
14894                         ("completion of tagged private type must be tagged",
14895                          N);
14896                   end if;
14897
14898                elsif Nkind (N) = N_Full_Type_Declaration
14899                  and then
14900                    Nkind (Type_Definition (N)) = N_Record_Definition
14901                  and then Interface_Present (Type_Definition (N))
14902                then
14903                   Error_Msg_N
14904                     ("completion of private type cannot be an interface", N);
14905                end if;
14906
14907             --  Ada 2005 (AI-251): Private extension declaration of a task
14908             --  type or a protected type. This case arises when covering
14909             --  interface types.
14910
14911             elsif Nkind_In (N, N_Task_Type_Declaration,
14912                                N_Protected_Type_Declaration)
14913             then
14914                null;
14915
14916             elsif Nkind (N) /= N_Full_Type_Declaration
14917               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
14918             then
14919                Error_Msg_N
14920                  ("full view of private extension must be an extension", N);
14921
14922             elsif not (Abstract_Present (Parent (Prev)))
14923               and then Abstract_Present (Type_Definition (N))
14924             then
14925                Error_Msg_N
14926                  ("full view of non-abstract extension cannot be abstract", N);
14927             end if;
14928
14929             if not In_Private_Part (Current_Scope) then
14930                Error_Msg_N
14931                  ("declaration of full view must appear in private part", N);
14932             end if;
14933
14934             Copy_And_Swap (Prev, Id);
14935             Set_Has_Private_Declaration (Prev);
14936             Set_Has_Private_Declaration (Id);
14937
14938             --  Preserve aspect and iterator flags that may have been set on
14939             --  the partial view.
14940
14941             Set_Has_Delayed_Aspects (Prev, Has_Delayed_Aspects (Id));
14942             Set_Has_Implicit_Dereference (Prev, Has_Implicit_Dereference (Id));
14943
14944             --  If no error, propagate freeze_node from private to full view.
14945             --  It may have been generated for an early operational item.
14946
14947             if Present (Freeze_Node (Id))
14948               and then Serious_Errors_Detected = 0
14949               and then No (Full_View (Id))
14950             then
14951                Set_Freeze_Node (Prev, Freeze_Node (Id));
14952                Set_Freeze_Node (Id, Empty);
14953                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
14954             end if;
14955
14956             Set_Full_View (Id, Prev);
14957             New_Id := Prev;
14958          end if;
14959
14960          --  Verify that full declaration conforms to partial one
14961
14962          if Is_Incomplete_Or_Private_Type (Prev)
14963            and then Present (Discriminant_Specifications (Prev_Par))
14964          then
14965             if Present (Discriminant_Specifications (N)) then
14966                if Ekind (Prev) = E_Incomplete_Type then
14967                   Check_Discriminant_Conformance (N, Prev, Prev);
14968                else
14969                   Check_Discriminant_Conformance (N, Prev, Id);
14970                end if;
14971
14972             else
14973                Error_Msg_N
14974                  ("missing discriminants in full type declaration", N);
14975
14976                --  To avoid cascaded errors on subsequent use, share the
14977                --  discriminants of the partial view.
14978
14979                Set_Discriminant_Specifications (N,
14980                  Discriminant_Specifications (Prev_Par));
14981             end if;
14982          end if;
14983
14984          --  A prior untagged partial view can have an associated class-wide
14985          --  type due to use of the class attribute, and in this case the full
14986          --  type must also be tagged. This Ada 95 usage is deprecated in favor
14987          --  of incomplete tagged declarations, but we check for it.
14988
14989          if Is_Type (Prev)
14990            and then (Is_Tagged_Type (Prev)
14991                        or else Present (Class_Wide_Type (Prev)))
14992          then
14993             --  Ada 2012 (AI05-0162): A private type may be the completion of
14994             --  an incomplete type
14995
14996             if Ada_Version >= Ada_2012
14997               and then Is_Incomplete_Type (Prev)
14998               and then Nkind_In (N, N_Private_Type_Declaration,
14999                                     N_Private_Extension_Declaration)
15000             then
15001                --  No need to check private extensions since they are tagged
15002
15003                if Nkind (N) = N_Private_Type_Declaration
15004                  and then not Tagged_Present (N)
15005                then
15006                   Tag_Mismatch;
15007                end if;
15008
15009             --  The full declaration is either a tagged type (including
15010             --  a synchronized type that implements interfaces) or a
15011             --  type extension, otherwise this is an error.
15012
15013             elsif Nkind_In (N, N_Task_Type_Declaration,
15014                                N_Protected_Type_Declaration)
15015             then
15016                if No (Interface_List (N))
15017                  and then not Error_Posted (N)
15018                then
15019                   Tag_Mismatch;
15020                end if;
15021
15022             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
15023
15024                --  Indicate that the previous declaration (tagged incomplete
15025                --  or private declaration) requires the same on the full one.
15026
15027                if not Tagged_Present (Type_Definition (N)) then
15028                   Tag_Mismatch;
15029                   Set_Is_Tagged_Type (Id);
15030                end if;
15031
15032             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
15033                if No (Record_Extension_Part (Type_Definition (N))) then
15034                   Error_Msg_NE
15035                     ("full declaration of } must be a record extension",
15036                      Prev, Id);
15037
15038                   --  Set some attributes to produce a usable full view
15039
15040                   Set_Is_Tagged_Type (Id);
15041                end if;
15042
15043             else
15044                Tag_Mismatch;
15045             end if;
15046          end if;
15047
15048          if Present (Prev)
15049            and then Nkind (Parent (Prev)) = N_Incomplete_Type_Declaration
15050            and then Present (Premature_Use (Parent (Prev)))
15051          then
15052             Error_Msg_Sloc := Sloc (N);
15053             Error_Msg_N
15054               ("\full declaration #", Premature_Use (Parent (Prev)));
15055          end if;
15056
15057          return New_Id;
15058       end if;
15059    end Find_Type_Name;
15060
15061    -------------------------
15062    -- Find_Type_Of_Object --
15063    -------------------------
15064
15065    function Find_Type_Of_Object
15066      (Obj_Def     : Node_Id;
15067       Related_Nod : Node_Id) return Entity_Id
15068    is
15069       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
15070       P        : Node_Id := Parent (Obj_Def);
15071       T        : Entity_Id;
15072       Nam      : Name_Id;
15073
15074    begin
15075       --  If the parent is a component_definition node we climb to the
15076       --  component_declaration node
15077
15078       if Nkind (P) = N_Component_Definition then
15079          P := Parent (P);
15080       end if;
15081
15082       --  Case of an anonymous array subtype
15083
15084       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
15085                              N_Unconstrained_Array_Definition)
15086       then
15087          T := Empty;
15088          Array_Type_Declaration (T, Obj_Def);
15089
15090       --  Create an explicit subtype whenever possible
15091
15092       elsif Nkind (P) /= N_Component_Declaration
15093         and then Def_Kind = N_Subtype_Indication
15094       then
15095          --  Base name of subtype on object name, which will be unique in
15096          --  the current scope.
15097
15098          --  If this is a duplicate declaration, return base type, to avoid
15099          --  generating duplicate anonymous types.
15100
15101          if Error_Posted (P) then
15102             Analyze (Subtype_Mark (Obj_Def));
15103             return Entity (Subtype_Mark (Obj_Def));
15104          end if;
15105
15106          Nam :=
15107             New_External_Name
15108              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
15109
15110          T := Make_Defining_Identifier (Sloc (P), Nam);
15111
15112          Insert_Action (Obj_Def,
15113            Make_Subtype_Declaration (Sloc (P),
15114              Defining_Identifier => T,
15115              Subtype_Indication  => Relocate_Node (Obj_Def)));
15116
15117          --  This subtype may need freezing, and this will not be done
15118          --  automatically if the object declaration is not in declarative
15119          --  part. Since this is an object declaration, the type cannot always
15120          --  be frozen here. Deferred constants do not freeze their type
15121          --  (which often enough will be private).
15122
15123          if Nkind (P) = N_Object_Declaration
15124            and then Constant_Present (P)
15125            and then No (Expression (P))
15126          then
15127             null;
15128          else
15129             Insert_Actions (Obj_Def, Freeze_Entity (T, P));
15130          end if;
15131
15132       --  Ada 2005 AI-406: the object definition in an object declaration
15133       --  can be an access definition.
15134
15135       elsif Def_Kind = N_Access_Definition then
15136          T := Access_Definition (Related_Nod, Obj_Def);
15137
15138          Set_Is_Local_Anonymous_Access
15139            (T,
15140             V => (Ada_Version < Ada_2012)
15141                    or else (Nkind (P) /= N_Object_Declaration)
15142                    or else Is_Library_Level_Entity (Defining_Identifier (P)));
15143
15144       --  Otherwise, the object definition is just a subtype_mark
15145
15146       else
15147          T := Process_Subtype (Obj_Def, Related_Nod);
15148
15149          --  If expansion is disabled an object definition that is an aggregate
15150          --  will not get expanded and may lead to scoping problems in the back
15151          --  end, if the object is referenced in an inner scope. In that case
15152          --  create an itype reference for the object definition now. This
15153          --  may be redundant in some cases, but harmless.
15154
15155          if Is_Itype (T)
15156            and then Nkind (Related_Nod) = N_Object_Declaration
15157            and then ASIS_Mode
15158          then
15159             Build_Itype_Reference (T, Related_Nod);
15160          end if;
15161       end if;
15162
15163       return T;
15164    end Find_Type_Of_Object;
15165
15166    --------------------------------
15167    -- Find_Type_Of_Subtype_Indic --
15168    --------------------------------
15169
15170    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
15171       Typ : Entity_Id;
15172
15173    begin
15174       --  Case of subtype mark with a constraint
15175
15176       if Nkind (S) = N_Subtype_Indication then
15177          Find_Type (Subtype_Mark (S));
15178          Typ := Entity (Subtype_Mark (S));
15179
15180          if not
15181            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
15182          then
15183             Error_Msg_N
15184               ("incorrect constraint for this kind of type", Constraint (S));
15185             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
15186          end if;
15187
15188       --  Otherwise we have a subtype mark without a constraint
15189
15190       elsif Error_Posted (S) then
15191          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
15192          return Any_Type;
15193
15194       else
15195          Find_Type (S);
15196          Typ := Entity (S);
15197       end if;
15198
15199       --  Check No_Wide_Characters restriction
15200
15201       Check_Wide_Character_Restriction (Typ, S);
15202
15203       return Typ;
15204    end Find_Type_Of_Subtype_Indic;
15205
15206    -------------------------------------
15207    -- Floating_Point_Type_Declaration --
15208    -------------------------------------
15209
15210    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
15211       Digs          : constant Node_Id := Digits_Expression (Def);
15212       Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
15213       Digs_Val      : Uint;
15214       Base_Typ      : Entity_Id;
15215       Implicit_Base : Entity_Id;
15216       Bound         : Node_Id;
15217
15218       function Can_Derive_From (E : Entity_Id) return Boolean;
15219       --  Find if given digits value, and possibly a specified range, allows
15220       --  derivation from specified type
15221
15222       function Find_Base_Type return Entity_Id;
15223       --  Find a predefined base type that Def can derive from, or generate
15224       --  an error and substitute Long_Long_Float if none exists.
15225
15226       ---------------------
15227       -- Can_Derive_From --
15228       ---------------------
15229
15230       function Can_Derive_From (E : Entity_Id) return Boolean is
15231          Spec : constant Entity_Id := Real_Range_Specification (Def);
15232
15233       begin
15234          if Digs_Val > Digits_Value (E) then
15235             return False;
15236          end if;
15237
15238          if Present (Spec) then
15239             if Expr_Value_R (Type_Low_Bound (E)) >
15240                Expr_Value_R (Low_Bound (Spec))
15241             then
15242                return False;
15243             end if;
15244
15245             if Expr_Value_R (Type_High_Bound (E)) <
15246                Expr_Value_R (High_Bound (Spec))
15247             then
15248                return False;
15249             end if;
15250          end if;
15251
15252          return True;
15253       end Can_Derive_From;
15254
15255       --------------------
15256       -- Find_Base_Type --
15257       --------------------
15258
15259       function Find_Base_Type return Entity_Id is
15260          Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
15261
15262       begin
15263          --  Iterate over the predefined types in order, returning the first
15264          --  one that Def can derive from.
15265
15266          while Present (Choice) loop
15267             if Can_Derive_From (Node (Choice)) then
15268                return Node (Choice);
15269             end if;
15270
15271             Next_Elmt (Choice);
15272          end loop;
15273
15274          --  If we can't derive from any existing type, use Long_Long_Float
15275          --  and give appropriate message explaining the problem.
15276
15277          if Digs_Val > Max_Digs_Val then
15278             --  It might be the case that there is a type with the requested
15279             --  range, just not the combination of digits and range.
15280
15281             Error_Msg_N
15282               ("no predefined type has requested range and precision",
15283                Real_Range_Specification (Def));
15284
15285          else
15286             Error_Msg_N
15287               ("range too large for any predefined type",
15288                Real_Range_Specification (Def));
15289          end if;
15290
15291          return Standard_Long_Long_Float;
15292       end Find_Base_Type;
15293
15294    --  Start of processing for Floating_Point_Type_Declaration
15295
15296    begin
15297       Check_Restriction (No_Floating_Point, Def);
15298
15299       --  Create an implicit base type
15300
15301       Implicit_Base :=
15302         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
15303
15304       --  Analyze and verify digits value
15305
15306       Analyze_And_Resolve (Digs, Any_Integer);
15307       Check_Digits_Expression (Digs);
15308       Digs_Val := Expr_Value (Digs);
15309
15310       --  Process possible range spec and find correct type to derive from
15311
15312       Process_Real_Range_Specification (Def);
15313
15314       --  Check that requested number of digits is not too high.
15315
15316       if Digs_Val > Max_Digs_Val then
15317          --  The check for Max_Base_Digits may be somewhat expensive, as it
15318          --  requires reading System, so only do it when necessary.
15319
15320          declare
15321             Max_Base_Digits : constant Uint :=
15322                                 Expr_Value
15323                                   (Expression
15324                                      (Parent (RTE (RE_Max_Base_Digits))));
15325
15326          begin
15327             if Digs_Val > Max_Base_Digits then
15328                Error_Msg_Uint_1 := Max_Base_Digits;
15329                Error_Msg_N ("digits value out of range, maximum is ^", Digs);
15330
15331             elsif No (Real_Range_Specification (Def)) then
15332                Error_Msg_Uint_1 := Max_Digs_Val;
15333                Error_Msg_N ("types with more than ^ digits need range spec "
15334                  & "(RM 3.5.7(6))", Digs);
15335             end if;
15336          end;
15337       end if;
15338
15339       --  Find a suitable type to derive from or complain and use a substitute
15340
15341       Base_Typ := Find_Base_Type;
15342
15343       --  If there are bounds given in the declaration use them as the bounds
15344       --  of the type, otherwise use the bounds of the predefined base type
15345       --  that was chosen based on the Digits value.
15346
15347       if Present (Real_Range_Specification (Def)) then
15348          Set_Scalar_Range (T, Real_Range_Specification (Def));
15349          Set_Is_Constrained (T);
15350
15351          --  The bounds of this range must be converted to machine numbers
15352          --  in accordance with RM 4.9(38).
15353
15354          Bound := Type_Low_Bound (T);
15355
15356          if Nkind (Bound) = N_Real_Literal then
15357             Set_Realval
15358               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
15359             Set_Is_Machine_Number (Bound);
15360          end if;
15361
15362          Bound := Type_High_Bound (T);
15363
15364          if Nkind (Bound) = N_Real_Literal then
15365             Set_Realval
15366               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
15367             Set_Is_Machine_Number (Bound);
15368          end if;
15369
15370       else
15371          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
15372       end if;
15373
15374       --  Complete definition of implicit base and declared first subtype
15375
15376       Set_Etype          (Implicit_Base, Base_Typ);
15377
15378       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
15379       Set_Size_Info      (Implicit_Base,                (Base_Typ));
15380       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
15381       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
15382       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
15383       Set_Float_Rep      (Implicit_Base, Float_Rep      (Base_Typ));
15384
15385       Set_Ekind          (T, E_Floating_Point_Subtype);
15386       Set_Etype          (T, Implicit_Base);
15387
15388       Set_Size_Info      (T,                (Implicit_Base));
15389       Set_RM_Size        (T, RM_Size        (Implicit_Base));
15390       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
15391       Set_Digits_Value   (T, Digs_Val);
15392    end Floating_Point_Type_Declaration;
15393
15394    ----------------------------
15395    -- Get_Discriminant_Value --
15396    ----------------------------
15397
15398    --  This is the situation:
15399
15400    --  There is a non-derived type
15401
15402    --       type T0 (Dx, Dy, Dz...)
15403
15404    --  There are zero or more levels of derivation, with each derivation
15405    --  either purely inheriting the discriminants, or defining its own.
15406
15407    --       type Ti      is new Ti-1
15408    --  or
15409    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
15410    --  or
15411    --       subtype Ti is ...
15412
15413    --  The subtype issue is avoided by the use of Original_Record_Component,
15414    --  and the fact that derived subtypes also derive the constraints.
15415
15416    --  This chain leads back from
15417
15418    --       Typ_For_Constraint
15419
15420    --  Typ_For_Constraint has discriminants, and the value for each
15421    --  discriminant is given by its corresponding Elmt of Constraints.
15422
15423    --  Discriminant is some discriminant in this hierarchy
15424
15425    --  We need to return its value
15426
15427    --  We do this by recursively searching each level, and looking for
15428    --  Discriminant. Once we get to the bottom, we start backing up
15429    --  returning the value for it which may in turn be a discriminant
15430    --  further up, so on the backup we continue the substitution.
15431
15432    function Get_Discriminant_Value
15433      (Discriminant       : Entity_Id;
15434       Typ_For_Constraint : Entity_Id;
15435       Constraint         : Elist_Id) return Node_Id
15436    is
15437       function Search_Derivation_Levels
15438         (Ti                    : Entity_Id;
15439          Discrim_Values        : Elist_Id;
15440          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
15441       --  This is the routine that performs the recursive search of levels
15442       --  as described above.
15443
15444       ------------------------------
15445       -- Search_Derivation_Levels --
15446       ------------------------------
15447
15448       function Search_Derivation_Levels
15449         (Ti                    : Entity_Id;
15450          Discrim_Values        : Elist_Id;
15451          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
15452       is
15453          Assoc          : Elmt_Id;
15454          Disc           : Entity_Id;
15455          Result         : Node_Or_Entity_Id;
15456          Result_Entity  : Node_Id;
15457
15458       begin
15459          --  If inappropriate type, return Error, this happens only in
15460          --  cascaded error situations, and we want to avoid a blow up.
15461
15462          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
15463             return Error;
15464          end if;
15465
15466          --  Look deeper if possible. Use Stored_Constraints only for
15467          --  untagged types. For tagged types use the given constraint.
15468          --  This asymmetry needs explanation???
15469
15470          if not Stored_Discrim_Values
15471            and then Present (Stored_Constraint (Ti))
15472            and then not Is_Tagged_Type (Ti)
15473          then
15474             Result :=
15475               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
15476          else
15477             declare
15478                Td : constant Entity_Id := Etype (Ti);
15479
15480             begin
15481                if Td = Ti then
15482                   Result := Discriminant;
15483
15484                else
15485                   if Present (Stored_Constraint (Ti)) then
15486                      Result :=
15487                         Search_Derivation_Levels
15488                           (Td, Stored_Constraint (Ti), True);
15489                   else
15490                      Result :=
15491                         Search_Derivation_Levels
15492                           (Td, Discrim_Values, Stored_Discrim_Values);
15493                   end if;
15494                end if;
15495             end;
15496          end if;
15497
15498          --  Extra underlying places to search, if not found above. For
15499          --  concurrent types, the relevant discriminant appears in the
15500          --  corresponding record. For a type derived from a private type
15501          --  without discriminant, the full view inherits the discriminants
15502          --  of the full view of the parent.
15503
15504          if Result = Discriminant then
15505             if Is_Concurrent_Type (Ti)
15506               and then Present (Corresponding_Record_Type (Ti))
15507             then
15508                Result :=
15509                  Search_Derivation_Levels (
15510                    Corresponding_Record_Type (Ti),
15511                    Discrim_Values,
15512                    Stored_Discrim_Values);
15513
15514             elsif Is_Private_Type (Ti)
15515               and then not Has_Discriminants (Ti)
15516               and then Present (Full_View (Ti))
15517               and then Etype (Full_View (Ti)) /= Ti
15518             then
15519                Result :=
15520                  Search_Derivation_Levels (
15521                    Full_View (Ti),
15522                    Discrim_Values,
15523                    Stored_Discrim_Values);
15524             end if;
15525          end if;
15526
15527          --  If Result is not a (reference to a) discriminant, return it,
15528          --  otherwise set Result_Entity to the discriminant.
15529
15530          if Nkind (Result) = N_Defining_Identifier then
15531             pragma Assert (Result = Discriminant);
15532             Result_Entity := Result;
15533
15534          else
15535             if not Denotes_Discriminant (Result) then
15536                return Result;
15537             end if;
15538
15539             Result_Entity := Entity (Result);
15540          end if;
15541
15542          --  See if this level of derivation actually has discriminants
15543          --  because tagged derivations can add them, hence the lower
15544          --  levels need not have any.
15545
15546          if not Has_Discriminants (Ti) then
15547             return Result;
15548          end if;
15549
15550          --  Scan Ti's discriminants for Result_Entity,
15551          --  and return its corresponding value, if any.
15552
15553          Result_Entity := Original_Record_Component (Result_Entity);
15554
15555          Assoc := First_Elmt (Discrim_Values);
15556
15557          if Stored_Discrim_Values then
15558             Disc := First_Stored_Discriminant (Ti);
15559          else
15560             Disc := First_Discriminant (Ti);
15561          end if;
15562
15563          while Present (Disc) loop
15564             pragma Assert (Present (Assoc));
15565
15566             if Original_Record_Component (Disc) = Result_Entity then
15567                return Node (Assoc);
15568             end if;
15569
15570             Next_Elmt (Assoc);
15571
15572             if Stored_Discrim_Values then
15573                Next_Stored_Discriminant (Disc);
15574             else
15575                Next_Discriminant (Disc);
15576             end if;
15577          end loop;
15578
15579          --  Could not find it
15580          --
15581          return Result;
15582       end Search_Derivation_Levels;
15583
15584       --  Local Variables
15585
15586       Result : Node_Or_Entity_Id;
15587
15588    --  Start of processing for Get_Discriminant_Value
15589
15590    begin
15591       --  ??? This routine is a gigantic mess and will be deleted. For the
15592       --  time being just test for the trivial case before calling recurse.
15593
15594       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
15595          declare
15596             D : Entity_Id;
15597             E : Elmt_Id;
15598
15599          begin
15600             D := First_Discriminant (Typ_For_Constraint);
15601             E := First_Elmt (Constraint);
15602             while Present (D) loop
15603                if Chars (D) = Chars (Discriminant) then
15604                   return Node (E);
15605                end if;
15606
15607                Next_Discriminant (D);
15608                Next_Elmt (E);
15609             end loop;
15610          end;
15611       end if;
15612
15613       Result := Search_Derivation_Levels
15614         (Typ_For_Constraint, Constraint, False);
15615
15616       --  ??? hack to disappear when this routine is gone
15617
15618       if  Nkind (Result) = N_Defining_Identifier then
15619          declare
15620             D : Entity_Id;
15621             E : Elmt_Id;
15622
15623          begin
15624             D := First_Discriminant (Typ_For_Constraint);
15625             E := First_Elmt (Constraint);
15626             while Present (D) loop
15627                if Corresponding_Discriminant (D) = Discriminant then
15628                   return Node (E);
15629                end if;
15630
15631                Next_Discriminant (D);
15632                Next_Elmt (E);
15633             end loop;
15634          end;
15635       end if;
15636
15637       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
15638       return Result;
15639    end Get_Discriminant_Value;
15640
15641    --------------------------
15642    -- Has_Range_Constraint --
15643    --------------------------
15644
15645    function Has_Range_Constraint (N : Node_Id) return Boolean is
15646       C : constant Node_Id := Constraint (N);
15647
15648    begin
15649       if Nkind (C) = N_Range_Constraint then
15650          return True;
15651
15652       elsif Nkind (C) = N_Digits_Constraint then
15653          return
15654             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
15655               or else
15656             Present (Range_Constraint (C));
15657
15658       elsif Nkind (C) = N_Delta_Constraint then
15659          return Present (Range_Constraint (C));
15660
15661       else
15662          return False;
15663       end if;
15664    end Has_Range_Constraint;
15665
15666    ------------------------
15667    -- Inherit_Components --
15668    ------------------------
15669
15670    function Inherit_Components
15671      (N             : Node_Id;
15672       Parent_Base   : Entity_Id;
15673       Derived_Base  : Entity_Id;
15674       Is_Tagged     : Boolean;
15675       Inherit_Discr : Boolean;
15676       Discs         : Elist_Id) return Elist_Id
15677    is
15678       Assoc_List : constant Elist_Id := New_Elmt_List;
15679
15680       procedure Inherit_Component
15681         (Old_C          : Entity_Id;
15682          Plain_Discrim  : Boolean := False;
15683          Stored_Discrim : Boolean := False);
15684       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
15685       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
15686       --  True, Old_C is a stored discriminant. If they are both false then
15687       --  Old_C is a regular component.
15688
15689       -----------------------
15690       -- Inherit_Component --
15691       -----------------------
15692
15693       procedure Inherit_Component
15694         (Old_C          : Entity_Id;
15695          Plain_Discrim  : Boolean := False;
15696          Stored_Discrim : Boolean := False)
15697       is
15698          procedure Set_Anonymous_Type (Id : Entity_Id);
15699          --  Id denotes the entity of an access discriminant or anonymous
15700          --  access component. Set the type of Id to either the same type of
15701          --  Old_C or create a new one depending on whether the parent and
15702          --  the child types are in the same scope.
15703
15704          ------------------------
15705          -- Set_Anonymous_Type --
15706          ------------------------
15707
15708          procedure Set_Anonymous_Type (Id : Entity_Id) is
15709             Old_Typ : constant Entity_Id := Etype (Old_C);
15710
15711          begin
15712             if Scope (Parent_Base) = Scope (Derived_Base) then
15713                Set_Etype (Id, Old_Typ);
15714
15715             --  The parent and the derived type are in two different scopes.
15716             --  Reuse the type of the original discriminant / component by
15717             --  copying it in order to preserve all attributes.
15718
15719             else
15720                declare
15721                   Typ : constant Entity_Id := New_Copy (Old_Typ);
15722
15723                begin
15724                   Set_Etype (Id, Typ);
15725
15726                   --  Since we do not generate component declarations for
15727                   --  inherited components, associate the itype with the
15728                   --  derived type.
15729
15730                   Set_Associated_Node_For_Itype (Typ, Parent (Derived_Base));
15731                   Set_Scope                     (Typ, Derived_Base);
15732                end;
15733             end if;
15734          end Set_Anonymous_Type;
15735
15736          --  Local variables and constants
15737
15738          New_C : constant Entity_Id := New_Copy (Old_C);
15739
15740          Corr_Discrim : Entity_Id;
15741          Discrim      : Entity_Id;
15742
15743       --  Start of processing for Inherit_Component
15744
15745       begin
15746          pragma Assert (not Is_Tagged or else not Stored_Discrim);
15747
15748          Set_Parent (New_C, Parent (Old_C));
15749
15750          --  Regular discriminants and components must be inserted in the scope
15751          --  of the Derived_Base. Do it here.
15752
15753          if not Stored_Discrim then
15754             Enter_Name (New_C);
15755          end if;
15756
15757          --  For tagged types the Original_Record_Component must point to
15758          --  whatever this field was pointing to in the parent type. This has
15759          --  already been achieved by the call to New_Copy above.
15760
15761          if not Is_Tagged then
15762             Set_Original_Record_Component (New_C, New_C);
15763          end if;
15764
15765          --  Set the proper type of an access discriminant
15766
15767          if Ekind (New_C) = E_Discriminant
15768            and then Ekind (Etype (New_C)) = E_Anonymous_Access_Type
15769          then
15770             Set_Anonymous_Type (New_C);
15771          end if;
15772
15773          --  If we have inherited a component then see if its Etype contains
15774          --  references to Parent_Base discriminants. In this case, replace
15775          --  these references with the constraints given in Discs. We do not
15776          --  do this for the partial view of private types because this is
15777          --  not needed (only the components of the full view will be used
15778          --  for code generation) and cause problem. We also avoid this
15779          --  transformation in some error situations.
15780
15781          if Ekind (New_C) = E_Component then
15782
15783             --  Set the proper type of an anonymous access component
15784
15785             if Ekind (Etype (New_C)) = E_Anonymous_Access_Type then
15786                Set_Anonymous_Type (New_C);
15787
15788             elsif (Is_Private_Type (Derived_Base)
15789                     and then not Is_Generic_Type (Derived_Base))
15790               or else (Is_Empty_Elmt_List (Discs)
15791                          and then not Expander_Active)
15792             then
15793                Set_Etype (New_C, Etype (Old_C));
15794
15795             else
15796                --  The current component introduces a circularity of the
15797                --  following kind:
15798
15799                --     limited with Pack_2;
15800                --     package Pack_1 is
15801                --        type T_1 is tagged record
15802                --           Comp : access Pack_2.T_2;
15803                --           ...
15804                --        end record;
15805                --     end Pack_1;
15806
15807                --     with Pack_1;
15808                --     package Pack_2 is
15809                --        type T_2 is new Pack_1.T_1 with ...;
15810                --     end Pack_2;
15811
15812                Set_Etype
15813                  (New_C,
15814                   Constrain_Component_Type
15815                     (Old_C, Derived_Base, N, Parent_Base, Discs));
15816             end if;
15817          end if;
15818
15819          --  In derived tagged types it is illegal to reference a non
15820          --  discriminant component in the parent type. To catch this, mark
15821          --  these components with an Ekind of E_Void. This will be reset in
15822          --  Record_Type_Definition after processing the record extension of
15823          --  the derived type.
15824
15825          --  If the declaration is a private extension, there is no further
15826          --  record extension to process, and the components retain their
15827          --  current kind, because they are visible at this point.
15828
15829          if Is_Tagged and then Ekind (New_C) = E_Component
15830            and then Nkind (N) /= N_Private_Extension_Declaration
15831          then
15832             Set_Ekind (New_C, E_Void);
15833          end if;
15834
15835          if Plain_Discrim then
15836             Set_Corresponding_Discriminant (New_C, Old_C);
15837             Build_Discriminal (New_C);
15838
15839          --  If we are explicitly inheriting a stored discriminant it will be
15840          --  completely hidden.
15841
15842          elsif Stored_Discrim then
15843             Set_Corresponding_Discriminant (New_C, Empty);
15844             Set_Discriminal (New_C, Empty);
15845             Set_Is_Completely_Hidden (New_C);
15846
15847             --  Set the Original_Record_Component of each discriminant in the
15848             --  derived base to point to the corresponding stored that we just
15849             --  created.
15850
15851             Discrim := First_Discriminant (Derived_Base);
15852             while Present (Discrim) loop
15853                Corr_Discrim := Corresponding_Discriminant (Discrim);
15854
15855                --  Corr_Discrim could be missing in an error situation
15856
15857                if Present (Corr_Discrim)
15858                  and then Original_Record_Component (Corr_Discrim) = Old_C
15859                then
15860                   Set_Original_Record_Component (Discrim, New_C);
15861                end if;
15862
15863                Next_Discriminant (Discrim);
15864             end loop;
15865
15866             Append_Entity (New_C, Derived_Base);
15867          end if;
15868
15869          if not Is_Tagged then
15870             Append_Elmt (Old_C, Assoc_List);
15871             Append_Elmt (New_C, Assoc_List);
15872          end if;
15873       end Inherit_Component;
15874
15875       --  Variables local to Inherit_Component
15876
15877       Loc : constant Source_Ptr := Sloc (N);
15878
15879       Parent_Discrim : Entity_Id;
15880       Stored_Discrim : Entity_Id;
15881       D              : Entity_Id;
15882       Component      : Entity_Id;
15883
15884    --  Start of processing for Inherit_Components
15885
15886    begin
15887       if not Is_Tagged then
15888          Append_Elmt (Parent_Base,  Assoc_List);
15889          Append_Elmt (Derived_Base, Assoc_List);
15890       end if;
15891
15892       --  Inherit parent discriminants if needed
15893
15894       if Inherit_Discr then
15895          Parent_Discrim := First_Discriminant (Parent_Base);
15896          while Present (Parent_Discrim) loop
15897             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
15898             Next_Discriminant (Parent_Discrim);
15899          end loop;
15900       end if;
15901
15902       --  Create explicit stored discrims for untagged types when necessary
15903
15904       if not Has_Unknown_Discriminants (Derived_Base)
15905         and then Has_Discriminants (Parent_Base)
15906         and then not Is_Tagged
15907         and then
15908           (not Inherit_Discr
15909              or else First_Discriminant (Parent_Base) /=
15910                      First_Stored_Discriminant (Parent_Base))
15911       then
15912          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
15913          while Present (Stored_Discrim) loop
15914             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
15915             Next_Stored_Discriminant (Stored_Discrim);
15916          end loop;
15917       end if;
15918
15919       --  See if we can apply the second transformation for derived types, as
15920       --  explained in point 6. in the comments above Build_Derived_Record_Type
15921       --  This is achieved by appending Derived_Base discriminants into Discs,
15922       --  which has the side effect of returning a non empty Discs list to the
15923       --  caller of Inherit_Components, which is what we want. This must be
15924       --  done for private derived types if there are explicit stored
15925       --  discriminants, to ensure that we can retrieve the values of the
15926       --  constraints provided in the ancestors.
15927
15928       if Inherit_Discr
15929         and then Is_Empty_Elmt_List (Discs)
15930         and then Present (First_Discriminant (Derived_Base))
15931         and then
15932           (not Is_Private_Type (Derived_Base)
15933              or else Is_Completely_Hidden
15934                (First_Stored_Discriminant (Derived_Base))
15935              or else Is_Generic_Type (Derived_Base))
15936       then
15937          D := First_Discriminant (Derived_Base);
15938          while Present (D) loop
15939             Append_Elmt (New_Reference_To (D, Loc), Discs);
15940             Next_Discriminant (D);
15941          end loop;
15942       end if;
15943
15944       --  Finally, inherit non-discriminant components unless they are not
15945       --  visible because defined or inherited from the full view of the
15946       --  parent. Don't inherit the _parent field of the parent type.
15947
15948       Component := First_Entity (Parent_Base);
15949       while Present (Component) loop
15950
15951          --  Ada 2005 (AI-251): Do not inherit components associated with
15952          --  secondary tags of the parent.
15953
15954          if Ekind (Component) = E_Component
15955            and then Present (Related_Type (Component))
15956          then
15957             null;
15958
15959          elsif Ekind (Component) /= E_Component
15960            or else Chars (Component) = Name_uParent
15961          then
15962             null;
15963
15964          --  If the derived type is within the parent type's declarative
15965          --  region, then the components can still be inherited even though
15966          --  they aren't visible at this point. This can occur for cases
15967          --  such as within public child units where the components must
15968          --  become visible upon entering the child unit's private part.
15969
15970          elsif not Is_Visible_Component (Component)
15971            and then not In_Open_Scopes (Scope (Parent_Base))
15972          then
15973             null;
15974
15975          elsif Ekind_In (Derived_Base, E_Private_Type,
15976                                        E_Limited_Private_Type)
15977          then
15978             null;
15979
15980          else
15981             Inherit_Component (Component);
15982          end if;
15983
15984          Next_Entity (Component);
15985       end loop;
15986
15987       --  For tagged derived types, inherited discriminants cannot be used in
15988       --  component declarations of the record extension part. To achieve this
15989       --  we mark the inherited discriminants as not visible.
15990
15991       if Is_Tagged and then Inherit_Discr then
15992          D := First_Discriminant (Derived_Base);
15993          while Present (D) loop
15994             Set_Is_Immediately_Visible (D, False);
15995             Next_Discriminant (D);
15996          end loop;
15997       end if;
15998
15999       return Assoc_List;
16000    end Inherit_Components;
16001
16002    -----------------------
16003    -- Is_Constant_Bound --
16004    -----------------------
16005
16006    function Is_Constant_Bound (Exp : Node_Id) return Boolean is
16007    begin
16008       if Compile_Time_Known_Value (Exp) then
16009          return True;
16010
16011       elsif Is_Entity_Name (Exp)
16012         and then Present (Entity (Exp))
16013       then
16014          return Is_Constant_Object (Entity (Exp))
16015            or else Ekind (Entity (Exp)) = E_Enumeration_Literal;
16016
16017       elsif Nkind (Exp) in N_Binary_Op then
16018          return Is_Constant_Bound (Left_Opnd (Exp))
16019            and then Is_Constant_Bound (Right_Opnd (Exp))
16020            and then Scope (Entity (Exp)) = Standard_Standard;
16021
16022       else
16023          return False;
16024       end if;
16025    end Is_Constant_Bound;
16026
16027    -----------------------
16028    -- Is_Null_Extension --
16029    -----------------------
16030
16031    function Is_Null_Extension (T : Entity_Id) return Boolean is
16032       Type_Decl : constant Node_Id := Parent (Base_Type (T));
16033       Comp_List : Node_Id;
16034       Comp      : Node_Id;
16035
16036    begin
16037       if Nkind (Type_Decl) /= N_Full_Type_Declaration
16038         or else not Is_Tagged_Type (T)
16039         or else Nkind (Type_Definition (Type_Decl)) /=
16040                                               N_Derived_Type_Definition
16041         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
16042       then
16043          return False;
16044       end if;
16045
16046       Comp_List :=
16047         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
16048
16049       if Present (Discriminant_Specifications (Type_Decl)) then
16050          return False;
16051
16052       elsif Present (Comp_List)
16053         and then Is_Non_Empty_List (Component_Items (Comp_List))
16054       then
16055          Comp := First (Component_Items (Comp_List));
16056
16057          --  Only user-defined components are relevant. The component list
16058          --  may also contain a parent component and internal components
16059          --  corresponding to secondary tags, but these do not determine
16060          --  whether this is a null extension.
16061
16062          while Present (Comp) loop
16063             if Comes_From_Source (Comp) then
16064                return False;
16065             end if;
16066
16067             Next (Comp);
16068          end loop;
16069
16070          return True;
16071       else
16072          return True;
16073       end if;
16074    end Is_Null_Extension;
16075
16076    ------------------------------
16077    -- Is_Valid_Constraint_Kind --
16078    ------------------------------
16079
16080    function Is_Valid_Constraint_Kind
16081      (T_Kind          : Type_Kind;
16082       Constraint_Kind : Node_Kind) return Boolean
16083    is
16084    begin
16085       case T_Kind is
16086          when Enumeration_Kind |
16087               Integer_Kind =>
16088             return Constraint_Kind = N_Range_Constraint;
16089
16090          when Decimal_Fixed_Point_Kind =>
16091             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
16092                                               N_Range_Constraint);
16093
16094          when Ordinary_Fixed_Point_Kind =>
16095             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
16096                                               N_Range_Constraint);
16097
16098          when Float_Kind =>
16099             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
16100                                               N_Range_Constraint);
16101
16102          when Access_Kind       |
16103               Array_Kind        |
16104               E_Record_Type     |
16105               E_Record_Subtype  |
16106               Class_Wide_Kind   |
16107               E_Incomplete_Type |
16108               Private_Kind      |
16109               Concurrent_Kind  =>
16110             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
16111
16112          when others =>
16113             return True; -- Error will be detected later
16114       end case;
16115    end Is_Valid_Constraint_Kind;
16116
16117    --------------------------
16118    -- Is_Visible_Component --
16119    --------------------------
16120
16121    function Is_Visible_Component (C : Entity_Id) return Boolean is
16122       Original_Comp  : Entity_Id := Empty;
16123       Original_Scope : Entity_Id;
16124       Type_Scope     : Entity_Id;
16125
16126       function Is_Local_Type (Typ : Entity_Id) return Boolean;
16127       --  Check whether parent type of inherited component is declared locally,
16128       --  possibly within a nested package or instance. The current scope is
16129       --  the derived record itself.
16130
16131       -------------------
16132       -- Is_Local_Type --
16133       -------------------
16134
16135       function Is_Local_Type (Typ : Entity_Id) return Boolean is
16136          Scop : Entity_Id;
16137
16138       begin
16139          Scop := Scope (Typ);
16140          while Present (Scop)
16141            and then Scop /= Standard_Standard
16142          loop
16143             if Scop = Scope (Current_Scope) then
16144                return True;
16145             end if;
16146
16147             Scop := Scope (Scop);
16148          end loop;
16149
16150          return False;
16151       end Is_Local_Type;
16152
16153    --  Start of processing for Is_Visible_Component
16154
16155    begin
16156       if Ekind_In (C, E_Component, E_Discriminant) then
16157          Original_Comp := Original_Record_Component (C);
16158       end if;
16159
16160       if No (Original_Comp) then
16161
16162          --  Premature usage, or previous error
16163
16164          return False;
16165
16166       else
16167          Original_Scope := Scope (Original_Comp);
16168          Type_Scope     := Scope (Base_Type (Scope (C)));
16169       end if;
16170
16171       --  This test only concerns tagged types
16172
16173       if not Is_Tagged_Type (Original_Scope) then
16174          return True;
16175
16176       --  If it is _Parent or _Tag, there is no visibility issue
16177
16178       elsif not Comes_From_Source (Original_Comp) then
16179          return True;
16180
16181       --  Discriminants are always visible
16182
16183       elsif Ekind (Original_Comp) = E_Discriminant
16184         and then not Has_Unknown_Discriminants (Original_Scope)
16185       then
16186          return True;
16187
16188       --  If we are in the body of an instantiation, the component is visible
16189       --  if the parent type is non-private, or in  an enclosing scope. The
16190       --  scope stack is not present when analyzing an instance body, so we
16191       --  must inspect the chain of scopes explicitly.
16192
16193       elsif In_Instance_Body then
16194          if not Is_Private_Type (Scope (C)) then
16195             return True;
16196
16197          else
16198             declare
16199                S : Entity_Id;
16200
16201             begin
16202                S := Current_Scope;
16203                while Present (S)
16204                  and then S /= Standard_Standard
16205                loop
16206                   if S = Type_Scope then
16207                      return True;
16208                   end if;
16209
16210                   S := Scope (S);
16211                end loop;
16212
16213                return False;
16214             end;
16215          end if;
16216
16217       --  If the component has been declared in an ancestor which is currently
16218       --  a private type, then it is not visible. The same applies if the
16219       --  component's containing type is not in an open scope and the original
16220       --  component's enclosing type is a visible full view of a private type
16221       --  (which can occur in cases where an attempt is being made to reference
16222       --  a component in a sibling package that is inherited from a visible
16223       --  component of a type in an ancestor package; the component in the
16224       --  sibling package should not be visible even though the component it
16225       --  inherited from is visible). This does not apply however in the case
16226       --  where the scope of the type is a private child unit, or when the
16227       --  parent comes from a local package in which the ancestor is currently
16228       --  visible. The latter suppression of visibility is needed for cases
16229       --  that are tested in B730006.
16230
16231       elsif Is_Private_Type (Original_Scope)
16232         or else
16233           (not Is_Private_Descendant (Type_Scope)
16234             and then not In_Open_Scopes (Type_Scope)
16235             and then Has_Private_Declaration (Original_Scope))
16236       then
16237          --  If the type derives from an entity in a formal package, there
16238          --  are no additional visible components.
16239
16240          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
16241             N_Formal_Package_Declaration
16242          then
16243             return False;
16244
16245          --  if we are not in the private part of the current package, there
16246          --  are no additional visible components.
16247
16248          elsif Ekind (Scope (Current_Scope)) = E_Package
16249            and then not In_Private_Part (Scope (Current_Scope))
16250          then
16251             return False;
16252          else
16253             return
16254               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
16255                 and then In_Open_Scopes (Scope (Original_Scope))
16256                 and then Is_Local_Type (Type_Scope);
16257          end if;
16258
16259       --  There is another weird way in which a component may be invisible
16260       --  when the private and the full view are not derived from the same
16261       --  ancestor. Here is an example :
16262
16263       --       type A1 is tagged      record F1 : integer; end record;
16264       --       type A2 is new A1 with record F2 : integer; end record;
16265       --       type T is new A1 with private;
16266       --     private
16267       --       type T is new A2 with null record;
16268
16269       --  In this case, the full view of T inherits F1 and F2 but the private
16270       --  view inherits only F1
16271
16272       else
16273          declare
16274             Ancestor : Entity_Id := Scope (C);
16275
16276          begin
16277             loop
16278                if Ancestor = Original_Scope then
16279                   return True;
16280                elsif Ancestor = Etype (Ancestor) then
16281                   return False;
16282                end if;
16283
16284                Ancestor := Etype (Ancestor);
16285             end loop;
16286          end;
16287       end if;
16288    end Is_Visible_Component;
16289
16290    --------------------------
16291    -- Make_Class_Wide_Type --
16292    --------------------------
16293
16294    procedure Make_Class_Wide_Type (T : Entity_Id) is
16295       CW_Type : Entity_Id;
16296       CW_Name : Name_Id;
16297       Next_E  : Entity_Id;
16298
16299    begin
16300       if Present (Class_Wide_Type (T)) then
16301
16302          --  The class-wide type is a partially decorated entity created for a
16303          --  unanalyzed tagged type referenced through a limited with clause.
16304          --  When the tagged type is analyzed, its class-wide type needs to be
16305          --  redecorated. Note that we reuse the entity created by Decorate_
16306          --  Tagged_Type in order to preserve all links.
16307
16308          if Materialize_Entity (Class_Wide_Type (T)) then
16309             CW_Type := Class_Wide_Type (T);
16310             Set_Materialize_Entity (CW_Type, False);
16311
16312          --  The class wide type can have been defined by the partial view, in
16313          --  which case everything is already done.
16314
16315          else
16316             return;
16317          end if;
16318
16319       --  Default case, we need to create a new class-wide type
16320
16321       else
16322          CW_Type :=
16323            New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
16324       end if;
16325
16326       --  Inherit root type characteristics
16327
16328       CW_Name := Chars (CW_Type);
16329       Next_E  := Next_Entity (CW_Type);
16330       Copy_Node (T, CW_Type);
16331       Set_Comes_From_Source (CW_Type, False);
16332       Set_Chars (CW_Type, CW_Name);
16333       Set_Parent (CW_Type, Parent (T));
16334       Set_Next_Entity (CW_Type, Next_E);
16335
16336       --  Ensure we have a new freeze node for the class-wide type. The partial
16337       --  view may have freeze action of its own, requiring a proper freeze
16338       --  node, and the same freeze node cannot be shared between the two
16339       --  types.
16340
16341       Set_Has_Delayed_Freeze (CW_Type);
16342       Set_Freeze_Node (CW_Type, Empty);
16343
16344       --  Customize the class-wide type: It has no prim. op., it cannot be
16345       --  abstract and its Etype points back to the specific root type.
16346
16347       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
16348       Set_Is_Tagged_Type              (CW_Type, True);
16349       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
16350       Set_Is_Abstract_Type            (CW_Type, False);
16351       Set_Is_Constrained              (CW_Type, False);
16352       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
16353
16354       if Ekind (T) = E_Class_Wide_Subtype then
16355          Set_Etype             (CW_Type, Etype (Base_Type (T)));
16356       else
16357          Set_Etype             (CW_Type, T);
16358       end if;
16359
16360       --  If this is the class_wide type of a constrained subtype, it does
16361       --  not have discriminants.
16362
16363       Set_Has_Discriminants (CW_Type,
16364         Has_Discriminants (T) and then not Is_Constrained (T));
16365
16366       Set_Has_Unknown_Discriminants (CW_Type, True);
16367       Set_Class_Wide_Type (T, CW_Type);
16368       Set_Equivalent_Type (CW_Type, Empty);
16369
16370       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
16371
16372       Set_Class_Wide_Type (CW_Type, CW_Type);
16373    end Make_Class_Wide_Type;
16374
16375    ----------------
16376    -- Make_Index --
16377    ----------------
16378
16379    procedure Make_Index
16380      (I            : Node_Id;
16381       Related_Nod  : Node_Id;
16382       Related_Id   : Entity_Id := Empty;
16383       Suffix_Index : Nat := 1;
16384       In_Iter_Schm : Boolean := False)
16385    is
16386       R      : Node_Id;
16387       T      : Entity_Id;
16388       Def_Id : Entity_Id := Empty;
16389       Found  : Boolean := False;
16390
16391    begin
16392       --  For a discrete range used in a constrained array definition and
16393       --  defined by a range, an implicit conversion to the predefined type
16394       --  INTEGER is assumed if each bound is either a numeric literal, a named
16395       --  number, or an attribute, and the type of both bounds (prior to the
16396       --  implicit conversion) is the type universal_integer. Otherwise, both
16397       --  bounds must be of the same discrete type, other than universal
16398       --  integer; this type must be determinable independently of the
16399       --  context, but using the fact that the type must be discrete and that
16400       --  both bounds must have the same type.
16401
16402       --  Character literals also have a universal type in the absence of
16403       --  of additional context,  and are resolved to Standard_Character.
16404
16405       if Nkind (I) = N_Range then
16406
16407          --  The index is given by a range constraint. The bounds are known
16408          --  to be of a consistent type.
16409
16410          if not Is_Overloaded (I) then
16411             T := Etype (I);
16412
16413             --  For universal bounds, choose the specific predefined type
16414
16415             if T = Universal_Integer then
16416                T := Standard_Integer;
16417
16418             elsif T = Any_Character then
16419                Ambiguous_Character (Low_Bound (I));
16420
16421                T := Standard_Character;
16422             end if;
16423
16424          --  The node may be overloaded because some user-defined operators
16425          --  are available, but if a universal interpretation exists it is
16426          --  also the selected one.
16427
16428          elsif Universal_Interpretation (I) = Universal_Integer then
16429             T := Standard_Integer;
16430
16431          else
16432             T := Any_Type;
16433
16434             declare
16435                Ind : Interp_Index;
16436                It  : Interp;
16437
16438             begin
16439                Get_First_Interp (I, Ind, It);
16440                while Present (It.Typ) loop
16441                   if Is_Discrete_Type (It.Typ) then
16442
16443                      if Found
16444                        and then not Covers (It.Typ, T)
16445                        and then not Covers (T, It.Typ)
16446                      then
16447                         Error_Msg_N ("ambiguous bounds in discrete range", I);
16448                         exit;
16449                      else
16450                         T := It.Typ;
16451                         Found := True;
16452                      end if;
16453                   end if;
16454
16455                   Get_Next_Interp (Ind, It);
16456                end loop;
16457
16458                if T = Any_Type then
16459                   Error_Msg_N ("discrete type required for range", I);
16460                   Set_Etype (I, Any_Type);
16461                   return;
16462
16463                elsif T = Universal_Integer then
16464                   T := Standard_Integer;
16465                end if;
16466             end;
16467          end if;
16468
16469          if not Is_Discrete_Type (T) then
16470             Error_Msg_N ("discrete type required for range", I);
16471             Set_Etype (I, Any_Type);
16472             return;
16473          end if;
16474
16475          if Nkind (Low_Bound (I)) = N_Attribute_Reference
16476            and then Attribute_Name (Low_Bound (I)) = Name_First
16477            and then Is_Entity_Name (Prefix (Low_Bound (I)))
16478            and then Is_Type (Entity (Prefix (Low_Bound (I))))
16479            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
16480          then
16481             --  The type of the index will be the type of the prefix, as long
16482             --  as the upper bound is 'Last of the same type.
16483
16484             Def_Id := Entity (Prefix (Low_Bound (I)));
16485
16486             if Nkind (High_Bound (I)) /= N_Attribute_Reference
16487               or else Attribute_Name (High_Bound (I)) /= Name_Last
16488               or else not Is_Entity_Name (Prefix (High_Bound (I)))
16489               or else Entity (Prefix (High_Bound (I))) /= Def_Id
16490             then
16491                Def_Id := Empty;
16492             end if;
16493          end if;
16494
16495          R := I;
16496          Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
16497
16498       elsif Nkind (I) = N_Subtype_Indication then
16499
16500          --  The index is given by a subtype with a range constraint
16501
16502          T :=  Base_Type (Entity (Subtype_Mark (I)));
16503
16504          if not Is_Discrete_Type (T) then
16505             Error_Msg_N ("discrete type required for range", I);
16506             Set_Etype (I, Any_Type);
16507             return;
16508          end if;
16509
16510          R := Range_Expression (Constraint (I));
16511
16512          Resolve (R, T);
16513          Process_Range_Expr_In_Decl
16514            (R, Entity (Subtype_Mark (I)), In_Iter_Schm => In_Iter_Schm);
16515
16516       elsif Nkind (I) = N_Attribute_Reference then
16517
16518          --  The parser guarantees that the attribute is a RANGE attribute
16519
16520          --  If the node denotes the range of a type mark, that is also the
16521          --  resulting type, and we do no need to create an Itype for it.
16522
16523          if Is_Entity_Name (Prefix (I))
16524            and then Comes_From_Source (I)
16525            and then Is_Type (Entity (Prefix (I)))
16526            and then Is_Discrete_Type (Entity (Prefix (I)))
16527          then
16528             Def_Id := Entity (Prefix (I));
16529          end if;
16530
16531          Analyze_And_Resolve (I);
16532          T := Etype (I);
16533          R := I;
16534
16535       --  If none of the above, must be a subtype. We convert this to a
16536       --  range attribute reference because in the case of declared first
16537       --  named subtypes, the types in the range reference can be different
16538       --  from the type of the entity. A range attribute normalizes the
16539       --  reference and obtains the correct types for the bounds.
16540
16541       --  This transformation is in the nature of an expansion, is only
16542       --  done if expansion is active. In particular, it is not done on
16543       --  formal generic types,  because we need to retain the name of the
16544       --  original index for instantiation purposes.
16545
16546       else
16547          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
16548             Error_Msg_N ("invalid subtype mark in discrete range ", I);
16549             Set_Etype (I, Any_Integer);
16550             return;
16551
16552          else
16553             --  The type mark may be that of an incomplete type. It is only
16554             --  now that we can get the full view, previous analysis does
16555             --  not look specifically for a type mark.
16556
16557             Set_Entity (I, Get_Full_View (Entity (I)));
16558             Set_Etype  (I, Entity (I));
16559             Def_Id := Entity (I);
16560
16561             if not Is_Discrete_Type (Def_Id) then
16562                Error_Msg_N ("discrete type required for index", I);
16563                Set_Etype (I, Any_Type);
16564                return;
16565             end if;
16566          end if;
16567
16568          if Expander_Active then
16569             Rewrite (I,
16570               Make_Attribute_Reference (Sloc (I),
16571                 Attribute_Name => Name_Range,
16572                 Prefix         => Relocate_Node (I)));
16573
16574             --  The original was a subtype mark that does not freeze. This
16575             --  means that the rewritten version must not freeze either.
16576
16577             Set_Must_Not_Freeze (I);
16578             Set_Must_Not_Freeze (Prefix (I));
16579
16580             --  Is order critical??? if so, document why, if not
16581             --  use Analyze_And_Resolve
16582
16583             Analyze_And_Resolve (I);
16584             T := Etype (I);
16585             R := I;
16586
16587          --  If expander is inactive, type is legal, nothing else to construct
16588
16589          else
16590             return;
16591          end if;
16592       end if;
16593
16594       if not Is_Discrete_Type (T) then
16595          Error_Msg_N ("discrete type required for range", I);
16596          Set_Etype (I, Any_Type);
16597          return;
16598
16599       elsif T = Any_Type then
16600          Set_Etype (I, Any_Type);
16601          return;
16602       end if;
16603
16604       --  We will now create the appropriate Itype to describe the range, but
16605       --  first a check. If we originally had a subtype, then we just label
16606       --  the range with this subtype. Not only is there no need to construct
16607       --  a new subtype, but it is wrong to do so for two reasons:
16608
16609       --    1. A legality concern, if we have a subtype, it must not freeze,
16610       --       and the Itype would cause freezing incorrectly
16611
16612       --    2. An efficiency concern, if we created an Itype, it would not be
16613       --       recognized as the same type for the purposes of eliminating
16614       --       checks in some circumstances.
16615
16616       --  We signal this case by setting the subtype entity in Def_Id
16617
16618       if No (Def_Id) then
16619          Def_Id :=
16620            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
16621          Set_Etype (Def_Id, Base_Type (T));
16622
16623          if Is_Signed_Integer_Type (T) then
16624             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
16625
16626          elsif Is_Modular_Integer_Type (T) then
16627             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
16628
16629          else
16630             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
16631             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
16632             Set_First_Literal     (Def_Id, First_Literal (T));
16633          end if;
16634
16635          Set_Size_Info      (Def_Id,                  (T));
16636          Set_RM_Size        (Def_Id, RM_Size          (T));
16637          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
16638
16639          Set_Scalar_Range   (Def_Id, R);
16640          Conditional_Delay  (Def_Id, T);
16641
16642          --  In the subtype indication case, if the immediate parent of the
16643          --  new subtype is non-static, then the subtype we create is non-
16644          --  static, even if its bounds are static.
16645
16646          if Nkind (I) = N_Subtype_Indication
16647            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
16648          then
16649             Set_Is_Non_Static_Subtype (Def_Id);
16650          end if;
16651       end if;
16652
16653       --  Final step is to label the index with this constructed type
16654
16655       Set_Etype (I, Def_Id);
16656    end Make_Index;
16657
16658    ------------------------------
16659    -- Modular_Type_Declaration --
16660    ------------------------------
16661
16662    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16663       Mod_Expr : constant Node_Id := Expression (Def);
16664       M_Val    : Uint;
16665
16666       procedure Set_Modular_Size (Bits : Int);
16667       --  Sets RM_Size to Bits, and Esize to normal word size above this
16668
16669       ----------------------
16670       -- Set_Modular_Size --
16671       ----------------------
16672
16673       procedure Set_Modular_Size (Bits : Int) is
16674       begin
16675          Set_RM_Size (T, UI_From_Int (Bits));
16676
16677          if Bits <= 8 then
16678             Init_Esize (T, 8);
16679
16680          elsif Bits <= 16 then
16681             Init_Esize (T, 16);
16682
16683          elsif Bits <= 32 then
16684             Init_Esize (T, 32);
16685
16686          else
16687             Init_Esize (T, System_Max_Binary_Modulus_Power);
16688          end if;
16689
16690          if not Non_Binary_Modulus (T)
16691            and then Esize (T) = RM_Size (T)
16692          then
16693             Set_Is_Known_Valid (T);
16694          end if;
16695       end Set_Modular_Size;
16696
16697    --  Start of processing for Modular_Type_Declaration
16698
16699    begin
16700       Analyze_And_Resolve (Mod_Expr, Any_Integer);
16701       Set_Etype (T, T);
16702       Set_Ekind (T, E_Modular_Integer_Type);
16703       Init_Alignment (T);
16704       Set_Is_Constrained (T);
16705
16706       if not Is_OK_Static_Expression (Mod_Expr) then
16707          Flag_Non_Static_Expr
16708            ("non-static expression used for modular type bound!", Mod_Expr);
16709          M_Val := 2 ** System_Max_Binary_Modulus_Power;
16710       else
16711          M_Val := Expr_Value (Mod_Expr);
16712       end if;
16713
16714       if M_Val < 1 then
16715          Error_Msg_N ("modulus value must be positive", Mod_Expr);
16716          M_Val := 2 ** System_Max_Binary_Modulus_Power;
16717       end if;
16718
16719       Set_Modulus (T, M_Val);
16720
16721       --   Create bounds for the modular type based on the modulus given in
16722       --   the type declaration and then analyze and resolve those bounds.
16723
16724       Set_Scalar_Range (T,
16725         Make_Range (Sloc (Mod_Expr),
16726           Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
16727           High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
16728
16729       --  Properly analyze the literals for the range. We do this manually
16730       --  because we can't go calling Resolve, since we are resolving these
16731       --  bounds with the type, and this type is certainly not complete yet!
16732
16733       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
16734       Set_Etype (High_Bound (Scalar_Range (T)), T);
16735       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
16736       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
16737
16738       --  Loop through powers of two to find number of bits required
16739
16740       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
16741
16742          --  Binary case
16743
16744          if M_Val = 2 ** Bits then
16745             Set_Modular_Size (Bits);
16746             return;
16747
16748          --  Non-binary case
16749
16750          elsif M_Val < 2 ** Bits then
16751             Check_SPARK_Restriction ("modulus should be a power of 2", T);
16752             Set_Non_Binary_Modulus (T);
16753
16754             if Bits > System_Max_Nonbinary_Modulus_Power then
16755                Error_Msg_Uint_1 :=
16756                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
16757                Error_Msg_F
16758                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
16759                Set_Modular_Size (System_Max_Binary_Modulus_Power);
16760                return;
16761
16762             else
16763                --  In the non-binary case, set size as per RM 13.3(55)
16764
16765                Set_Modular_Size (Bits);
16766                return;
16767             end if;
16768          end if;
16769
16770       end loop;
16771
16772       --  If we fall through, then the size exceed System.Max_Binary_Modulus
16773       --  so we just signal an error and set the maximum size.
16774
16775       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
16776       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
16777
16778       Set_Modular_Size (System_Max_Binary_Modulus_Power);
16779       Init_Alignment (T);
16780
16781    end Modular_Type_Declaration;
16782
16783    --------------------------
16784    -- New_Concatenation_Op --
16785    --------------------------
16786
16787    procedure New_Concatenation_Op (Typ : Entity_Id) is
16788       Loc : constant Source_Ptr := Sloc (Typ);
16789       Op  : Entity_Id;
16790
16791       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
16792       --  Create abbreviated declaration for the formal of a predefined
16793       --  Operator 'Op' of type 'Typ'
16794
16795       --------------------
16796       -- Make_Op_Formal --
16797       --------------------
16798
16799       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
16800          Formal : Entity_Id;
16801       begin
16802          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
16803          Set_Etype (Formal, Typ);
16804          Set_Mechanism (Formal, Default_Mechanism);
16805          return Formal;
16806       end Make_Op_Formal;
16807
16808    --  Start of processing for New_Concatenation_Op
16809
16810    begin
16811       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
16812
16813       Set_Ekind                   (Op, E_Operator);
16814       Set_Scope                   (Op, Current_Scope);
16815       Set_Etype                   (Op, Typ);
16816       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
16817       Set_Is_Immediately_Visible  (Op);
16818       Set_Is_Intrinsic_Subprogram (Op);
16819       Set_Has_Completion          (Op);
16820       Append_Entity               (Op, Current_Scope);
16821
16822       Set_Name_Entity_Id (Name_Op_Concat, Op);
16823
16824       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16825       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16826    end New_Concatenation_Op;
16827
16828    -------------------------
16829    -- OK_For_Limited_Init --
16830    -------------------------
16831
16832    --  ???Check all calls of this, and compare the conditions under which it's
16833    --  called.
16834
16835    function OK_For_Limited_Init
16836      (Typ : Entity_Id;
16837       Exp : Node_Id) return Boolean
16838    is
16839    begin
16840       return Is_CPP_Constructor_Call (Exp)
16841         or else (Ada_Version >= Ada_2005
16842                   and then not Debug_Flag_Dot_L
16843                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
16844    end OK_For_Limited_Init;
16845
16846    -------------------------------
16847    -- OK_For_Limited_Init_In_05 --
16848    -------------------------------
16849
16850    function OK_For_Limited_Init_In_05
16851      (Typ : Entity_Id;
16852       Exp : Node_Id) return Boolean
16853    is
16854    begin
16855       --  An object of a limited interface type can be initialized with any
16856       --  expression of a nonlimited descendant type.
16857
16858       if Is_Class_Wide_Type (Typ)
16859         and then Is_Limited_Interface (Typ)
16860         and then not Is_Limited_Type (Etype (Exp))
16861       then
16862          return True;
16863       end if;
16864
16865       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
16866       --  case of limited aggregates (including extension aggregates), and
16867       --  function calls. The function call may have been given in prefixed
16868       --  notation, in which case the original node is an indexed component.
16869       --  If the function is parameterless, the original node was an explicit
16870       --  dereference. The function may also be parameterless, in which case
16871       --  the source node is just an identifier.
16872
16873       case Nkind (Original_Node (Exp)) is
16874          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
16875             return True;
16876
16877          when N_Identifier =>
16878             return Present (Entity (Original_Node (Exp)))
16879               and then Ekind (Entity (Original_Node (Exp))) = E_Function;
16880
16881          when N_Qualified_Expression =>
16882             return
16883               OK_For_Limited_Init_In_05
16884                 (Typ, Expression (Original_Node (Exp)));
16885
16886          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
16887          --  with a function call, the expander has rewritten the call into an
16888          --  N_Type_Conversion node to force displacement of the pointer to
16889          --  reference the component containing the secondary dispatch table.
16890          --  Otherwise a type conversion is not a legal context.
16891          --  A return statement for a build-in-place function returning a
16892          --  synchronized type also introduces an unchecked conversion.
16893
16894          when N_Type_Conversion           |
16895               N_Unchecked_Type_Conversion =>
16896             return not Comes_From_Source (Exp)
16897               and then
16898                 OK_For_Limited_Init_In_05
16899                   (Typ, Expression (Original_Node (Exp)));
16900
16901          when N_Indexed_Component     |
16902               N_Selected_Component    |
16903               N_Explicit_Dereference  =>
16904             return Nkind (Exp) = N_Function_Call;
16905
16906          --  A use of 'Input is a function call, hence allowed. Normally the
16907          --  attribute will be changed to a call, but the attribute by itself
16908          --  can occur with -gnatc.
16909
16910          when N_Attribute_Reference =>
16911             return Attribute_Name (Original_Node (Exp)) = Name_Input;
16912
16913          --  For a conditional expression, all dependent expressions must be
16914          --  legal constructs.
16915
16916          when N_Conditional_Expression =>
16917             declare
16918                Then_Expr : constant Node_Id :=
16919                              Next (First (Expressions (Original_Node (Exp))));
16920                Else_Expr : constant Node_Id := Next (Then_Expr);
16921             begin
16922                return OK_For_Limited_Init_In_05 (Typ, Then_Expr)
16923                  and then OK_For_Limited_Init_In_05 (Typ, Else_Expr);
16924             end;
16925
16926          when N_Case_Expression =>
16927             declare
16928                Alt : Node_Id;
16929
16930             begin
16931                Alt := First (Alternatives (Original_Node (Exp)));
16932                while Present (Alt) loop
16933                   if not OK_For_Limited_Init_In_05 (Typ, Expression (Alt)) then
16934                      return False;
16935                   end if;
16936
16937                   Next (Alt);
16938                end loop;
16939
16940                return True;
16941             end;
16942
16943          when others =>
16944             return False;
16945       end case;
16946    end OK_For_Limited_Init_In_05;
16947
16948    -------------------------------------------
16949    -- Ordinary_Fixed_Point_Type_Declaration --
16950    -------------------------------------------
16951
16952    procedure Ordinary_Fixed_Point_Type_Declaration
16953      (T   : Entity_Id;
16954       Def : Node_Id)
16955    is
16956       Loc           : constant Source_Ptr := Sloc (Def);
16957       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
16958       RRS           : constant Node_Id    := Real_Range_Specification (Def);
16959       Implicit_Base : Entity_Id;
16960       Delta_Val     : Ureal;
16961       Small_Val     : Ureal;
16962       Low_Val       : Ureal;
16963       High_Val      : Ureal;
16964
16965    begin
16966       Check_Restriction (No_Fixed_Point, Def);
16967
16968       --  Create implicit base type
16969
16970       Implicit_Base :=
16971         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
16972       Set_Etype (Implicit_Base, Implicit_Base);
16973
16974       --  Analyze and process delta expression
16975
16976       Analyze_And_Resolve (Delta_Expr, Any_Real);
16977
16978       Check_Delta_Expression (Delta_Expr);
16979       Delta_Val := Expr_Value_R (Delta_Expr);
16980
16981       Set_Delta_Value (Implicit_Base, Delta_Val);
16982
16983       --  Compute default small from given delta, which is the largest power
16984       --  of two that does not exceed the given delta value.
16985
16986       declare
16987          Tmp   : Ureal;
16988          Scale : Int;
16989
16990       begin
16991          Tmp := Ureal_1;
16992          Scale := 0;
16993
16994          if Delta_Val < Ureal_1 then
16995             while Delta_Val < Tmp loop
16996                Tmp := Tmp / Ureal_2;
16997                Scale := Scale + 1;
16998             end loop;
16999
17000          else
17001             loop
17002                Tmp := Tmp * Ureal_2;
17003                exit when Tmp > Delta_Val;
17004                Scale := Scale - 1;
17005             end loop;
17006          end if;
17007
17008          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
17009       end;
17010
17011       Set_Small_Value (Implicit_Base, Small_Val);
17012
17013       --  If no range was given, set a dummy range
17014
17015       if RRS <= Empty_Or_Error then
17016          Low_Val  := -Small_Val;
17017          High_Val := Small_Val;
17018
17019       --  Otherwise analyze and process given range
17020
17021       else
17022          declare
17023             Low  : constant Node_Id := Low_Bound  (RRS);
17024             High : constant Node_Id := High_Bound (RRS);
17025
17026          begin
17027             Analyze_And_Resolve (Low, Any_Real);
17028             Analyze_And_Resolve (High, Any_Real);
17029             Check_Real_Bound (Low);
17030             Check_Real_Bound (High);
17031
17032             --  Obtain and set the range
17033
17034             Low_Val  := Expr_Value_R (Low);
17035             High_Val := Expr_Value_R (High);
17036
17037             if Low_Val > High_Val then
17038                Error_Msg_NE ("?fixed point type& has null range", Def, T);
17039             end if;
17040          end;
17041       end if;
17042
17043       --  The range for both the implicit base and the declared first subtype
17044       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
17045       --  set a temporary range in place. Note that the bounds of the base
17046       --  type will be widened to be symmetrical and to fill the available
17047       --  bits when the type is frozen.
17048
17049       --  We could do this with all discrete types, and probably should, but
17050       --  we absolutely have to do it for fixed-point, since the end-points
17051       --  of the range and the size are determined by the small value, which
17052       --  could be reset before the freeze point.
17053
17054       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
17055       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
17056
17057       --  Complete definition of first subtype
17058
17059       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
17060       Set_Etype          (T, Implicit_Base);
17061       Init_Size_Align    (T);
17062       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
17063       Set_Small_Value    (T, Small_Val);
17064       Set_Delta_Value    (T, Delta_Val);
17065       Set_Is_Constrained (T);
17066
17067    end Ordinary_Fixed_Point_Type_Declaration;
17068
17069    ----------------------------------------
17070    -- Prepare_Private_Subtype_Completion --
17071    ----------------------------------------
17072
17073    procedure Prepare_Private_Subtype_Completion
17074      (Id          : Entity_Id;
17075       Related_Nod : Node_Id)
17076    is
17077       Id_B   : constant Entity_Id := Base_Type (Id);
17078       Full_B : constant Entity_Id := Full_View (Id_B);
17079       Full   : Entity_Id;
17080
17081    begin
17082       if Present (Full_B) then
17083
17084          --  The Base_Type is already completed, we can complete the subtype
17085          --  now. We have to create a new entity with the same name, Thus we
17086          --  can't use Create_Itype.
17087
17088          --  This is messy, should be fixed ???
17089
17090          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
17091          Set_Is_Itype (Full);
17092          Set_Associated_Node_For_Itype (Full, Related_Nod);
17093          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
17094       end if;
17095
17096       --  The parent subtype may be private, but the base might not, in some
17097       --  nested instances. In that case, the subtype does not need to be
17098       --  exchanged. It would still be nice to make private subtypes and their
17099       --  bases consistent at all times ???
17100
17101       if Is_Private_Type (Id_B) then
17102          Append_Elmt (Id, Private_Dependents (Id_B));
17103       end if;
17104
17105    end Prepare_Private_Subtype_Completion;
17106
17107    ---------------------------
17108    -- Process_Discriminants --
17109    ---------------------------
17110
17111    procedure Process_Discriminants
17112      (N    : Node_Id;
17113       Prev : Entity_Id := Empty)
17114    is
17115       Elist               : constant Elist_Id := New_Elmt_List;
17116       Id                  : Node_Id;
17117       Discr               : Node_Id;
17118       Discr_Number        : Uint;
17119       Discr_Type          : Entity_Id;
17120       Default_Present     : Boolean := False;
17121       Default_Not_Present : Boolean := False;
17122
17123    begin
17124       --  A composite type other than an array type can have discriminants.
17125       --  On entry, the current scope is the composite type.
17126
17127       --  The discriminants are initially entered into the scope of the type
17128       --  via Enter_Name with the default Ekind of E_Void to prevent premature
17129       --  use, as explained at the end of this procedure.
17130
17131       Discr := First (Discriminant_Specifications (N));
17132       while Present (Discr) loop
17133          Enter_Name (Defining_Identifier (Discr));
17134
17135          --  For navigation purposes we add a reference to the discriminant
17136          --  in the entity for the type. If the current declaration is a
17137          --  completion, place references on the partial view. Otherwise the
17138          --  type is the current scope.
17139
17140          if Present (Prev) then
17141
17142             --  The references go on the partial view, if present. If the
17143             --  partial view has discriminants, the references have been
17144             --  generated already.
17145
17146             if not Has_Discriminants (Prev) then
17147                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
17148             end if;
17149          else
17150             Generate_Reference
17151               (Current_Scope, Defining_Identifier (Discr), 'd');
17152          end if;
17153
17154          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
17155             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
17156
17157             --  Ada 2005 (AI-254)
17158
17159             if Present (Access_To_Subprogram_Definition
17160                          (Discriminant_Type (Discr)))
17161               and then Protected_Present (Access_To_Subprogram_Definition
17162                                            (Discriminant_Type (Discr)))
17163             then
17164                Discr_Type :=
17165                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
17166             end if;
17167
17168          else
17169             Find_Type (Discriminant_Type (Discr));
17170             Discr_Type := Etype (Discriminant_Type (Discr));
17171
17172             if Error_Posted (Discriminant_Type (Discr)) then
17173                Discr_Type := Any_Type;
17174             end if;
17175          end if;
17176
17177          if Is_Access_Type (Discr_Type) then
17178
17179             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
17180             --  record types
17181
17182             if Ada_Version < Ada_2005 then
17183                Check_Access_Discriminant_Requires_Limited
17184                  (Discr, Discriminant_Type (Discr));
17185             end if;
17186
17187             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
17188                Error_Msg_N
17189                  ("(Ada 83) access discriminant not allowed", Discr);
17190             end if;
17191
17192          elsif not Is_Discrete_Type (Discr_Type) then
17193             Error_Msg_N ("discriminants must have a discrete or access type",
17194               Discriminant_Type (Discr));
17195          end if;
17196
17197          Set_Etype (Defining_Identifier (Discr), Discr_Type);
17198
17199          --  If a discriminant specification includes the assignment compound
17200          --  delimiter followed by an expression, the expression is the default
17201          --  expression of the discriminant; the default expression must be of
17202          --  the type of the discriminant. (RM 3.7.1) Since this expression is
17203          --  a default expression, we do the special preanalysis, since this
17204          --  expression does not freeze (see "Handling of Default and Per-
17205          --  Object Expressions" in spec of package Sem).
17206
17207          if Present (Expression (Discr)) then
17208             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
17209
17210             if Nkind (N) = N_Formal_Type_Declaration then
17211                Error_Msg_N
17212                  ("discriminant defaults not allowed for formal type",
17213                   Expression (Discr));
17214
17215             --  Flag an error for a tagged type with defaulted discriminants,
17216             --  excluding limited tagged types when compiling for Ada 2012
17217             --  (see AI05-0214).
17218
17219             elsif Is_Tagged_Type (Current_Scope)
17220               and then (not Is_Limited_Type (Current_Scope)
17221                          or else Ada_Version < Ada_2012)
17222               and then Comes_From_Source (N)
17223             then
17224                --  Note: see similar test in Check_Or_Process_Discriminants, to
17225                --  handle the (illegal) case of the completion of an untagged
17226                --  view with discriminants with defaults by a tagged full view.
17227                --  We skip the check if Discr does not come from source, to
17228                --  account for the case of an untagged derived type providing
17229                --  defaults for a renamed discriminant from a private untagged
17230                --  ancestor with a tagged full view (ACATS B460006).
17231
17232                if Ada_Version >= Ada_2012 then
17233                   Error_Msg_N
17234                     ("discriminants of nonlimited tagged type cannot have"
17235                        & " defaults",
17236                      Expression (Discr));
17237                else
17238                   Error_Msg_N
17239                     ("discriminants of tagged type cannot have defaults",
17240                      Expression (Discr));
17241                end if;
17242
17243             else
17244                Default_Present := True;
17245                Append_Elmt (Expression (Discr), Elist);
17246
17247                --  Tag the defining identifiers for the discriminants with
17248                --  their corresponding default expressions from the tree.
17249
17250                Set_Discriminant_Default_Value
17251                  (Defining_Identifier (Discr), Expression (Discr));
17252             end if;
17253
17254          else
17255             Default_Not_Present := True;
17256          end if;
17257
17258          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
17259          --  Discr_Type but with the null-exclusion attribute
17260
17261          if Ada_Version >= Ada_2005 then
17262
17263             --  Ada 2005 (AI-231): Static checks
17264
17265             if Can_Never_Be_Null (Discr_Type) then
17266                Null_Exclusion_Static_Checks (Discr);
17267
17268             elsif Is_Access_Type (Discr_Type)
17269               and then Null_Exclusion_Present (Discr)
17270
17271                --  No need to check itypes because in their case this check
17272                --  was done at their point of creation
17273
17274               and then not Is_Itype (Discr_Type)
17275             then
17276                if Can_Never_Be_Null (Discr_Type) then
17277                   Error_Msg_NE
17278                     ("`NOT NULL` not allowed (& already excludes null)",
17279                      Discr,
17280                      Discr_Type);
17281                end if;
17282
17283                Set_Etype (Defining_Identifier (Discr),
17284                  Create_Null_Excluding_Itype
17285                    (T           => Discr_Type,
17286                     Related_Nod => Discr));
17287
17288             --  Check for improper null exclusion if the type is otherwise
17289             --  legal for a discriminant.
17290
17291             elsif Null_Exclusion_Present (Discr)
17292               and then Is_Discrete_Type (Discr_Type)
17293             then
17294                Error_Msg_N
17295                  ("null exclusion can only apply to an access type", Discr);
17296             end if;
17297
17298             --  Ada 2005 (AI-402): access discriminants of nonlimited types
17299             --  can't have defaults. Synchronized types, or types that are
17300             --  explicitly limited are fine, but special tests apply to derived
17301             --  types in generics: in a generic body we have to assume the
17302             --  worst, and therefore defaults are not allowed if the parent is
17303             --  a generic formal private type (see ACATS B370001).
17304
17305             if Is_Access_Type (Discr_Type) and then Default_Present then
17306                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
17307                  or else Is_Limited_Record (Current_Scope)
17308                  or else Is_Concurrent_Type (Current_Scope)
17309                  or else Is_Concurrent_Record_Type (Current_Scope)
17310                  or else Ekind (Current_Scope) = E_Limited_Private_Type
17311                then
17312                   if not Is_Derived_Type (Current_Scope)
17313                     or else not Is_Generic_Type (Etype (Current_Scope))
17314                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
17315                     or else Limited_Present
17316                               (Type_Definition (Parent (Current_Scope)))
17317                   then
17318                      null;
17319
17320                   else
17321                      Error_Msg_N ("access discriminants of nonlimited types",
17322                          Expression (Discr));
17323                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
17324                   end if;
17325
17326                elsif Present (Expression (Discr)) then
17327                   Error_Msg_N
17328                     ("(Ada 2005) access discriminants of nonlimited types",
17329                      Expression (Discr));
17330                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
17331                end if;
17332             end if;
17333          end if;
17334
17335          Next (Discr);
17336       end loop;
17337
17338       --  An element list consisting of the default expressions of the
17339       --  discriminants is constructed in the above loop and used to set
17340       --  the Discriminant_Constraint attribute for the type. If an object
17341       --  is declared of this (record or task) type without any explicit
17342       --  discriminant constraint given, this element list will form the
17343       --  actual parameters for the corresponding initialization procedure
17344       --  for the type.
17345
17346       Set_Discriminant_Constraint (Current_Scope, Elist);
17347       Set_Stored_Constraint (Current_Scope, No_Elist);
17348
17349       --  Default expressions must be provided either for all or for none
17350       --  of the discriminants of a discriminant part. (RM 3.7.1)
17351
17352       if Default_Present and then Default_Not_Present then
17353          Error_Msg_N
17354            ("incomplete specification of defaults for discriminants", N);
17355       end if;
17356
17357       --  The use of the name of a discriminant is not allowed in default
17358       --  expressions of a discriminant part if the specification of the
17359       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
17360
17361       --  To detect this, the discriminant names are entered initially with an
17362       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
17363       --  attempt to use a void entity (for example in an expression that is
17364       --  type-checked) produces the error message: premature usage. Now after
17365       --  completing the semantic analysis of the discriminant part, we can set
17366       --  the Ekind of all the discriminants appropriately.
17367
17368       Discr := First (Discriminant_Specifications (N));
17369       Discr_Number := Uint_1;
17370       while Present (Discr) loop
17371          Id := Defining_Identifier (Discr);
17372          Set_Ekind (Id, E_Discriminant);
17373          Init_Component_Location (Id);
17374          Init_Esize (Id);
17375          Set_Discriminant_Number (Id, Discr_Number);
17376
17377          --  Make sure this is always set, even in illegal programs
17378
17379          Set_Corresponding_Discriminant (Id, Empty);
17380
17381          --  Initialize the Original_Record_Component to the entity itself.
17382          --  Inherit_Components will propagate the right value to
17383          --  discriminants in derived record types.
17384
17385          Set_Original_Record_Component (Id, Id);
17386
17387          --  Create the discriminal for the discriminant
17388
17389          Build_Discriminal (Id);
17390
17391          Next (Discr);
17392          Discr_Number := Discr_Number + 1;
17393       end loop;
17394
17395       Set_Has_Discriminants (Current_Scope);
17396    end Process_Discriminants;
17397
17398    -----------------------
17399    -- Process_Full_View --
17400    -----------------------
17401
17402    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
17403       Priv_Parent : Entity_Id;
17404       Full_Parent : Entity_Id;
17405       Full_Indic  : Node_Id;
17406
17407       procedure Collect_Implemented_Interfaces
17408         (Typ    : Entity_Id;
17409          Ifaces : Elist_Id);
17410       --  Ada 2005: Gather all the interfaces that Typ directly or
17411       --  inherently implements. Duplicate entries are not added to
17412       --  the list Ifaces.
17413
17414       ------------------------------------
17415       -- Collect_Implemented_Interfaces --
17416       ------------------------------------
17417
17418       procedure Collect_Implemented_Interfaces
17419         (Typ    : Entity_Id;
17420          Ifaces : Elist_Id)
17421       is
17422          Iface      : Entity_Id;
17423          Iface_Elmt : Elmt_Id;
17424
17425       begin
17426          --  Abstract interfaces are only associated with tagged record types
17427
17428          if not Is_Tagged_Type (Typ)
17429            or else not Is_Record_Type (Typ)
17430          then
17431             return;
17432          end if;
17433
17434          --  Recursively climb to the ancestors
17435
17436          if Etype (Typ) /= Typ
17437
17438             --  Protect the frontend against wrong cyclic declarations like:
17439
17440             --     type B is new A with private;
17441             --     type C is new A with private;
17442             --  private
17443             --     type B is new C with null record;
17444             --     type C is new B with null record;
17445
17446            and then Etype (Typ) /= Priv_T
17447            and then Etype (Typ) /= Full_T
17448          then
17449             --  Keep separate the management of private type declarations
17450
17451             if Ekind (Typ) = E_Record_Type_With_Private then
17452
17453                --  Handle the following erroneous case:
17454                --      type Private_Type is tagged private;
17455                --   private
17456                --      type Private_Type is new Type_Implementing_Iface;
17457
17458                if Present (Full_View (Typ))
17459                  and then Etype (Typ) /= Full_View (Typ)
17460                then
17461                   if Is_Interface (Etype (Typ)) then
17462                      Append_Unique_Elmt (Etype (Typ), Ifaces);
17463                   end if;
17464
17465                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
17466                end if;
17467
17468             --  Non-private types
17469
17470             else
17471                if Is_Interface (Etype (Typ)) then
17472                   Append_Unique_Elmt (Etype (Typ), Ifaces);
17473                end if;
17474
17475                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
17476             end if;
17477          end if;
17478
17479          --  Handle entities in the list of abstract interfaces
17480
17481          if Present (Interfaces (Typ)) then
17482             Iface_Elmt := First_Elmt (Interfaces (Typ));
17483             while Present (Iface_Elmt) loop
17484                Iface := Node (Iface_Elmt);
17485
17486                pragma Assert (Is_Interface (Iface));
17487
17488                if not Contain_Interface (Iface, Ifaces) then
17489                   Append_Elmt (Iface, Ifaces);
17490                   Collect_Implemented_Interfaces (Iface, Ifaces);
17491                end if;
17492
17493                Next_Elmt (Iface_Elmt);
17494             end loop;
17495          end if;
17496       end Collect_Implemented_Interfaces;
17497
17498    --  Start of processing for Process_Full_View
17499
17500    begin
17501       --  First some sanity checks that must be done after semantic
17502       --  decoration of the full view and thus cannot be placed with other
17503       --  similar checks in Find_Type_Name
17504
17505       if not Is_Limited_Type (Priv_T)
17506         and then (Is_Limited_Type (Full_T)
17507                    or else Is_Limited_Composite (Full_T))
17508       then
17509          if In_Instance then
17510             null;
17511          else
17512             Error_Msg_N
17513               ("completion of nonlimited type cannot be limited", Full_T);
17514             Explain_Limited_Type (Full_T, Full_T);
17515          end if;
17516
17517       elsif Is_Abstract_Type (Full_T)
17518         and then not Is_Abstract_Type (Priv_T)
17519       then
17520          Error_Msg_N
17521            ("completion of nonabstract type cannot be abstract", Full_T);
17522
17523       elsif Is_Tagged_Type (Priv_T)
17524         and then Is_Limited_Type (Priv_T)
17525         and then not Is_Limited_Type (Full_T)
17526       then
17527          --  If pragma CPP_Class was applied to the private declaration
17528          --  propagate the limitedness to the full-view
17529
17530          if Is_CPP_Class (Priv_T) then
17531             Set_Is_Limited_Record (Full_T);
17532
17533          --  GNAT allow its own definition of Limited_Controlled to disobey
17534          --  this rule in order in ease the implementation. This test is safe
17535          --  because Root_Controlled is defined in a child of System that
17536          --  normal programs are not supposed to use.
17537
17538          elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
17539             Set_Is_Limited_Composite (Full_T);
17540          else
17541             Error_Msg_N
17542               ("completion of limited tagged type must be limited", Full_T);
17543          end if;
17544
17545       elsif Is_Generic_Type (Priv_T) then
17546          Error_Msg_N ("generic type cannot have a completion", Full_T);
17547       end if;
17548
17549       --  Check that ancestor interfaces of private and full views are
17550       --  consistent. We omit this check for synchronized types because
17551       --  they are performed on the corresponding record type when frozen.
17552
17553       if Ada_Version >= Ada_2005
17554         and then Is_Tagged_Type (Priv_T)
17555         and then Is_Tagged_Type (Full_T)
17556         and then not Is_Concurrent_Type (Full_T)
17557       then
17558          declare
17559             Iface         : Entity_Id;
17560             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
17561             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
17562
17563          begin
17564             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
17565             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
17566
17567             --  Ada 2005 (AI-251): The partial view shall be a descendant of
17568             --  an interface type if and only if the full type is descendant
17569             --  of the interface type (AARM 7.3 (7.3/2)).
17570
17571             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
17572
17573             if Present (Iface) then
17574                Error_Msg_NE
17575                  ("interface & not implemented by full type " &
17576                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
17577             end if;
17578
17579             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
17580
17581             if Present (Iface) then
17582                Error_Msg_NE
17583                  ("interface & not implemented by partial view " &
17584                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
17585             end if;
17586          end;
17587       end if;
17588
17589       if Is_Tagged_Type (Priv_T)
17590         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17591         and then Is_Derived_Type (Full_T)
17592       then
17593          Priv_Parent := Etype (Priv_T);
17594
17595          --  The full view of a private extension may have been transformed
17596          --  into an unconstrained derived type declaration and a subtype
17597          --  declaration (see build_derived_record_type for details).
17598
17599          if Nkind (N) = N_Subtype_Declaration then
17600             Full_Indic  := Subtype_Indication (N);
17601             Full_Parent := Etype (Base_Type (Full_T));
17602          else
17603             Full_Indic  := Subtype_Indication (Type_Definition (N));
17604             Full_Parent := Etype (Full_T);
17605          end if;
17606
17607          --  Check that the parent type of the full type is a descendant of
17608          --  the ancestor subtype given in the private extension. If either
17609          --  entity has an Etype equal to Any_Type then we had some previous
17610          --  error situation [7.3(8)].
17611
17612          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
17613             return;
17614
17615          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
17616          --  any order. Therefore we don't have to check that its parent must
17617          --  be a descendant of the parent of the private type declaration.
17618
17619          elsif Is_Interface (Priv_Parent)
17620            and then Is_Interface (Full_Parent)
17621          then
17622             null;
17623
17624          --  Ada 2005 (AI-251): If the parent of the private type declaration
17625          --  is an interface there is no need to check that it is an ancestor
17626          --  of the associated full type declaration. The required tests for
17627          --  this case are performed by Build_Derived_Record_Type.
17628
17629          elsif not Is_Interface (Base_Type (Priv_Parent))
17630            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
17631          then
17632             Error_Msg_N
17633               ("parent of full type must descend from parent"
17634                   & " of private extension", Full_Indic);
17635
17636          --  First check a formal restriction, and then proceed with checking
17637          --  Ada rules. Since the formal restriction is not a serious error, we
17638          --  don't prevent further error detection for this check, hence the
17639          --  ELSE.
17640
17641          else
17642
17643             --  In formal mode, when completing a private extension the type
17644             --  named in the private part must be exactly the same as that
17645             --  named in the visible part.
17646
17647             if Priv_Parent /= Full_Parent then
17648                Error_Msg_Name_1 := Chars (Priv_Parent);
17649                Check_SPARK_Restriction ("% expected", Full_Indic);
17650             end if;
17651
17652             --  Check the rules of 7.3(10): if the private extension inherits
17653             --  known discriminants, then the full type must also inherit those
17654             --  discriminants from the same (ancestor) type, and the parent
17655             --  subtype of the full type must be constrained if and only if
17656             --  the ancestor subtype of the private extension is constrained.
17657
17658             if No (Discriminant_Specifications (Parent (Priv_T)))
17659               and then not Has_Unknown_Discriminants (Priv_T)
17660               and then Has_Discriminants (Base_Type (Priv_Parent))
17661             then
17662                declare
17663                   Priv_Indic  : constant Node_Id :=
17664                                   Subtype_Indication (Parent (Priv_T));
17665
17666                   Priv_Constr : constant Boolean :=
17667                                   Is_Constrained (Priv_Parent)
17668                                     or else
17669                                       Nkind (Priv_Indic) = N_Subtype_Indication
17670                                     or else
17671                                       Is_Constrained (Entity (Priv_Indic));
17672
17673                   Full_Constr : constant Boolean :=
17674                                   Is_Constrained (Full_Parent)
17675                                     or else
17676                                       Nkind (Full_Indic) = N_Subtype_Indication
17677                                     or else
17678                                       Is_Constrained (Entity (Full_Indic));
17679
17680                   Priv_Discr : Entity_Id;
17681                   Full_Discr : Entity_Id;
17682
17683                begin
17684                   Priv_Discr := First_Discriminant (Priv_Parent);
17685                   Full_Discr := First_Discriminant (Full_Parent);
17686                   while Present (Priv_Discr) and then Present (Full_Discr) loop
17687                      if Original_Record_Component (Priv_Discr) =
17688                         Original_Record_Component (Full_Discr)
17689                        or else
17690                          Corresponding_Discriminant (Priv_Discr) =
17691                          Corresponding_Discriminant (Full_Discr)
17692                      then
17693                         null;
17694                      else
17695                         exit;
17696                      end if;
17697
17698                      Next_Discriminant (Priv_Discr);
17699                      Next_Discriminant (Full_Discr);
17700                   end loop;
17701
17702                   if Present (Priv_Discr) or else Present (Full_Discr) then
17703                      Error_Msg_N
17704                        ("full view must inherit discriminants of the parent"
17705                         & " type used in the private extension", Full_Indic);
17706
17707                   elsif Priv_Constr and then not Full_Constr then
17708                      Error_Msg_N
17709                        ("parent subtype of full type must be constrained",
17710                         Full_Indic);
17711
17712                   elsif Full_Constr and then not Priv_Constr then
17713                      Error_Msg_N
17714                        ("parent subtype of full type must be unconstrained",
17715                         Full_Indic);
17716                   end if;
17717                end;
17718
17719                --  Check the rules of 7.3(12): if a partial view has neither
17720                --  known or unknown discriminants, then the full type
17721                --  declaration shall define a definite subtype.
17722
17723             elsif      not Has_Unknown_Discriminants (Priv_T)
17724               and then not Has_Discriminants (Priv_T)
17725               and then not Is_Constrained (Full_T)
17726             then
17727                Error_Msg_N
17728                  ("full view must define a constrained type if partial view"
17729                   & " has no discriminants", Full_T);
17730             end if;
17731
17732             --  ??????? Do we implement the following properly ?????
17733             --  If the ancestor subtype of a private extension has constrained
17734             --  discriminants, then the parent subtype of the full view shall
17735             --  impose a statically matching constraint on those discriminants
17736             --  [7.3(13)].
17737          end if;
17738
17739       else
17740          --  For untagged types, verify that a type without discriminants
17741          --  is not completed with an unconstrained type.
17742
17743          if not Is_Indefinite_Subtype (Priv_T)
17744            and then Is_Indefinite_Subtype (Full_T)
17745          then
17746             Error_Msg_N ("full view of type must be definite subtype", Full_T);
17747          end if;
17748       end if;
17749
17750       --  AI-419: verify that the use of "limited" is consistent
17751
17752       declare
17753          Orig_Decl : constant Node_Id := Original_Node (N);
17754
17755       begin
17756          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17757            and then not Limited_Present (Parent (Priv_T))
17758            and then not Synchronized_Present (Parent (Priv_T))
17759            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
17760            and then Nkind
17761              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
17762            and then Limited_Present (Type_Definition (Orig_Decl))
17763          then
17764             Error_Msg_N
17765               ("full view of non-limited extension cannot be limited", N);
17766          end if;
17767       end;
17768
17769       --  Ada 2005 (AI-443): A synchronized private extension must be
17770       --  completed by a task or protected type.
17771
17772       if Ada_Version >= Ada_2005
17773         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17774         and then Synchronized_Present (Parent (Priv_T))
17775         and then not Is_Concurrent_Type (Full_T)
17776       then
17777          Error_Msg_N ("full view of synchronized extension must " &
17778                       "be synchronized type", N);
17779       end if;
17780
17781       --  Ada 2005 AI-363: if the full view has discriminants with
17782       --  defaults, it is illegal to declare constrained access subtypes
17783       --  whose designated type is the current type. This allows objects
17784       --  of the type that are declared in the heap to be unconstrained.
17785
17786       if not Has_Unknown_Discriminants (Priv_T)
17787         and then not Has_Discriminants (Priv_T)
17788         and then Has_Discriminants (Full_T)
17789         and then
17790           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
17791       then
17792          Set_Has_Constrained_Partial_View (Full_T);
17793          Set_Has_Constrained_Partial_View (Priv_T);
17794       end if;
17795
17796       --  Create a full declaration for all its subtypes recorded in
17797       --  Private_Dependents and swap them similarly to the base type. These
17798       --  are subtypes that have been define before the full declaration of
17799       --  the private type. We also swap the entry in Private_Dependents list
17800       --  so we can properly restore the private view on exit from the scope.
17801
17802       declare
17803          Priv_Elmt : Elmt_Id;
17804          Priv      : Entity_Id;
17805          Full      : Entity_Id;
17806
17807       begin
17808          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
17809          while Present (Priv_Elmt) loop
17810             Priv := Node (Priv_Elmt);
17811
17812             if Ekind_In (Priv, E_Private_Subtype,
17813                                E_Limited_Private_Subtype,
17814                                E_Record_Subtype_With_Private)
17815             then
17816                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
17817                Set_Is_Itype (Full);
17818                Set_Parent (Full, Parent (Priv));
17819                Set_Associated_Node_For_Itype (Full, N);
17820
17821                --  Now we need to complete the private subtype, but since the
17822                --  base type has already been swapped, we must also swap the
17823                --  subtypes (and thus, reverse the arguments in the call to
17824                --  Complete_Private_Subtype).
17825
17826                Copy_And_Swap (Priv, Full);
17827                Complete_Private_Subtype (Full, Priv, Full_T, N);
17828                Replace_Elmt (Priv_Elmt, Full);
17829             end if;
17830
17831             Next_Elmt (Priv_Elmt);
17832          end loop;
17833       end;
17834
17835       --  If the private view was tagged, copy the new primitive operations
17836       --  from the private view to the full view.
17837
17838       if Is_Tagged_Type (Full_T) then
17839          declare
17840             Disp_Typ  : Entity_Id;
17841             Full_List : Elist_Id;
17842             Prim      : Entity_Id;
17843             Prim_Elmt : Elmt_Id;
17844             Priv_List : Elist_Id;
17845
17846             function Contains
17847               (E : Entity_Id;
17848                L : Elist_Id) return Boolean;
17849             --  Determine whether list L contains element E
17850
17851             --------------
17852             -- Contains --
17853             --------------
17854
17855             function Contains
17856               (E : Entity_Id;
17857                L : Elist_Id) return Boolean
17858             is
17859                List_Elmt : Elmt_Id;
17860
17861             begin
17862                List_Elmt := First_Elmt (L);
17863                while Present (List_Elmt) loop
17864                   if Node (List_Elmt) = E then
17865                      return True;
17866                   end if;
17867
17868                   Next_Elmt (List_Elmt);
17869                end loop;
17870
17871                return False;
17872             end Contains;
17873
17874          --  Start of processing
17875
17876          begin
17877             if Is_Tagged_Type (Priv_T) then
17878                Priv_List := Primitive_Operations (Priv_T);
17879                Prim_Elmt := First_Elmt (Priv_List);
17880
17881                --  In the case of a concurrent type completing a private tagged
17882                --  type, primitives may have been declared in between the two
17883                --  views. These subprograms need to be wrapped the same way
17884                --  entries and protected procedures are handled because they
17885                --  cannot be directly shared by the two views.
17886
17887                if Is_Concurrent_Type (Full_T) then
17888                   declare
17889                      Conc_Typ  : constant Entity_Id :=
17890                                    Corresponding_Record_Type (Full_T);
17891                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
17892                      Wrap_Spec : Node_Id;
17893
17894                   begin
17895                      while Present (Prim_Elmt) loop
17896                         Prim := Node (Prim_Elmt);
17897
17898                         if Comes_From_Source (Prim)
17899                           and then not Is_Abstract_Subprogram (Prim)
17900                         then
17901                            Wrap_Spec :=
17902                              Make_Subprogram_Declaration (Sloc (Prim),
17903                                Specification =>
17904                                  Build_Wrapper_Spec
17905                                    (Subp_Id => Prim,
17906                                     Obj_Typ => Conc_Typ,
17907                                     Formals =>
17908                                       Parameter_Specifications (
17909                                         Parent (Prim))));
17910
17911                            Insert_After (Curr_Nod, Wrap_Spec);
17912                            Curr_Nod := Wrap_Spec;
17913
17914                            Analyze (Wrap_Spec);
17915                         end if;
17916
17917                         Next_Elmt (Prim_Elmt);
17918                      end loop;
17919
17920                      return;
17921                   end;
17922
17923                --  For non-concurrent types, transfer explicit primitives, but
17924                --  omit those inherited from the parent of the private view
17925                --  since they will be re-inherited later on.
17926
17927                else
17928                   Full_List := Primitive_Operations (Full_T);
17929
17930                   while Present (Prim_Elmt) loop
17931                      Prim := Node (Prim_Elmt);
17932
17933                      if Comes_From_Source (Prim)
17934                        and then not Contains (Prim, Full_List)
17935                      then
17936                         Append_Elmt (Prim, Full_List);
17937                      end if;
17938
17939                      Next_Elmt (Prim_Elmt);
17940                   end loop;
17941                end if;
17942
17943             --  Untagged private view
17944
17945             else
17946                Full_List := Primitive_Operations (Full_T);
17947
17948                --  In this case the partial view is untagged, so here we locate
17949                --  all of the earlier primitives that need to be treated as
17950                --  dispatching (those that appear between the two views). Note
17951                --  that these additional operations must all be new operations
17952                --  (any earlier operations that override inherited operations
17953                --  of the full view will already have been inserted in the
17954                --  primitives list, marked by Check_Operation_From_Private_View
17955                --  as dispatching. Note that implicit "/=" operators are
17956                --  excluded from being added to the primitives list since they
17957                --  shouldn't be treated as dispatching (tagged "/=" is handled
17958                --  specially).
17959
17960                Prim := Next_Entity (Full_T);
17961                while Present (Prim) and then Prim /= Priv_T loop
17962                   if Ekind_In (Prim, E_Procedure, E_Function) then
17963                      Disp_Typ := Find_Dispatching_Type (Prim);
17964
17965                      if Disp_Typ = Full_T
17966                        and then (Chars (Prim) /= Name_Op_Ne
17967                                   or else Comes_From_Source (Prim))
17968                      then
17969                         Check_Controlling_Formals (Full_T, Prim);
17970
17971                         if not Is_Dispatching_Operation (Prim) then
17972                            Append_Elmt (Prim, Full_List);
17973                            Set_Is_Dispatching_Operation (Prim, True);
17974                            Set_DT_Position (Prim, No_Uint);
17975                         end if;
17976
17977                      elsif Is_Dispatching_Operation (Prim)
17978                        and then Disp_Typ  /= Full_T
17979                      then
17980
17981                         --  Verify that it is not otherwise controlled by a
17982                         --  formal or a return value of type T.
17983
17984                         Check_Controlling_Formals (Disp_Typ, Prim);
17985                      end if;
17986                   end if;
17987
17988                   Next_Entity (Prim);
17989                end loop;
17990             end if;
17991
17992             --  For the tagged case, the two views can share the same primitive
17993             --  operations list and the same class-wide type. Update attributes
17994             --  of the class-wide type which depend on the full declaration.
17995
17996             if Is_Tagged_Type (Priv_T) then
17997                Set_Direct_Primitive_Operations (Priv_T, Full_List);
17998                Set_Class_Wide_Type
17999                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
18000
18001                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
18002             end if;
18003          end;
18004       end if;
18005
18006       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
18007
18008       if Known_To_Have_Preelab_Init (Priv_T) then
18009
18010          --  Case where there is a pragma Preelaborable_Initialization. We
18011          --  always allow this in predefined units, which is a bit of a kludge,
18012          --  but it means we don't have to struggle to meet the requirements in
18013          --  the RM for having Preelaborable Initialization. Otherwise we
18014          --  require that the type meets the RM rules. But we can't check that
18015          --  yet, because of the rule about overriding Initialize, so we simply
18016          --  set a flag that will be checked at freeze time.
18017
18018          if not In_Predefined_Unit (Full_T) then
18019             Set_Must_Have_Preelab_Init (Full_T);
18020          end if;
18021       end if;
18022
18023       --  If pragma CPP_Class was applied to the private type declaration,
18024       --  propagate it now to the full type declaration.
18025
18026       if Is_CPP_Class (Priv_T) then
18027          Set_Is_CPP_Class (Full_T);
18028          Set_Convention   (Full_T, Convention_CPP);
18029       end if;
18030
18031       --  If the private view has user specified stream attributes, then so has
18032       --  the full view.
18033
18034       --  Why the test, how could these flags be already set in Full_T ???
18035
18036       if Has_Specified_Stream_Read (Priv_T) then
18037          Set_Has_Specified_Stream_Read (Full_T);
18038       end if;
18039
18040       if Has_Specified_Stream_Write (Priv_T) then
18041          Set_Has_Specified_Stream_Write (Full_T);
18042       end if;
18043
18044       if Has_Specified_Stream_Input (Priv_T) then
18045          Set_Has_Specified_Stream_Input (Full_T);
18046       end if;
18047
18048       if Has_Specified_Stream_Output (Priv_T) then
18049          Set_Has_Specified_Stream_Output (Full_T);
18050       end if;
18051
18052       --  Propagate invariants to full type
18053
18054       if Has_Invariants (Priv_T) then
18055          Set_Has_Invariants (Full_T);
18056          Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
18057       end if;
18058
18059       if Has_Inheritable_Invariants (Priv_T) then
18060          Set_Has_Inheritable_Invariants (Full_T);
18061       end if;
18062
18063       --  Propagate predicates to full type
18064
18065       if Has_Predicates (Priv_T) then
18066          Set_Predicate_Function (Priv_T, Predicate_Function (Full_T));
18067          Set_Has_Predicates (Priv_T);
18068       end if;
18069    end Process_Full_View;
18070
18071    -----------------------------------
18072    -- Process_Incomplete_Dependents --
18073    -----------------------------------
18074
18075    procedure Process_Incomplete_Dependents
18076      (N      : Node_Id;
18077       Full_T : Entity_Id;
18078       Inc_T  : Entity_Id)
18079    is
18080       Inc_Elmt : Elmt_Id;
18081       Priv_Dep : Entity_Id;
18082       New_Subt : Entity_Id;
18083
18084       Disc_Constraint : Elist_Id;
18085
18086    begin
18087       if No (Private_Dependents (Inc_T)) then
18088          return;
18089       end if;
18090
18091       --  Itypes that may be generated by the completion of an incomplete
18092       --  subtype are not used by the back-end and not attached to the tree.
18093       --  They are created only for constraint-checking purposes.
18094
18095       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
18096       while Present (Inc_Elmt) loop
18097          Priv_Dep := Node (Inc_Elmt);
18098
18099          if Ekind (Priv_Dep) = E_Subprogram_Type then
18100
18101             --  An Access_To_Subprogram type may have a return type or a
18102             --  parameter type that is incomplete. Replace with the full view.
18103
18104             if Etype (Priv_Dep) = Inc_T then
18105                Set_Etype (Priv_Dep, Full_T);
18106             end if;
18107
18108             declare
18109                Formal : Entity_Id;
18110
18111             begin
18112                Formal := First_Formal (Priv_Dep);
18113                while Present (Formal) loop
18114                   if Etype (Formal) = Inc_T then
18115                      Set_Etype (Formal, Full_T);
18116                   end if;
18117
18118                   Next_Formal (Formal);
18119                end loop;
18120             end;
18121
18122          elsif Is_Overloadable (Priv_Dep) then
18123
18124             --  If a subprogram in the incomplete dependents list is primitive
18125             --  for a tagged full type then mark it as a dispatching operation,
18126             --  check whether it overrides an inherited subprogram, and check
18127             --  restrictions on its controlling formals. Note that a protected
18128             --  operation is never dispatching: only its wrapper operation
18129             --  (which has convention Ada) is.
18130
18131             if Is_Tagged_Type (Full_T)
18132               and then Is_Primitive (Priv_Dep)
18133               and then Convention (Priv_Dep) /= Convention_Protected
18134             then
18135                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
18136                Set_Is_Dispatching_Operation (Priv_Dep);
18137                Check_Controlling_Formals (Full_T, Priv_Dep);
18138             end if;
18139
18140          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
18141
18142             --  Can happen during processing of a body before the completion
18143             --  of a TA type. Ignore, because spec is also on dependent list.
18144
18145             return;
18146
18147          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
18148          --  corresponding subtype of the full view.
18149
18150          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
18151             Set_Subtype_Indication
18152               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
18153             Set_Etype (Priv_Dep, Full_T);
18154             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
18155             Set_Analyzed (Parent (Priv_Dep), False);
18156
18157             --  Reanalyze the declaration, suppressing the call to
18158             --  Enter_Name to avoid duplicate names.
18159
18160             Analyze_Subtype_Declaration
18161               (N    => Parent (Priv_Dep),
18162                Skip => True);
18163
18164          --  Dependent is a subtype
18165
18166          else
18167             --  We build a new subtype indication using the full view of the
18168             --  incomplete parent. The discriminant constraints have been
18169             --  elaborated already at the point of the subtype declaration.
18170
18171             New_Subt := Create_Itype (E_Void, N);
18172
18173             if Has_Discriminants (Full_T) then
18174                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
18175             else
18176                Disc_Constraint := No_Elist;
18177             end if;
18178
18179             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
18180             Set_Full_View (Priv_Dep, New_Subt);
18181          end if;
18182
18183          Next_Elmt (Inc_Elmt);
18184       end loop;
18185    end Process_Incomplete_Dependents;
18186
18187    --------------------------------
18188    -- Process_Range_Expr_In_Decl --
18189    --------------------------------
18190
18191    procedure Process_Range_Expr_In_Decl
18192      (R            : Node_Id;
18193       T            : Entity_Id;
18194       Check_List   : List_Id := Empty_List;
18195       R_Check_Off  : Boolean := False;
18196       In_Iter_Schm : Boolean := False)
18197    is
18198       Lo, Hi      : Node_Id;
18199       R_Checks    : Check_Result;
18200       Insert_Node : Node_Id;
18201       Def_Id      : Entity_Id;
18202
18203    begin
18204       Analyze_And_Resolve (R, Base_Type (T));
18205
18206       if Nkind (R) = N_Range then
18207
18208          --  In SPARK, all ranges should be static, with the exception of the
18209          --  discrete type definition of a loop parameter specification.
18210
18211          if not In_Iter_Schm
18212            and then not Is_Static_Range (R)
18213          then
18214             Check_SPARK_Restriction ("range should be static", R);
18215          end if;
18216
18217          Lo := Low_Bound (R);
18218          Hi := High_Bound (R);
18219
18220          --  We need to ensure validity of the bounds here, because if we
18221          --  go ahead and do the expansion, then the expanded code will get
18222          --  analyzed with range checks suppressed and we miss the check.
18223
18224          Validity_Check_Range (R);
18225
18226          --  If there were errors in the declaration, try and patch up some
18227          --  common mistakes in the bounds. The cases handled are literals
18228          --  which are Integer where the expected type is Real and vice versa.
18229          --  These corrections allow the compilation process to proceed further
18230          --  along since some basic assumptions of the format of the bounds
18231          --  are guaranteed.
18232
18233          if Etype (R) = Any_Type then
18234
18235             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
18236                Rewrite (Lo,
18237                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
18238
18239             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
18240                Rewrite (Hi,
18241                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
18242
18243             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
18244                Rewrite (Lo,
18245                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
18246
18247             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
18248                Rewrite (Hi,
18249                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
18250             end if;
18251
18252             Set_Etype (Lo, T);
18253             Set_Etype (Hi, T);
18254          end if;
18255
18256          --  If the bounds of the range have been mistakenly given as string
18257          --  literals (perhaps in place of character literals), then an error
18258          --  has already been reported, but we rewrite the string literal as a
18259          --  bound of the range's type to avoid blowups in later processing
18260          --  that looks at static values.
18261
18262          if Nkind (Lo) = N_String_Literal then
18263             Rewrite (Lo,
18264               Make_Attribute_Reference (Sloc (Lo),
18265                 Attribute_Name => Name_First,
18266                 Prefix => New_Reference_To (T, Sloc (Lo))));
18267             Analyze_And_Resolve (Lo);
18268          end if;
18269
18270          if Nkind (Hi) = N_String_Literal then
18271             Rewrite (Hi,
18272               Make_Attribute_Reference (Sloc (Hi),
18273                 Attribute_Name => Name_First,
18274                 Prefix => New_Reference_To (T, Sloc (Hi))));
18275             Analyze_And_Resolve (Hi);
18276          end if;
18277
18278          --  If bounds aren't scalar at this point then exit, avoiding
18279          --  problems with further processing of the range in this procedure.
18280
18281          if not Is_Scalar_Type (Etype (Lo)) then
18282             return;
18283          end if;
18284
18285          --  Resolve (actually Sem_Eval) has checked that the bounds are in
18286          --  then range of the base type. Here we check whether the bounds
18287          --  are in the range of the subtype itself. Note that if the bounds
18288          --  represent the null range the Constraint_Error exception should
18289          --  not be raised.
18290
18291          --  ??? The following code should be cleaned up as follows
18292
18293          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
18294          --     is done in the call to Range_Check (R, T); below
18295
18296          --  2. The use of R_Check_Off should be investigated and possibly
18297          --     removed, this would clean up things a bit.
18298
18299          if Is_Null_Range (Lo, Hi) then
18300             null;
18301
18302          else
18303             --  Capture values of bounds and generate temporaries for them
18304             --  if needed, before applying checks, since checks may cause
18305             --  duplication of the expression without forcing evaluation.
18306
18307             if Expander_Active then
18308                Force_Evaluation (Lo);
18309                Force_Evaluation (Hi);
18310             end if;
18311
18312             --  We use a flag here instead of suppressing checks on the
18313             --  type because the type we check against isn't necessarily
18314             --  the place where we put the check.
18315
18316             if not R_Check_Off then
18317                R_Checks := Get_Range_Checks (R, T);
18318
18319                --  Look up tree to find an appropriate insertion point. We
18320                --  can't just use insert_actions because later processing
18321                --  depends on the insertion node. Prior to Ada 2012 the
18322                --  insertion point could only be a declaration or a loop, but
18323                --  quantified expressions can appear within any context in an
18324                --  expression, and the insertion point can be any statement,
18325                --  pragma, or declaration.
18326
18327                Insert_Node := Parent (R);
18328                while Present (Insert_Node) loop
18329                   exit when
18330                     Nkind (Insert_Node) in N_Declaration
18331                     and then
18332                       not Nkind_In
18333                         (Insert_Node, N_Component_Declaration,
18334                                       N_Loop_Parameter_Specification,
18335                                       N_Function_Specification,
18336                                       N_Procedure_Specification);
18337
18338                   exit when Nkind (Insert_Node) in N_Later_Decl_Item
18339                     or else Nkind (Insert_Node) in
18340                               N_Statement_Other_Than_Procedure_Call
18341                     or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
18342                                                    N_Pragma);
18343
18344                   Insert_Node := Parent (Insert_Node);
18345                end loop;
18346
18347                --  Why would Type_Decl not be present???  Without this test,
18348                --  short regression tests fail.
18349
18350                if Present (Insert_Node) then
18351
18352                   --  Case of loop statement. Verify that the range is part
18353                   --  of the subtype indication of the iteration scheme.
18354
18355                   if Nkind (Insert_Node) = N_Loop_Statement then
18356                      declare
18357                         Indic : Node_Id;
18358
18359                      begin
18360                         Indic := Parent (R);
18361                         while Present (Indic)
18362                           and then Nkind (Indic) /= N_Subtype_Indication
18363                         loop
18364                            Indic := Parent (Indic);
18365                         end loop;
18366
18367                         if Present (Indic) then
18368                            Def_Id := Etype (Subtype_Mark (Indic));
18369
18370                            Insert_Range_Checks
18371                              (R_Checks,
18372                               Insert_Node,
18373                               Def_Id,
18374                               Sloc (Insert_Node),
18375                               R,
18376                               Do_Before => True);
18377                         end if;
18378                      end;
18379
18380                   --  Insertion before a declaration. If the declaration
18381                   --  includes discriminants, the list of applicable checks
18382                   --  is given by the caller.
18383
18384                   elsif Nkind (Insert_Node) in N_Declaration then
18385                      Def_Id := Defining_Identifier (Insert_Node);
18386
18387                      if (Ekind (Def_Id) = E_Record_Type
18388                           and then Depends_On_Discriminant (R))
18389                        or else
18390                         (Ekind (Def_Id) = E_Protected_Type
18391                           and then Has_Discriminants (Def_Id))
18392                      then
18393                         Append_Range_Checks
18394                           (R_Checks,
18395                             Check_List, Def_Id, Sloc (Insert_Node), R);
18396
18397                      else
18398                         Insert_Range_Checks
18399                           (R_Checks,
18400                             Insert_Node, Def_Id, Sloc (Insert_Node), R);
18401
18402                      end if;
18403
18404                   --  Insertion before a statement. Range appears in the
18405                   --  context of a quantified expression. Insertion will
18406                   --  take place when expression is expanded.
18407
18408                   else
18409                      null;
18410                   end if;
18411                end if;
18412             end if;
18413          end if;
18414
18415       --  Case of other than an explicit N_Range node
18416
18417       elsif Expander_Active then
18418          Get_Index_Bounds (R, Lo, Hi);
18419          Force_Evaluation (Lo);
18420          Force_Evaluation (Hi);
18421       end if;
18422    end Process_Range_Expr_In_Decl;
18423
18424    --------------------------------------
18425    -- Process_Real_Range_Specification --
18426    --------------------------------------
18427
18428    procedure Process_Real_Range_Specification (Def : Node_Id) is
18429       Spec : constant Node_Id := Real_Range_Specification (Def);
18430       Lo   : Node_Id;
18431       Hi   : Node_Id;
18432       Err  : Boolean := False;
18433
18434       procedure Analyze_Bound (N : Node_Id);
18435       --  Analyze and check one bound
18436
18437       -------------------
18438       -- Analyze_Bound --
18439       -------------------
18440
18441       procedure Analyze_Bound (N : Node_Id) is
18442       begin
18443          Analyze_And_Resolve (N, Any_Real);
18444
18445          if not Is_OK_Static_Expression (N) then
18446             Flag_Non_Static_Expr
18447               ("bound in real type definition is not static!", N);
18448             Err := True;
18449          end if;
18450       end Analyze_Bound;
18451
18452    --  Start of processing for Process_Real_Range_Specification
18453
18454    begin
18455       if Present (Spec) then
18456          Lo := Low_Bound (Spec);
18457          Hi := High_Bound (Spec);
18458          Analyze_Bound (Lo);
18459          Analyze_Bound (Hi);
18460
18461          --  If error, clear away junk range specification
18462
18463          if Err then
18464             Set_Real_Range_Specification (Def, Empty);
18465          end if;
18466       end if;
18467    end Process_Real_Range_Specification;
18468
18469    ---------------------
18470    -- Process_Subtype --
18471    ---------------------
18472
18473    function Process_Subtype
18474      (S           : Node_Id;
18475       Related_Nod : Node_Id;
18476       Related_Id  : Entity_Id := Empty;
18477       Suffix      : Character := ' ') return Entity_Id
18478    is
18479       P               : Node_Id;
18480       Def_Id          : Entity_Id;
18481       Error_Node      : Node_Id;
18482       Full_View_Id    : Entity_Id;
18483       Subtype_Mark_Id : Entity_Id;
18484
18485       May_Have_Null_Exclusion : Boolean;
18486
18487       procedure Check_Incomplete (T : Entity_Id);
18488       --  Called to verify that an incomplete type is not used prematurely
18489
18490       ----------------------
18491       -- Check_Incomplete --
18492       ----------------------
18493
18494       procedure Check_Incomplete (T : Entity_Id) is
18495       begin
18496          --  Ada 2005 (AI-412): Incomplete subtypes are legal
18497
18498          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
18499            and then
18500              not (Ada_Version >= Ada_2005
18501                     and then
18502                        (Nkind (Parent (T)) = N_Subtype_Declaration
18503                           or else
18504                             (Nkind (Parent (T)) = N_Subtype_Indication
18505                                and then Nkind (Parent (Parent (T))) =
18506                                           N_Subtype_Declaration)))
18507          then
18508             Error_Msg_N ("invalid use of type before its full declaration", T);
18509          end if;
18510       end Check_Incomplete;
18511
18512    --  Start of processing for Process_Subtype
18513
18514    begin
18515       --  Case of no constraints present
18516
18517       if Nkind (S) /= N_Subtype_Indication then
18518          Find_Type (S);
18519          Check_Incomplete (S);
18520          P := Parent (S);
18521
18522          --  Ada 2005 (AI-231): Static check
18523
18524          if Ada_Version >= Ada_2005
18525            and then Present (P)
18526            and then Null_Exclusion_Present (P)
18527            and then Nkind (P) /= N_Access_To_Object_Definition
18528            and then not Is_Access_Type (Entity (S))
18529          then
18530             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
18531          end if;
18532
18533          --  The following is ugly, can't we have a range or even a flag???
18534
18535          May_Have_Null_Exclusion :=
18536            Nkind_In (P, N_Access_Definition,
18537                         N_Access_Function_Definition,
18538                         N_Access_Procedure_Definition,
18539                         N_Access_To_Object_Definition,
18540                         N_Allocator,
18541                         N_Component_Definition)
18542              or else
18543            Nkind_In (P, N_Derived_Type_Definition,
18544                         N_Discriminant_Specification,
18545                         N_Formal_Object_Declaration,
18546                         N_Object_Declaration,
18547                         N_Object_Renaming_Declaration,
18548                         N_Parameter_Specification,
18549                         N_Subtype_Declaration);
18550
18551          --  Create an Itype that is a duplicate of Entity (S) but with the
18552          --  null-exclusion attribute.
18553
18554          if May_Have_Null_Exclusion
18555            and then Is_Access_Type (Entity (S))
18556            and then Null_Exclusion_Present (P)
18557
18558             --  No need to check the case of an access to object definition.
18559             --  It is correct to define double not-null pointers.
18560
18561             --  Example:
18562             --     type Not_Null_Int_Ptr is not null access Integer;
18563             --     type Acc is not null access Not_Null_Int_Ptr;
18564
18565            and then Nkind (P) /= N_Access_To_Object_Definition
18566          then
18567             if Can_Never_Be_Null (Entity (S)) then
18568                case Nkind (Related_Nod) is
18569                   when N_Full_Type_Declaration =>
18570                      if Nkind (Type_Definition (Related_Nod))
18571                        in N_Array_Type_Definition
18572                      then
18573                         Error_Node :=
18574                           Subtype_Indication
18575                             (Component_Definition
18576                              (Type_Definition (Related_Nod)));
18577                      else
18578                         Error_Node :=
18579                           Subtype_Indication (Type_Definition (Related_Nod));
18580                      end if;
18581
18582                   when N_Subtype_Declaration =>
18583                      Error_Node := Subtype_Indication (Related_Nod);
18584
18585                   when N_Object_Declaration =>
18586                      Error_Node := Object_Definition (Related_Nod);
18587
18588                   when N_Component_Declaration =>
18589                      Error_Node :=
18590                        Subtype_Indication (Component_Definition (Related_Nod));
18591
18592                   when N_Allocator =>
18593                      Error_Node := Expression (Related_Nod);
18594
18595                   when others =>
18596                      pragma Assert (False);
18597                      Error_Node := Related_Nod;
18598                end case;
18599
18600                Error_Msg_NE
18601                  ("`NOT NULL` not allowed (& already excludes null)",
18602                   Error_Node,
18603                   Entity (S));
18604             end if;
18605
18606             Set_Etype  (S,
18607               Create_Null_Excluding_Itype
18608                 (T           => Entity (S),
18609                  Related_Nod => P));
18610             Set_Entity (S, Etype (S));
18611          end if;
18612
18613          return Entity (S);
18614
18615       --  Case of constraint present, so that we have an N_Subtype_Indication
18616       --  node (this node is created only if constraints are present).
18617
18618       else
18619          Find_Type (Subtype_Mark (S));
18620
18621          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
18622            and then not
18623             (Nkind (Parent (S)) = N_Subtype_Declaration
18624               and then Is_Itype (Defining_Identifier (Parent (S))))
18625          then
18626             Check_Incomplete (Subtype_Mark (S));
18627          end if;
18628
18629          P := Parent (S);
18630          Subtype_Mark_Id := Entity (Subtype_Mark (S));
18631
18632          --  Explicit subtype declaration case
18633
18634          if Nkind (P) = N_Subtype_Declaration then
18635             Def_Id := Defining_Identifier (P);
18636
18637          --  Explicit derived type definition case
18638
18639          elsif Nkind (P) = N_Derived_Type_Definition then
18640             Def_Id := Defining_Identifier (Parent (P));
18641
18642          --  Implicit case, the Def_Id must be created as an implicit type.
18643          --  The one exception arises in the case of concurrent types, array
18644          --  and access types, where other subsidiary implicit types may be
18645          --  created and must appear before the main implicit type. In these
18646          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
18647          --  has not yet been called to create Def_Id.
18648
18649          else
18650             if Is_Array_Type (Subtype_Mark_Id)
18651               or else Is_Concurrent_Type (Subtype_Mark_Id)
18652               or else Is_Access_Type (Subtype_Mark_Id)
18653             then
18654                Def_Id := Empty;
18655
18656             --  For the other cases, we create a new unattached Itype,
18657             --  and set the indication to ensure it gets attached later.
18658
18659             else
18660                Def_Id :=
18661                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
18662             end if;
18663          end if;
18664
18665          --  If the kind of constraint is invalid for this kind of type,
18666          --  then give an error, and then pretend no constraint was given.
18667
18668          if not Is_Valid_Constraint_Kind
18669                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
18670          then
18671             Error_Msg_N
18672               ("incorrect constraint for this kind of type", Constraint (S));
18673
18674             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
18675
18676             --  Set Ekind of orphan itype, to prevent cascaded errors
18677
18678             if Present (Def_Id) then
18679                Set_Ekind (Def_Id, Ekind (Any_Type));
18680             end if;
18681
18682             --  Make recursive call, having got rid of the bogus constraint
18683
18684             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
18685          end if;
18686
18687          --  Remaining processing depends on type. Select on Base_Type kind to
18688          --  ensure getting to the concrete type kind in the case of a private
18689          --  subtype (needed when only doing semantic analysis).
18690
18691          case Ekind (Base_Type (Subtype_Mark_Id)) is
18692             when Access_Kind =>
18693                Constrain_Access (Def_Id, S, Related_Nod);
18694
18695                if Expander_Active
18696                  and then  Is_Itype (Designated_Type (Def_Id))
18697                  and then Nkind (Related_Nod) = N_Subtype_Declaration
18698                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
18699                then
18700                   Build_Itype_Reference
18701                     (Designated_Type (Def_Id), Related_Nod);
18702                end if;
18703
18704             when Array_Kind =>
18705                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
18706
18707             when Decimal_Fixed_Point_Kind =>
18708                Constrain_Decimal (Def_Id, S);
18709
18710             when Enumeration_Kind =>
18711                Constrain_Enumeration (Def_Id, S);
18712
18713             when Ordinary_Fixed_Point_Kind =>
18714                Constrain_Ordinary_Fixed (Def_Id, S);
18715
18716             when Float_Kind =>
18717                Constrain_Float (Def_Id, S);
18718
18719             when Integer_Kind =>
18720                Constrain_Integer (Def_Id, S);
18721
18722             when E_Record_Type     |
18723                  E_Record_Subtype  |
18724                  Class_Wide_Kind   |
18725                  E_Incomplete_Type =>
18726                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
18727
18728                if Ekind (Def_Id) = E_Incomplete_Type then
18729                   Set_Private_Dependents (Def_Id, New_Elmt_List);
18730                end if;
18731
18732             when Private_Kind =>
18733                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
18734                Set_Private_Dependents (Def_Id, New_Elmt_List);
18735
18736                --  In case of an invalid constraint prevent further processing
18737                --  since the type constructed is missing expected fields.
18738
18739                if Etype (Def_Id) = Any_Type then
18740                   return Def_Id;
18741                end if;
18742
18743                --  If the full view is that of a task with discriminants,
18744                --  we must constrain both the concurrent type and its
18745                --  corresponding record type. Otherwise we will just propagate
18746                --  the constraint to the full view, if available.
18747
18748                if Present (Full_View (Subtype_Mark_Id))
18749                  and then Has_Discriminants (Subtype_Mark_Id)
18750                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
18751                then
18752                   Full_View_Id :=
18753                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
18754
18755                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
18756                   Constrain_Concurrent (Full_View_Id, S,
18757                     Related_Nod, Related_Id, Suffix);
18758                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
18759                   Set_Full_View (Def_Id, Full_View_Id);
18760
18761                   --  Introduce an explicit reference to the private subtype,
18762                   --  to prevent scope anomalies in gigi if first use appears
18763                   --  in a nested context, e.g. a later function body.
18764                   --  Should this be generated in other contexts than a full
18765                   --  type declaration?
18766
18767                   if Is_Itype (Def_Id)
18768                     and then
18769                       Nkind (Parent (P)) = N_Full_Type_Declaration
18770                   then
18771                      Build_Itype_Reference (Def_Id, Parent (P));
18772                   end if;
18773
18774                else
18775                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
18776                end if;
18777
18778             when Concurrent_Kind  =>
18779                Constrain_Concurrent (Def_Id, S,
18780                  Related_Nod, Related_Id, Suffix);
18781
18782             when others =>
18783                Error_Msg_N ("invalid subtype mark in subtype indication", S);
18784          end case;
18785
18786          --  Size and Convention are always inherited from the base type
18787
18788          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
18789          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
18790
18791          return Def_Id;
18792       end if;
18793    end Process_Subtype;
18794
18795    ---------------------------------------
18796    -- Check_Anonymous_Access_Components --
18797    ---------------------------------------
18798
18799    procedure Check_Anonymous_Access_Components
18800       (Typ_Decl  : Node_Id;
18801        Typ       : Entity_Id;
18802        Prev      : Entity_Id;
18803        Comp_List : Node_Id)
18804    is
18805       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
18806       Anon_Access : Entity_Id;
18807       Acc_Def     : Node_Id;
18808       Comp        : Node_Id;
18809       Comp_Def    : Node_Id;
18810       Decl        : Node_Id;
18811       Type_Def    : Node_Id;
18812
18813       procedure Build_Incomplete_Type_Declaration;
18814       --  If the record type contains components that include an access to the
18815       --  current record, then create an incomplete type declaration for the
18816       --  record, to be used as the designated type of the anonymous access.
18817       --  This is done only once, and only if there is no previous partial
18818       --  view of the type.
18819
18820       function Designates_T (Subt : Node_Id) return Boolean;
18821       --  Check whether a node designates the enclosing record type, or 'Class
18822       --  of that type
18823
18824       function Mentions_T (Acc_Def : Node_Id) return Boolean;
18825       --  Check whether an access definition includes a reference to
18826       --  the enclosing record type. The reference can be a subtype mark
18827       --  in the access definition itself, a 'Class attribute reference, or
18828       --  recursively a reference appearing in a parameter specification
18829       --  or result definition of an access_to_subprogram definition.
18830
18831       --------------------------------------
18832       -- Build_Incomplete_Type_Declaration --
18833       --------------------------------------
18834
18835       procedure Build_Incomplete_Type_Declaration is
18836          Decl  : Node_Id;
18837          Inc_T : Entity_Id;
18838          H     : Entity_Id;
18839
18840          --  Is_Tagged indicates whether the type is tagged. It is tagged if
18841          --  it's "is new ... with record" or else "is tagged record ...".
18842
18843          Is_Tagged : constant Boolean :=
18844              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
18845                  and then
18846                    Present
18847                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
18848            or else
18849              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
18850                  and then Tagged_Present (Type_Definition (Typ_Decl)));
18851
18852       begin
18853          --  If there is a previous partial view, no need to create a new one
18854          --  If the partial view, given by Prev, is incomplete,  If Prev is
18855          --  a private declaration, full declaration is flagged accordingly.
18856
18857          if Prev /= Typ then
18858             if Is_Tagged then
18859                Make_Class_Wide_Type (Prev);
18860                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
18861                Set_Etype (Class_Wide_Type (Typ), Typ);
18862             end if;
18863
18864             return;
18865
18866          elsif Has_Private_Declaration (Typ) then
18867
18868             --  If we refer to T'Class inside T, and T is the completion of a
18869             --  private type, then we need to make sure the class-wide type
18870             --  exists.
18871
18872             if Is_Tagged then
18873                Make_Class_Wide_Type (Typ);
18874             end if;
18875
18876             return;
18877
18878          --  If there was a previous anonymous access type, the incomplete
18879          --  type declaration will have been created already.
18880
18881          elsif Present (Current_Entity (Typ))
18882            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
18883            and then Full_View (Current_Entity (Typ)) = Typ
18884          then
18885             if Is_Tagged
18886               and then Comes_From_Source (Current_Entity (Typ))
18887               and then not Is_Tagged_Type (Current_Entity (Typ))
18888             then
18889                Make_Class_Wide_Type (Typ);
18890                Error_Msg_N
18891                  ("incomplete view of tagged type should be declared tagged?",
18892                   Parent (Current_Entity (Typ)));
18893             end if;
18894             return;
18895
18896          else
18897             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
18898             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
18899
18900             --  Type has already been inserted into the current scope. Remove
18901             --  it, and add incomplete declaration for type, so that subsequent
18902             --  anonymous access types can use it. The entity is unchained from
18903             --  the homonym list and from immediate visibility. After analysis,
18904             --  the entity in the incomplete declaration becomes immediately
18905             --  visible in the record declaration that follows.
18906
18907             H := Current_Entity (Typ);
18908
18909             if H = Typ then
18910                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
18911             else
18912                while Present (H)
18913                  and then Homonym (H) /= Typ
18914                loop
18915                   H := Homonym (Typ);
18916                end loop;
18917
18918                Set_Homonym (H, Homonym (Typ));
18919             end if;
18920
18921             Insert_Before (Typ_Decl, Decl);
18922             Analyze (Decl);
18923             Set_Full_View (Inc_T, Typ);
18924
18925             if Is_Tagged then
18926
18927                --  Create a common class-wide type for both views, and set the
18928                --  Etype of the class-wide type to the full view.
18929
18930                Make_Class_Wide_Type (Inc_T);
18931                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
18932                Set_Etype (Class_Wide_Type (Typ), Typ);
18933             end if;
18934          end if;
18935       end Build_Incomplete_Type_Declaration;
18936
18937       ------------------
18938       -- Designates_T --
18939       ------------------
18940
18941       function Designates_T (Subt : Node_Id) return Boolean is
18942          Type_Id : constant Name_Id := Chars (Typ);
18943
18944          function Names_T (Nam : Node_Id) return Boolean;
18945          --  The record type has not been introduced in the current scope
18946          --  yet, so we must examine the name of the type itself, either
18947          --  an identifier T, or an expanded name of the form P.T, where
18948          --  P denotes the current scope.
18949
18950          -------------
18951          -- Names_T --
18952          -------------
18953
18954          function Names_T (Nam : Node_Id) return Boolean is
18955          begin
18956             if Nkind (Nam) = N_Identifier then
18957                return Chars (Nam) = Type_Id;
18958
18959             elsif Nkind (Nam) = N_Selected_Component then
18960                if Chars (Selector_Name (Nam)) = Type_Id then
18961                   if Nkind (Prefix (Nam)) = N_Identifier then
18962                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
18963
18964                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
18965                      return Chars (Selector_Name (Prefix (Nam))) =
18966                             Chars (Current_Scope);
18967                   else
18968                      return False;
18969                   end if;
18970
18971                else
18972                   return False;
18973                end if;
18974
18975             else
18976                return False;
18977             end if;
18978          end Names_T;
18979
18980       --  Start of processing for Designates_T
18981
18982       begin
18983          if Nkind (Subt) = N_Identifier then
18984             return Chars (Subt) = Type_Id;
18985
18986             --  Reference can be through an expanded name which has not been
18987             --  analyzed yet, and which designates enclosing scopes.
18988
18989          elsif Nkind (Subt) = N_Selected_Component then
18990             if Names_T (Subt) then
18991                return True;
18992
18993             --  Otherwise it must denote an entity that is already visible.
18994             --  The access definition may name a subtype of the enclosing
18995             --  type, if there is a previous incomplete declaration for it.
18996
18997             else
18998                Find_Selected_Component (Subt);
18999                return
19000                  Is_Entity_Name (Subt)
19001                    and then Scope (Entity (Subt)) = Current_Scope
19002                    and then
19003                      (Chars (Base_Type (Entity (Subt))) = Type_Id
19004                        or else
19005                          (Is_Class_Wide_Type (Entity (Subt))
19006                            and then
19007                            Chars (Etype (Base_Type (Entity (Subt)))) =
19008                                                                   Type_Id));
19009             end if;
19010
19011          --  A reference to the current type may appear as the prefix of
19012          --  a 'Class attribute.
19013
19014          elsif Nkind (Subt) = N_Attribute_Reference
19015            and then Attribute_Name (Subt) = Name_Class
19016          then
19017             return Names_T (Prefix (Subt));
19018
19019          else
19020             return False;
19021          end if;
19022       end Designates_T;
19023
19024       ----------------
19025       -- Mentions_T --
19026       ----------------
19027
19028       function Mentions_T (Acc_Def : Node_Id) return Boolean is
19029          Param_Spec : Node_Id;
19030
19031          Acc_Subprg : constant Node_Id :=
19032                         Access_To_Subprogram_Definition (Acc_Def);
19033
19034       begin
19035          if No (Acc_Subprg) then
19036             return Designates_T (Subtype_Mark (Acc_Def));
19037          end if;
19038
19039          --  Component is an access_to_subprogram: examine its formals,
19040          --  and result definition in the case of an access_to_function.
19041
19042          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
19043          while Present (Param_Spec) loop
19044             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
19045               and then Mentions_T (Parameter_Type (Param_Spec))
19046             then
19047                return True;
19048
19049             elsif Designates_T (Parameter_Type (Param_Spec)) then
19050                return True;
19051             end if;
19052
19053             Next (Param_Spec);
19054          end loop;
19055
19056          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
19057             if Nkind (Result_Definition (Acc_Subprg)) =
19058                  N_Access_Definition
19059             then
19060                return Mentions_T (Result_Definition (Acc_Subprg));
19061             else
19062                return Designates_T (Result_Definition (Acc_Subprg));
19063             end if;
19064          end if;
19065
19066          return False;
19067       end Mentions_T;
19068
19069    --  Start of processing for Check_Anonymous_Access_Components
19070
19071    begin
19072       if No (Comp_List) then
19073          return;
19074       end if;
19075
19076       Comp := First (Component_Items (Comp_List));
19077       while Present (Comp) loop
19078          if Nkind (Comp) = N_Component_Declaration
19079            and then Present
19080              (Access_Definition (Component_Definition (Comp)))
19081            and then
19082              Mentions_T (Access_Definition (Component_Definition (Comp)))
19083          then
19084             Comp_Def := Component_Definition (Comp);
19085             Acc_Def :=
19086               Access_To_Subprogram_Definition
19087                 (Access_Definition (Comp_Def));
19088
19089             Build_Incomplete_Type_Declaration;
19090             Anon_Access := Make_Temporary (Loc, 'S');
19091
19092             --  Create a declaration for the anonymous access type: either
19093             --  an access_to_object or an access_to_subprogram.
19094
19095             if Present (Acc_Def) then
19096                if Nkind (Acc_Def) = N_Access_Function_Definition then
19097                   Type_Def :=
19098                     Make_Access_Function_Definition (Loc,
19099                       Parameter_Specifications =>
19100                         Parameter_Specifications (Acc_Def),
19101                       Result_Definition => Result_Definition (Acc_Def));
19102                else
19103                   Type_Def :=
19104                     Make_Access_Procedure_Definition (Loc,
19105                       Parameter_Specifications =>
19106                         Parameter_Specifications (Acc_Def));
19107                end if;
19108
19109             else
19110                Type_Def :=
19111                  Make_Access_To_Object_Definition (Loc,
19112                    Subtype_Indication =>
19113                       Relocate_Node
19114                         (Subtype_Mark
19115                           (Access_Definition (Comp_Def))));
19116
19117                Set_Constant_Present
19118                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
19119                Set_All_Present
19120                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
19121             end if;
19122
19123             Set_Null_Exclusion_Present
19124               (Type_Def,
19125                Null_Exclusion_Present (Access_Definition (Comp_Def)));
19126
19127             Decl :=
19128               Make_Full_Type_Declaration (Loc,
19129                 Defining_Identifier => Anon_Access,
19130                 Type_Definition     => Type_Def);
19131
19132             Insert_Before (Typ_Decl, Decl);
19133             Analyze (Decl);
19134
19135             --  If an access to subprogram, create the extra formals
19136
19137             if Present (Acc_Def) then
19138                Create_Extra_Formals (Designated_Type (Anon_Access));
19139
19140             --  If an access to object, preserve entity of designated type,
19141             --  for ASIS use, before rewriting the component definition.
19142
19143             else
19144                declare
19145                   Desig : Entity_Id;
19146
19147                begin
19148                   Desig := Entity (Subtype_Indication (Type_Def));
19149
19150                   --  If the access definition is to the current  record,
19151                   --  the visible entity at this point is an  incomplete
19152                   --  type. Retrieve the full view to simplify  ASIS queries
19153
19154                   if Ekind (Desig) = E_Incomplete_Type then
19155                      Desig := Full_View (Desig);
19156                   end if;
19157
19158                   Set_Entity
19159                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
19160                end;
19161             end if;
19162
19163             Rewrite (Comp_Def,
19164               Make_Component_Definition (Loc,
19165                 Subtype_Indication =>
19166                New_Occurrence_Of (Anon_Access, Loc)));
19167
19168             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
19169                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
19170             else
19171                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
19172             end if;
19173
19174             Set_Is_Local_Anonymous_Access (Anon_Access);
19175          end if;
19176
19177          Next (Comp);
19178       end loop;
19179
19180       if Present (Variant_Part (Comp_List)) then
19181          declare
19182             V : Node_Id;
19183          begin
19184             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
19185             while Present (V) loop
19186                Check_Anonymous_Access_Components
19187                  (Typ_Decl, Typ, Prev, Component_List (V));
19188                Next_Non_Pragma (V);
19189             end loop;
19190          end;
19191       end if;
19192    end Check_Anonymous_Access_Components;
19193
19194    --------------------------------
19195    -- Preanalyze_Spec_Expression --
19196    --------------------------------
19197
19198    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
19199       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
19200    begin
19201       In_Spec_Expression := True;
19202       Preanalyze_And_Resolve (N, T);
19203       In_Spec_Expression := Save_In_Spec_Expression;
19204    end Preanalyze_Spec_Expression;
19205
19206    -----------------------------
19207    -- Record_Type_Declaration --
19208    -----------------------------
19209
19210    procedure Record_Type_Declaration
19211      (T    : Entity_Id;
19212       N    : Node_Id;
19213       Prev : Entity_Id)
19214    is
19215       Def       : constant Node_Id := Type_Definition (N);
19216       Is_Tagged : Boolean;
19217       Tag_Comp  : Entity_Id;
19218
19219    begin
19220       --  These flags must be initialized before calling Process_Discriminants
19221       --  because this routine makes use of them.
19222
19223       Set_Ekind             (T, E_Record_Type);
19224       Set_Etype             (T, T);
19225       Init_Size_Align       (T);
19226       Set_Interfaces        (T, No_Elist);
19227       Set_Stored_Constraint (T, No_Elist);
19228
19229       --  Normal case
19230
19231       if Ada_Version < Ada_2005
19232         or else not Interface_Present (Def)
19233       then
19234          if Limited_Present (Def) then
19235             Check_SPARK_Restriction ("limited is not allowed", N);
19236          end if;
19237
19238          if Abstract_Present (Def) then
19239             Check_SPARK_Restriction ("abstract is not allowed", N);
19240          end if;
19241
19242          --  The flag Is_Tagged_Type might have already been set by
19243          --  Find_Type_Name if it detected an error for declaration T. This
19244          --  arises in the case of private tagged types where the full view
19245          --  omits the word tagged.
19246
19247          Is_Tagged :=
19248            Tagged_Present (Def)
19249              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
19250
19251          Set_Is_Tagged_Type      (T, Is_Tagged);
19252          Set_Is_Limited_Record   (T, Limited_Present (Def));
19253
19254          --  Type is abstract if full declaration carries keyword, or if
19255          --  previous partial view did.
19256
19257          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
19258                                       or else Abstract_Present (Def));
19259
19260       else
19261          Check_SPARK_Restriction ("interface is not allowed", N);
19262
19263          Is_Tagged := True;
19264          Analyze_Interface_Declaration (T, Def);
19265
19266          if Present (Discriminant_Specifications (N)) then
19267             Error_Msg_N
19268               ("interface types cannot have discriminants",
19269                 Defining_Identifier
19270                   (First (Discriminant_Specifications (N))));
19271          end if;
19272       end if;
19273
19274       --  First pass: if there are self-referential access components,
19275       --  create the required anonymous access type declarations, and if
19276       --  need be an incomplete type declaration for T itself.
19277
19278       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
19279
19280       if Ada_Version >= Ada_2005
19281         and then Present (Interface_List (Def))
19282       then
19283          Check_Interfaces (N, Def);
19284
19285          declare
19286             Ifaces_List : Elist_Id;
19287
19288          begin
19289             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
19290             --  already in the parents.
19291
19292             Collect_Interfaces
19293               (T               => T,
19294                Ifaces_List     => Ifaces_List,
19295                Exclude_Parents => True);
19296
19297             Set_Interfaces (T, Ifaces_List);
19298          end;
19299       end if;
19300
19301       --  Records constitute a scope for the component declarations within.
19302       --  The scope is created prior to the processing of these declarations.
19303       --  Discriminants are processed first, so that they are visible when
19304       --  processing the other components. The Ekind of the record type itself
19305       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
19306
19307       --  Enter record scope
19308
19309       Push_Scope (T);
19310
19311       --  If an incomplete or private type declaration was already given for
19312       --  the type, then this scope already exists, and the discriminants have
19313       --  been declared within. We must verify that the full declaration
19314       --  matches the incomplete one.
19315
19316       Check_Or_Process_Discriminants (N, T, Prev);
19317
19318       Set_Is_Constrained     (T, not Has_Discriminants (T));
19319       Set_Has_Delayed_Freeze (T, True);
19320
19321       --  For tagged types add a manually analyzed component corresponding
19322       --  to the component _tag, the corresponding piece of tree will be
19323       --  expanded as part of the freezing actions if it is not a CPP_Class.
19324
19325       if Is_Tagged then
19326
19327          --  Do not add the tag unless we are in expansion mode
19328
19329          if Expander_Active then
19330             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
19331             Enter_Name (Tag_Comp);
19332
19333             Set_Ekind                     (Tag_Comp, E_Component);
19334             Set_Is_Tag                    (Tag_Comp);
19335             Set_Is_Aliased                (Tag_Comp);
19336             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
19337             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
19338             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
19339             Init_Component_Location       (Tag_Comp);
19340
19341             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
19342             --  implemented interfaces.
19343
19344             if Has_Interfaces (T) then
19345                Add_Interface_Tag_Components (N, T);
19346             end if;
19347          end if;
19348
19349          Make_Class_Wide_Type (T);
19350          Set_Direct_Primitive_Operations (T, New_Elmt_List);
19351       end if;
19352
19353       --  We must suppress range checks when processing record components in
19354       --  the presence of discriminants, since we don't want spurious checks to
19355       --  be generated during their analysis, but Suppress_Range_Checks flags
19356       --  must be reset the after processing the record definition.
19357
19358       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
19359       --  couldn't we just use the normal range check suppression method here.
19360       --  That would seem cleaner ???
19361
19362       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
19363          Set_Kill_Range_Checks (T, True);
19364          Record_Type_Definition (Def, Prev);
19365          Set_Kill_Range_Checks (T, False);
19366       else
19367          Record_Type_Definition (Def, Prev);
19368       end if;
19369
19370       --  Exit from record scope
19371
19372       End_Scope;
19373
19374       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
19375       --  the implemented interfaces and associate them an aliased entity.
19376
19377       if Is_Tagged
19378         and then not Is_Empty_List (Interface_List (Def))
19379       then
19380          Derive_Progenitor_Subprograms (T, T);
19381       end if;
19382    end Record_Type_Declaration;
19383
19384    ----------------------------
19385    -- Record_Type_Definition --
19386    ----------------------------
19387
19388    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
19389       Component          : Entity_Id;
19390       Ctrl_Components    : Boolean := False;
19391       Final_Storage_Only : Boolean;
19392       T                  : Entity_Id;
19393
19394    begin
19395       if Ekind (Prev_T) = E_Incomplete_Type then
19396          T := Full_View (Prev_T);
19397       else
19398          T := Prev_T;
19399       end if;
19400
19401       --  In SPARK, tagged types and type extensions may only be declared in
19402       --  the specification of library unit packages.
19403
19404       if Present (Def) and then Is_Tagged_Type (T) then
19405          declare
19406             Typ  : Node_Id;
19407             Ctxt : Node_Id;
19408
19409          begin
19410             if Nkind (Parent (Def)) = N_Full_Type_Declaration then
19411                Typ := Parent (Def);
19412             else
19413                pragma Assert
19414                  (Nkind (Parent (Def)) = N_Derived_Type_Definition);
19415                Typ := Parent (Parent (Def));
19416             end if;
19417
19418             Ctxt := Parent (Typ);
19419
19420             if Nkind (Ctxt) = N_Package_Body
19421               and then Nkind (Parent (Ctxt)) = N_Compilation_Unit
19422             then
19423                Check_SPARK_Restriction
19424                  ("type should be defined in package specification", Typ);
19425
19426             elsif Nkind (Ctxt) /= N_Package_Specification
19427               or else Nkind (Parent (Parent (Ctxt))) /= N_Compilation_Unit
19428             then
19429                Check_SPARK_Restriction
19430                  ("type should be defined in library unit package", Typ);
19431             end if;
19432          end;
19433       end if;
19434
19435       Final_Storage_Only := not Is_Controlled (T);
19436
19437       --  Ada 2005: check whether an explicit Limited is present in a derived
19438       --  type declaration.
19439
19440       if Nkind (Parent (Def)) = N_Derived_Type_Definition
19441         and then Limited_Present (Parent (Def))
19442       then
19443          Set_Is_Limited_Record (T);
19444       end if;
19445
19446       --  If the component list of a record type is defined by the reserved
19447       --  word null and there is no discriminant part, then the record type has
19448       --  no components and all records of the type are null records (RM 3.7)
19449       --  This procedure is also called to process the extension part of a
19450       --  record extension, in which case the current scope may have inherited
19451       --  components.
19452
19453       if No (Def)
19454         or else No (Component_List (Def))
19455         or else Null_Present (Component_List (Def))
19456       then
19457          if not Is_Tagged_Type (T) then
19458             Check_SPARK_Restriction ("non-tagged record cannot be null", Def);
19459          end if;
19460
19461       else
19462          Analyze_Declarations (Component_Items (Component_List (Def)));
19463
19464          if Present (Variant_Part (Component_List (Def))) then
19465             Check_SPARK_Restriction ("variant part is not allowed", Def);
19466             Analyze (Variant_Part (Component_List (Def)));
19467          end if;
19468       end if;
19469
19470       --  After completing the semantic analysis of the record definition,
19471       --  record components, both new and inherited, are accessible. Set their
19472       --  kind accordingly. Exclude malformed itypes from illegal declarations,
19473       --  whose Ekind may be void.
19474
19475       Component := First_Entity (Current_Scope);
19476       while Present (Component) loop
19477          if Ekind (Component) = E_Void
19478            and then not Is_Itype (Component)
19479          then
19480             Set_Ekind (Component, E_Component);
19481             Init_Component_Location (Component);
19482          end if;
19483
19484          if Has_Task (Etype (Component)) then
19485             Set_Has_Task (T);
19486          end if;
19487
19488          if Ekind (Component) /= E_Component then
19489             null;
19490
19491          --  Do not set Has_Controlled_Component on a class-wide equivalent
19492          --  type. See Make_CW_Equivalent_Type.
19493
19494          elsif not Is_Class_Wide_Equivalent_Type (T)
19495            and then (Has_Controlled_Component (Etype (Component))
19496                       or else (Chars (Component) /= Name_uParent
19497                                 and then Is_Controlled (Etype (Component))))
19498          then
19499             Set_Has_Controlled_Component (T, True);
19500             Final_Storage_Only :=
19501               Final_Storage_Only
19502                 and then Finalize_Storage_Only (Etype (Component));
19503             Ctrl_Components := True;
19504          end if;
19505
19506          Next_Entity (Component);
19507       end loop;
19508
19509       --  A Type is Finalize_Storage_Only only if all its controlled components
19510       --  are also.
19511
19512       if Ctrl_Components then
19513          Set_Finalize_Storage_Only (T, Final_Storage_Only);
19514       end if;
19515
19516       --  Place reference to end record on the proper entity, which may
19517       --  be a partial view.
19518
19519       if Present (Def) then
19520          Process_End_Label (Def, 'e', Prev_T);
19521       end if;
19522    end Record_Type_Definition;
19523
19524    ------------------------
19525    -- Replace_Components --
19526    ------------------------
19527
19528    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
19529       function Process (N : Node_Id) return Traverse_Result;
19530
19531       -------------
19532       -- Process --
19533       -------------
19534
19535       function Process (N : Node_Id) return Traverse_Result is
19536          Comp : Entity_Id;
19537
19538       begin
19539          if Nkind (N) = N_Discriminant_Specification then
19540             Comp := First_Discriminant (Typ);
19541             while Present (Comp) loop
19542                if Chars (Comp) = Chars (Defining_Identifier (N)) then
19543                   Set_Defining_Identifier (N, Comp);
19544                   exit;
19545                end if;
19546
19547                Next_Discriminant (Comp);
19548             end loop;
19549
19550          elsif Nkind (N) = N_Component_Declaration then
19551             Comp := First_Component (Typ);
19552             while Present (Comp) loop
19553                if Chars (Comp) = Chars (Defining_Identifier (N)) then
19554                   Set_Defining_Identifier (N, Comp);
19555                   exit;
19556                end if;
19557
19558                Next_Component (Comp);
19559             end loop;
19560          end if;
19561
19562          return OK;
19563       end Process;
19564
19565       procedure Replace is new Traverse_Proc (Process);
19566
19567    --  Start of processing for Replace_Components
19568
19569    begin
19570       Replace (Decl);
19571    end Replace_Components;
19572
19573    -------------------------------
19574    -- Set_Completion_Referenced --
19575    -------------------------------
19576
19577    procedure Set_Completion_Referenced (E : Entity_Id) is
19578    begin
19579       --  If in main unit, mark entity that is a completion as referenced,
19580       --  warnings go on the partial view when needed.
19581
19582       if In_Extended_Main_Source_Unit (E) then
19583          Set_Referenced (E);
19584       end if;
19585    end Set_Completion_Referenced;
19586
19587    ---------------------
19588    -- Set_Fixed_Range --
19589    ---------------------
19590
19591    --  The range for fixed-point types is complicated by the fact that we
19592    --  do not know the exact end points at the time of the declaration. This
19593    --  is true for three reasons:
19594
19595    --     A size clause may affect the fudging of the end-points.
19596    --     A small clause may affect the values of the end-points.
19597    --     We try to include the end-points if it does not affect the size.
19598
19599    --  This means that the actual end-points must be established at the
19600    --  point when the type is frozen. Meanwhile, we first narrow the range
19601    --  as permitted (so that it will fit if necessary in a small specified
19602    --  size), and then build a range subtree with these narrowed bounds.
19603    --  Set_Fixed_Range constructs the range from real literal values, and
19604    --  sets the range as the Scalar_Range of the given fixed-point type entity.
19605
19606    --  The parent of this range is set to point to the entity so that it is
19607    --  properly hooked into the tree (unlike normal Scalar_Range entries for
19608    --  other scalar types, which are just pointers to the range in the
19609    --  original tree, this would otherwise be an orphan).
19610
19611    --  The tree is left unanalyzed. When the type is frozen, the processing
19612    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
19613    --  analyzed, and uses this as an indication that it should complete
19614    --  work on the range (it will know the final small and size values).
19615
19616    procedure Set_Fixed_Range
19617      (E   : Entity_Id;
19618       Loc : Source_Ptr;
19619       Lo  : Ureal;
19620       Hi  : Ureal)
19621    is
19622       S : constant Node_Id :=
19623             Make_Range (Loc,
19624               Low_Bound  => Make_Real_Literal (Loc, Lo),
19625               High_Bound => Make_Real_Literal (Loc, Hi));
19626    begin
19627       Set_Scalar_Range (E, S);
19628       Set_Parent (S, E);
19629
19630       --  Before the freeze point, the bounds of a fixed point are universal
19631       --  and carry the corresponding type.
19632
19633       Set_Etype (Low_Bound (S),  Universal_Real);
19634       Set_Etype (High_Bound (S), Universal_Real);
19635    end Set_Fixed_Range;
19636
19637    ----------------------------------
19638    -- Set_Scalar_Range_For_Subtype --
19639    ----------------------------------
19640
19641    procedure Set_Scalar_Range_For_Subtype
19642      (Def_Id : Entity_Id;
19643       R      : Node_Id;
19644       Subt   : Entity_Id)
19645    is
19646       Kind : constant Entity_Kind :=  Ekind (Def_Id);
19647
19648    begin
19649       --  Defend against previous error
19650
19651       if Nkind (R) = N_Error then
19652          return;
19653       end if;
19654
19655       Set_Scalar_Range (Def_Id, R);
19656
19657       --  We need to link the range into the tree before resolving it so
19658       --  that types that are referenced, including importantly the subtype
19659       --  itself, are properly frozen (Freeze_Expression requires that the
19660       --  expression be properly linked into the tree). Of course if it is
19661       --  already linked in, then we do not disturb the current link.
19662
19663       if No (Parent (R)) then
19664          Set_Parent (R, Def_Id);
19665       end if;
19666
19667       --  Reset the kind of the subtype during analysis of the range, to
19668       --  catch possible premature use in the bounds themselves.
19669
19670       Set_Ekind (Def_Id, E_Void);
19671       Process_Range_Expr_In_Decl (R, Subt);
19672       Set_Ekind (Def_Id, Kind);
19673    end Set_Scalar_Range_For_Subtype;
19674
19675    --------------------------------------------------------
19676    -- Set_Stored_Constraint_From_Discriminant_Constraint --
19677    --------------------------------------------------------
19678
19679    procedure Set_Stored_Constraint_From_Discriminant_Constraint
19680      (E : Entity_Id)
19681    is
19682    begin
19683       --  Make sure set if encountered during Expand_To_Stored_Constraint
19684
19685       Set_Stored_Constraint (E, No_Elist);
19686
19687       --  Give it the right value
19688
19689       if Is_Constrained (E) and then Has_Discriminants (E) then
19690          Set_Stored_Constraint (E,
19691            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
19692       end if;
19693    end Set_Stored_Constraint_From_Discriminant_Constraint;
19694
19695    -------------------------------------
19696    -- Signed_Integer_Type_Declaration --
19697    -------------------------------------
19698
19699    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
19700       Implicit_Base : Entity_Id;
19701       Base_Typ      : Entity_Id;
19702       Lo_Val        : Uint;
19703       Hi_Val        : Uint;
19704       Errs          : Boolean := False;
19705       Lo            : Node_Id;
19706       Hi            : Node_Id;
19707
19708       function Can_Derive_From (E : Entity_Id) return Boolean;
19709       --  Determine whether given bounds allow derivation from specified type
19710
19711       procedure Check_Bound (Expr : Node_Id);
19712       --  Check bound to make sure it is integral and static. If not, post
19713       --  appropriate error message and set Errs flag
19714
19715       ---------------------
19716       -- Can_Derive_From --
19717       ---------------------
19718
19719       --  Note we check both bounds against both end values, to deal with
19720       --  strange types like ones with a range of 0 .. -12341234.
19721
19722       function Can_Derive_From (E : Entity_Id) return Boolean is
19723          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
19724          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
19725       begin
19726          return Lo <= Lo_Val and then Lo_Val <= Hi
19727                   and then
19728                 Lo <= Hi_Val and then Hi_Val <= Hi;
19729       end Can_Derive_From;
19730
19731       -----------------
19732       -- Check_Bound --
19733       -----------------
19734
19735       procedure Check_Bound (Expr : Node_Id) is
19736       begin
19737          --  If a range constraint is used as an integer type definition, each
19738          --  bound of the range must be defined by a static expression of some
19739          --  integer type, but the two bounds need not have the same integer
19740          --  type (Negative bounds are allowed.) (RM 3.5.4)
19741
19742          if not Is_Integer_Type (Etype (Expr)) then
19743             Error_Msg_N
19744               ("integer type definition bounds must be of integer type", Expr);
19745             Errs := True;
19746
19747          elsif not Is_OK_Static_Expression (Expr) then
19748             Flag_Non_Static_Expr
19749               ("non-static expression used for integer type bound!", Expr);
19750             Errs := True;
19751
19752          --  The bounds are folded into literals, and we set their type to be
19753          --  universal, to avoid typing difficulties: we cannot set the type
19754          --  of the literal to the new type, because this would be a forward
19755          --  reference for the back end,  and if the original type is user-
19756          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
19757
19758          else
19759             if Is_Entity_Name (Expr) then
19760                Fold_Uint (Expr, Expr_Value (Expr), True);
19761             end if;
19762
19763             Set_Etype (Expr, Universal_Integer);
19764          end if;
19765       end Check_Bound;
19766
19767    --  Start of processing for Signed_Integer_Type_Declaration
19768
19769    begin
19770       --  Create an anonymous base type
19771
19772       Implicit_Base :=
19773         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
19774
19775       --  Analyze and check the bounds, they can be of any integer type
19776
19777       Lo := Low_Bound (Def);
19778       Hi := High_Bound (Def);
19779
19780       --  Arbitrarily use Integer as the type if either bound had an error
19781
19782       if Hi = Error or else Lo = Error then
19783          Base_Typ := Any_Integer;
19784          Set_Error_Posted (T, True);
19785
19786       --  Here both bounds are OK expressions
19787
19788       else
19789          Analyze_And_Resolve (Lo, Any_Integer);
19790          Analyze_And_Resolve (Hi, Any_Integer);
19791
19792          Check_Bound (Lo);
19793          Check_Bound (Hi);
19794
19795          if Errs then
19796             Hi := Type_High_Bound (Standard_Long_Long_Integer);
19797             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
19798          end if;
19799
19800          --  Find type to derive from
19801
19802          Lo_Val := Expr_Value (Lo);
19803          Hi_Val := Expr_Value (Hi);
19804
19805          if Can_Derive_From (Standard_Short_Short_Integer) then
19806             Base_Typ := Base_Type (Standard_Short_Short_Integer);
19807
19808          elsif Can_Derive_From (Standard_Short_Integer) then
19809             Base_Typ := Base_Type (Standard_Short_Integer);
19810
19811          elsif Can_Derive_From (Standard_Integer) then
19812             Base_Typ := Base_Type (Standard_Integer);
19813
19814          elsif Can_Derive_From (Standard_Long_Integer) then
19815             Base_Typ := Base_Type (Standard_Long_Integer);
19816
19817          elsif Can_Derive_From (Standard_Long_Long_Integer) then
19818             Base_Typ := Base_Type (Standard_Long_Long_Integer);
19819
19820          else
19821             Base_Typ := Base_Type (Standard_Long_Long_Integer);
19822             Error_Msg_N ("integer type definition bounds out of range", Def);
19823             Hi := Type_High_Bound (Standard_Long_Long_Integer);
19824             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
19825          end if;
19826       end if;
19827
19828       --  Complete both implicit base and declared first subtype entities
19829
19830       Set_Etype          (Implicit_Base, Base_Typ);
19831       Set_Size_Info      (Implicit_Base,                (Base_Typ));
19832       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
19833       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
19834
19835       Set_Ekind          (T, E_Signed_Integer_Subtype);
19836       Set_Etype          (T, Implicit_Base);
19837
19838       --  In formal verification mode, restrict the base type's range to the
19839       --  minimum allowed by RM 3.5.4, namely the smallest symmetric range
19840       --  around zero with a possible extra negative value that contains the
19841       --  subtype range. Keep Size, RM_Size and First_Rep_Item info, which
19842       --  should not be relied upon in formal verification.
19843
19844       if Strict_Alfa_Mode then
19845          declare
19846             Sym_Hi_Val : Uint;
19847             Sym_Lo_Val : Uint;
19848             Dloc       : constant Source_Ptr := Sloc (Def);
19849             Lbound     : Node_Id;
19850             Ubound     : Node_Id;
19851             Bounds     : Node_Id;
19852
19853          begin
19854             --  If the subtype range is empty, the smallest base type range
19855             --  is the symmetric range around zero containing Lo_Val and
19856             --  Hi_Val.
19857
19858             if UI_Gt (Lo_Val, Hi_Val) then
19859                Sym_Hi_Val := UI_Max (UI_Abs (Lo_Val), UI_Abs (Hi_Val));
19860                Sym_Lo_Val := UI_Negate (Sym_Hi_Val);
19861
19862                --  Otherwise, if the subtype range is not empty and Hi_Val has
19863                --  the largest absolute value, Hi_Val is non negative and the
19864                --  smallest base type range is the symmetric range around zero
19865                --  containing Hi_Val.
19866
19867             elsif UI_Le (UI_Abs (Lo_Val), UI_Abs (Hi_Val)) then
19868                Sym_Hi_Val := Hi_Val;
19869                Sym_Lo_Val := UI_Negate (Hi_Val);
19870
19871                --  Otherwise, the subtype range is not empty, Lo_Val has the
19872                --  strictly largest absolute value, Lo_Val is negative and the
19873                --  smallest base type range is the symmetric range around zero
19874                --  with an extra negative value Lo_Val.
19875
19876             else
19877                Sym_Lo_Val := Lo_Val;
19878                Sym_Hi_Val := UI_Sub (UI_Negate (Lo_Val), Uint_1);
19879             end if;
19880
19881             Lbound := Make_Integer_Literal (Dloc, Sym_Lo_Val);
19882             Ubound := Make_Integer_Literal (Dloc, Sym_Hi_Val);
19883             Set_Is_Static_Expression (Lbound);
19884             Set_Is_Static_Expression (Ubound);
19885             Analyze_And_Resolve (Lbound, Any_Integer);
19886             Analyze_And_Resolve (Ubound, Any_Integer);
19887
19888             Bounds := Make_Range (Dloc, Lbound, Ubound);
19889             Set_Etype (Bounds, Base_Typ);
19890
19891             Set_Scalar_Range (Implicit_Base, Bounds);
19892          end;
19893
19894       else
19895          Set_Scalar_Range (Implicit_Base, Scalar_Range (Base_Typ));
19896       end if;
19897
19898       Set_Size_Info      (T,                (Implicit_Base));
19899       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
19900       Set_Scalar_Range   (T, Def);
19901       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
19902       Set_Is_Constrained (T);
19903    end Signed_Integer_Type_Declaration;
19904
19905 end Sem_Ch3;