8074775dfd067949a2eb7d3d4edc9795277ffb8e
[platform/upstream/gcc.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-2013, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Elists;   use Elists;
31 with Einfo;    use Einfo;
32 with Errout;   use Errout;
33 with Eval_Fat; use Eval_Fat;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Disp; use Exp_Disp;
37 with Exp_Dist; use Exp_Dist;
38 with Exp_Pakd; use Exp_Pakd;
39 with Exp_Tss;  use Exp_Tss;
40 with Exp_Util; use Exp_Util;
41 with Fname;    use Fname;
42 with Freeze;   use Freeze;
43 with Itypes;   use Itypes;
44 with Layout;   use Layout;
45 with Lib;      use Lib;
46 with Lib.Xref; use Lib.Xref;
47 with Namet;    use Namet;
48 with Nmake;    use Nmake;
49 with Opt;      use Opt;
50 with Restrict; use Restrict;
51 with Rident;   use Rident;
52 with Rtsfind;  use Rtsfind;
53 with Sem;      use Sem;
54 with Sem_Aux;  use Sem_Aux;
55 with Sem_Case; use Sem_Case;
56 with Sem_Cat;  use Sem_Cat;
57 with Sem_Ch6;  use Sem_Ch6;
58 with Sem_Ch7;  use Sem_Ch7;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch13; use Sem_Ch13;
61 with Sem_Dim;  use Sem_Dim;
62 with Sem_Disp; use Sem_Disp;
63 with Sem_Dist; use Sem_Dist;
64 with Sem_Elim; use Sem_Elim;
65 with Sem_Eval; use Sem_Eval;
66 with Sem_Mech; use Sem_Mech;
67 with Sem_Prag; use Sem_Prag;
68 with Sem_Res;  use Sem_Res;
69 with Sem_Smem; use Sem_Smem;
70 with Sem_Type; use Sem_Type;
71 with Sem_Util; use Sem_Util;
72 with Sem_Warn; use Sem_Warn;
73 with Stand;    use Stand;
74 with Sinfo;    use Sinfo;
75 with Sinput;   use Sinput;
76 with Snames;   use Snames;
77 with Targparm; use Targparm;
78 with Tbuild;   use Tbuild;
79 with Ttypes;   use Ttypes;
80 with Uintp;    use Uintp;
81 with Urealp;   use Urealp;
82
83 package body Sem_Ch3 is
84
85    -----------------------
86    -- Local Subprograms --
87    -----------------------
88
89    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
90    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
91    --  abstract interface types implemented by a record type or a derived
92    --  record type.
93
94    procedure Build_Derived_Type
95      (N             : Node_Id;
96       Parent_Type   : Entity_Id;
97       Derived_Type  : Entity_Id;
98       Is_Completion : Boolean;
99       Derive_Subps  : Boolean := True);
100    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
101    --  the N_Full_Type_Declaration node containing the derived type definition.
102    --  Parent_Type is the entity for the parent type in the derived type
103    --  definition and Derived_Type the actual derived type. Is_Completion must
104    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
105    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
106    --  completion of a private type declaration. If Is_Completion is set to
107    --  True, N is the completion of a private type declaration and Derived_Type
108    --  is different from the defining identifier inside N (i.e. Derived_Type /=
109    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
110    --  subprograms should be derived. The only case where this parameter is
111    --  False is when Build_Derived_Type is recursively called to process an
112    --  implicit derived full type for a type derived from a private type (in
113    --  that case the subprograms must only be derived for the private view of
114    --  the type).
115    --
116    --  ??? These flags need a bit of re-examination and re-documentation:
117    --  ???  are they both necessary (both seem related to the recursion)?
118
119    procedure Build_Derived_Access_Type
120      (N            : Node_Id;
121       Parent_Type  : Entity_Id;
122       Derived_Type : Entity_Id);
123    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
124    --  create an implicit base if the parent type is constrained or if the
125    --  subtype indication has a constraint.
126
127    procedure Build_Derived_Array_Type
128      (N            : Node_Id;
129       Parent_Type  : Entity_Id;
130       Derived_Type : Entity_Id);
131    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
132    --  create an implicit base if the parent type is constrained or if the
133    --  subtype indication has a constraint.
134
135    procedure Build_Derived_Concurrent_Type
136      (N            : Node_Id;
137       Parent_Type  : Entity_Id;
138       Derived_Type : Entity_Id);
139    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
140    --  protected type, inherit entries and protected subprograms, check
141    --  legality of discriminant constraints if any.
142
143    procedure Build_Derived_Enumeration_Type
144      (N            : Node_Id;
145       Parent_Type  : Entity_Id;
146       Derived_Type : Entity_Id);
147    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
148    --  type, we must create a new list of literals. Types derived from
149    --  Character and [Wide_]Wide_Character are special-cased.
150
151    procedure Build_Derived_Numeric_Type
152      (N            : Node_Id;
153       Parent_Type  : Entity_Id;
154       Derived_Type : Entity_Id);
155    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
156    --  an anonymous base type, and propagate constraint to subtype if needed.
157
158    procedure Build_Derived_Private_Type
159      (N             : Node_Id;
160       Parent_Type   : Entity_Id;
161       Derived_Type  : Entity_Id;
162       Is_Completion : Boolean;
163       Derive_Subps  : Boolean := True);
164    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
165    --  because the parent may or may not have a completion, and the derivation
166    --  may itself be a completion.
167
168    procedure Build_Derived_Record_Type
169      (N            : Node_Id;
170       Parent_Type  : Entity_Id;
171       Derived_Type : Entity_Id;
172       Derive_Subps : Boolean := True);
173    --  Subsidiary procedure used for tagged and untagged record types
174    --  by Build_Derived_Type and Analyze_Private_Extension_Declaration.
175    --  All parameters are as in Build_Derived_Type except that N, in
176    --  addition to being an N_Full_Type_Declaration node, can also be an
177    --  N_Private_Extension_Declaration node. See the definition of this routine
178    --  for much more info. Derive_Subps indicates whether subprograms should be
179    --  derived from the parent type. The only case where Derive_Subps is False
180    --  is for an implicit derived full type for a type derived from a private
181    --  type (see Build_Derived_Type).
182
183    procedure Build_Discriminal (Discrim : Entity_Id);
184    --  Create the discriminal corresponding to discriminant Discrim, that is
185    --  the parameter corresponding to Discrim to be used in initialization
186    --  procedures for the type where Discrim is a discriminant. Discriminals
187    --  are not used during semantic analysis, and are not fully defined
188    --  entities until expansion. Thus they are not given a scope until
189    --  initialization procedures are built.
190
191    function Build_Discriminant_Constraints
192      (T           : Entity_Id;
193       Def         : Node_Id;
194       Derived_Def : Boolean := False) return Elist_Id;
195    --  Validate discriminant constraints and return the list of the constraints
196    --  in order of discriminant declarations, where T is the discriminated
197    --  unconstrained type. Def is the N_Subtype_Indication node where the
198    --  discriminants constraints for T are specified. Derived_Def is True
199    --  when building the discriminant constraints in a derived type definition
200    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
201    --  type and Def is the constraint "(xxx)" on T and this routine sets the
202    --  Corresponding_Discriminant field of the discriminants in the derived
203    --  type D to point to the corresponding discriminants in the parent type T.
204
205    procedure Build_Discriminated_Subtype
206      (T           : Entity_Id;
207       Def_Id      : Entity_Id;
208       Elist       : Elist_Id;
209       Related_Nod : Node_Id;
210       For_Access  : Boolean := False);
211    --  Subsidiary procedure to Constrain_Discriminated_Type and to
212    --  Process_Incomplete_Dependents. Given
213    --
214    --     T (a possibly discriminated base type)
215    --     Def_Id (a very partially built subtype for T),
216    --
217    --  the call completes Def_Id to be the appropriate E_*_Subtype.
218    --
219    --  The Elist is the list of discriminant constraints if any (it is set
220    --  to No_Elist if T is not a discriminated type, and to an empty list if
221    --  T has discriminants but there are no discriminant constraints). The
222    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
223    --  The For_Access says whether or not this subtype is really constraining
224    --  an access type. That is its sole purpose is the designated type of an
225    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
226    --  is built to avoid freezing T when the access subtype is frozen.
227
228    function Build_Scalar_Bound
229      (Bound : Node_Id;
230       Par_T : Entity_Id;
231       Der_T : Entity_Id) return Node_Id;
232    --  The bounds of a derived scalar type are conversions of the bounds of
233    --  the parent type. Optimize the representation if the bounds are literals.
234    --  Needs a more complete spec--what are the parameters exactly, and what
235    --  exactly is the returned value, and how is Bound affected???
236
237    procedure Build_Underlying_Full_View
238      (N   : Node_Id;
239       Typ : Entity_Id;
240       Par : Entity_Id);
241    --  If the completion of a private type is itself derived from a private
242    --  type, or if the full view of a private subtype is itself private, the
243    --  back-end has no way to compute the actual size of this type. We build
244    --  an internal subtype declaration of the proper parent type to convey
245    --  this information. This extra mechanism is needed because a full
246    --  view cannot itself have a full view (it would get clobbered during
247    --  view exchanges).
248
249    procedure Check_Access_Discriminant_Requires_Limited
250      (D   : Node_Id;
251       Loc : Node_Id);
252    --  Check the restriction that the type to which an access discriminant
253    --  belongs must be a concurrent type or a descendant of a type with
254    --  the reserved word 'limited' in its declaration.
255
256    procedure Check_Anonymous_Access_Components
257       (Typ_Decl  : Node_Id;
258        Typ       : Entity_Id;
259        Prev      : Entity_Id;
260        Comp_List : Node_Id);
261    --  Ada 2005 AI-382: an access component in a record definition can refer to
262    --  the enclosing record, in which case it denotes the type itself, and not
263    --  the current instance of the type. We create an anonymous access type for
264    --  the component, and flag it as an access to a component, so accessibility
265    --  checks are properly performed on it. The declaration of the access type
266    --  is placed ahead of that of the record to prevent order-of-elaboration
267    --  circularity issues in Gigi. We create an incomplete type for the record
268    --  declaration, which is the designated type of the anonymous access.
269
270    procedure Check_Delta_Expression (E : Node_Id);
271    --  Check that the expression represented by E is suitable for use as a
272    --  delta expression, i.e. it is of real type and is static.
273
274    procedure Check_Digits_Expression (E : Node_Id);
275    --  Check that the expression represented by E is suitable for use as a
276    --  digits expression, i.e. it is of integer type, positive and static.
277
278    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
279    --  Validate the initialization of an object declaration. T is the required
280    --  type, and Exp is the initialization expression.
281
282    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
283    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
284
285    procedure Check_Or_Process_Discriminants
286      (N    : Node_Id;
287       T    : Entity_Id;
288       Prev : Entity_Id := Empty);
289    --  If N is the full declaration of the completion T of an incomplete or
290    --  private type, check its discriminants (which are already known to be
291    --  conformant with those of the partial view, see Find_Type_Name),
292    --  otherwise process them. Prev is the entity of the partial declaration,
293    --  if any.
294
295    procedure Check_Real_Bound (Bound : Node_Id);
296    --  Check given bound for being of real type and static. If not, post an
297    --  appropriate message, and rewrite the bound with the real literal zero.
298
299    procedure Constant_Redeclaration
300      (Id : Entity_Id;
301       N  : Node_Id;
302       T  : out Entity_Id);
303    --  Various checks on legality of full declaration of deferred constant.
304    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
305    --  node. The caller has not yet set any attributes of this entity.
306
307    function Contain_Interface
308      (Iface  : Entity_Id;
309       Ifaces : Elist_Id) return Boolean;
310    --  Ada 2005: Determine whether Iface is present in the list Ifaces
311
312    procedure Convert_Scalar_Bounds
313      (N            : Node_Id;
314       Parent_Type  : Entity_Id;
315       Derived_Type : Entity_Id;
316       Loc          : Source_Ptr);
317    --  For derived scalar types, convert the bounds in the type definition to
318    --  the derived type, and complete their analysis. Given a constraint of the
319    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
320    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
321    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
322    --  subtype are conversions of those bounds to the derived_type, so that
323    --  their typing is consistent.
324
325    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
326    --  Copies attributes from array base type T2 to array base type T1. Copies
327    --  only attributes that apply to base types, but not subtypes.
328
329    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
330    --  Copies attributes from array subtype T2 to array subtype T1. Copies
331    --  attributes that apply to both subtypes and base types.
332
333    procedure Create_Constrained_Components
334      (Subt        : Entity_Id;
335       Decl_Node   : Node_Id;
336       Typ         : Entity_Id;
337       Constraints : Elist_Id);
338    --  Build the list of entities for a constrained discriminated record
339    --  subtype. If a component depends on a discriminant, replace its subtype
340    --  using the discriminant values in the discriminant constraint. Subt
341    --  is the defining identifier for the subtype whose list of constrained
342    --  entities we will create. Decl_Node is the type declaration node where
343    --  we will attach all the itypes created. Typ is the base discriminated
344    --  type for the subtype Subt. Constraints is the list of discriminant
345    --  constraints for Typ.
346
347    function Constrain_Component_Type
348      (Comp            : Entity_Id;
349       Constrained_Typ : Entity_Id;
350       Related_Node    : Node_Id;
351       Typ             : Entity_Id;
352       Constraints     : Elist_Id) return Entity_Id;
353    --  Given a discriminated base type Typ, a list of discriminant constraint
354    --  Constraints for Typ and a component of Typ, with type Compon_Type,
355    --  create and return the type corresponding to Compon_type where all
356    --  discriminant references are replaced with the corresponding constraint.
357    --  If no discriminant references occur in Compon_Typ then return it as is.
358    --  Constrained_Typ is the final constrained subtype to which the
359    --  constrained Compon_Type belongs. Related_Node is the node where we will
360    --  attach all the itypes created.
361    --
362    --  Above description is confused, what is Compon_Type???
363
364    procedure Constrain_Access
365      (Def_Id      : in out Entity_Id;
366       S           : Node_Id;
367       Related_Nod : Node_Id);
368    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
369    --  an anonymous type created for a subtype indication. In that case it is
370    --  created in the procedure and attached to Related_Nod.
371
372    procedure Constrain_Array
373      (Def_Id      : in out Entity_Id;
374       SI          : Node_Id;
375       Related_Nod : Node_Id;
376       Related_Id  : Entity_Id;
377       Suffix      : Character);
378    --  Apply a list of index constraints to an unconstrained array type. The
379    --  first parameter is the entity for the resulting subtype. A value of
380    --  Empty for Def_Id indicates that an implicit type must be created, but
381    --  creation is delayed (and must be done by this procedure) because other
382    --  subsidiary implicit types must be created first (which is why Def_Id
383    --  is an in/out parameter). The second parameter is a subtype indication
384    --  node for the constrained array to be created (e.g. something of the
385    --  form string (1 .. 10)). Related_Nod gives the place where this type
386    --  has to be inserted in the tree. The Related_Id and Suffix parameters
387    --  are used to build the associated Implicit type name.
388
389    procedure Constrain_Concurrent
390      (Def_Id      : in out Entity_Id;
391       SI          : Node_Id;
392       Related_Nod : Node_Id;
393       Related_Id  : Entity_Id;
394       Suffix      : Character);
395    --  Apply list of discriminant constraints to an unconstrained concurrent
396    --  type.
397    --
398    --    SI is the N_Subtype_Indication node containing the constraint and
399    --    the unconstrained type to constrain.
400    --
401    --    Def_Id is the entity for the resulting constrained subtype. A value
402    --    of Empty for Def_Id indicates that an implicit type must be created,
403    --    but creation is delayed (and must be done by this procedure) because
404    --    other subsidiary implicit types must be created first (which is why
405    --    Def_Id is an in/out parameter).
406    --
407    --    Related_Nod gives the place where this type has to be inserted
408    --    in the tree
409    --
410    --  The last two arguments are used to create its external name if needed.
411
412    function Constrain_Corresponding_Record
413      (Prot_Subt   : Entity_Id;
414       Corr_Rec    : Entity_Id;
415       Related_Nod : Node_Id;
416       Related_Id  : Entity_Id) return Entity_Id;
417    --  When constraining a protected type or task type with discriminants,
418    --  constrain the corresponding record with the same discriminant values.
419
420    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
421    --  Constrain a decimal fixed point type with a digits constraint and/or a
422    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
423
424    procedure Constrain_Discriminated_Type
425      (Def_Id      : Entity_Id;
426       S           : Node_Id;
427       Related_Nod : Node_Id;
428       For_Access  : Boolean := False);
429    --  Process discriminant constraints of composite type. Verify that values
430    --  have been provided for all discriminants, that the original type is
431    --  unconstrained, and that the types of the supplied expressions match
432    --  the discriminant types. The first three parameters are like in routine
433    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
434    --  of For_Access.
435
436    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
437    --  Constrain an enumeration type with a range constraint. This is identical
438    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
439
440    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
441    --  Constrain a floating point type with either a digits constraint
442    --  and/or a range constraint, building a E_Floating_Point_Subtype.
443
444    procedure Constrain_Index
445      (Index        : Node_Id;
446       S            : Node_Id;
447       Related_Nod  : Node_Id;
448       Related_Id   : Entity_Id;
449       Suffix       : Character;
450       Suffix_Index : Nat);
451    --  Process an index constraint S in a constrained array declaration. The
452    --  constraint can be a subtype name, or a range with or without an explicit
453    --  subtype mark. The index is the corresponding index of the unconstrained
454    --  array. The Related_Id and Suffix parameters are used to build the
455    --  associated Implicit type name.
456
457    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
458    --  Build subtype of a signed or modular integer type
459
460    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
461    --  Constrain an ordinary fixed point type with a range constraint, and
462    --  build an E_Ordinary_Fixed_Point_Subtype entity.
463
464    procedure Copy_And_Swap (Priv, Full : Entity_Id);
465    --  Copy the Priv entity into the entity of its full declaration then swap
466    --  the two entities in such a manner that the former private type is now
467    --  seen as a full type.
468
469    procedure Decimal_Fixed_Point_Type_Declaration
470      (T   : Entity_Id;
471       Def : Node_Id);
472    --  Create a new decimal fixed point type, and apply the constraint to
473    --  obtain a subtype of this new type.
474
475    procedure Complete_Private_Subtype
476      (Priv        : Entity_Id;
477       Full        : Entity_Id;
478       Full_Base   : Entity_Id;
479       Related_Nod : Node_Id);
480    --  Complete the implicit full view of a private subtype by setting the
481    --  appropriate semantic fields. If the full view of the parent is a record
482    --  type, build constrained components of subtype.
483
484    procedure Derive_Progenitor_Subprograms
485      (Parent_Type : Entity_Id;
486       Tagged_Type : Entity_Id);
487    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
488    --  operations of progenitors of Tagged_Type, and replace the subsidiary
489    --  subtypes with Tagged_Type, to build the specs of the inherited interface
490    --  primitives. The derived primitives are aliased to those of the
491    --  interface. This routine takes care also of transferring to the full view
492    --  subprograms associated with the partial view of Tagged_Type that cover
493    --  interface primitives.
494
495    procedure Derived_Standard_Character
496      (N             : Node_Id;
497       Parent_Type   : Entity_Id;
498       Derived_Type  : Entity_Id);
499    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
500    --  derivations from types Standard.Character and Standard.Wide_Character.
501
502    procedure Derived_Type_Declaration
503      (T             : Entity_Id;
504       N             : Node_Id;
505       Is_Completion : Boolean);
506    --  Process a derived type declaration. Build_Derived_Type is invoked
507    --  to process the actual derived type definition. Parameters N and
508    --  Is_Completion have the same meaning as in Build_Derived_Type.
509    --  T is the N_Defining_Identifier for the entity defined in the
510    --  N_Full_Type_Declaration node N, that is T is the derived type.
511
512    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
513    --  Insert each literal in symbol table, as an overloadable identifier. Each
514    --  enumeration type is mapped into a sequence of integers, and each literal
515    --  is defined as a constant with integer value. If any of the literals are
516    --  character literals, the type is a character type, which means that
517    --  strings are legal aggregates for arrays of components of the type.
518
519    function Expand_To_Stored_Constraint
520      (Typ        : Entity_Id;
521       Constraint : Elist_Id) return Elist_Id;
522    --  Given a constraint (i.e. a list of expressions) on the discriminants of
523    --  Typ, expand it into a constraint on the stored discriminants and return
524    --  the new list of expressions constraining the stored discriminants.
525
526    function Find_Type_Of_Object
527      (Obj_Def     : Node_Id;
528       Related_Nod : Node_Id) return Entity_Id;
529    --  Get type entity for object referenced by Obj_Def, attaching the
530    --  implicit types generated to Related_Nod
531
532    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
533    --  Create a new float and apply the constraint to obtain subtype of it
534
535    function Has_Range_Constraint (N : Node_Id) return Boolean;
536    --  Given an N_Subtype_Indication node N, return True if a range constraint
537    --  is present, either directly, or as part of a digits or delta constraint.
538    --  In addition, a digits constraint in the decimal case returns True, since
539    --  it establishes a default range if no explicit range is present.
540
541    function Inherit_Components
542      (N             : Node_Id;
543       Parent_Base   : Entity_Id;
544       Derived_Base  : Entity_Id;
545       Is_Tagged     : Boolean;
546       Inherit_Discr : Boolean;
547       Discs         : Elist_Id) return Elist_Id;
548    --  Called from Build_Derived_Record_Type to inherit the components of
549    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
550    --  For more information on derived types and component inheritance please
551    --  consult the comment above the body of Build_Derived_Record_Type.
552    --
553    --    N is the original derived type declaration
554    --
555    --    Is_Tagged is set if we are dealing with tagged types
556    --
557    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
558    --    Parent_Base, otherwise no discriminants are inherited.
559    --
560    --    Discs gives the list of constraints that apply to Parent_Base in the
561    --    derived type declaration. If Discs is set to No_Elist, then we have
562    --    the following situation:
563    --
564    --      type Parent (D1..Dn : ..) is [tagged] record ...;
565    --      type Derived is new Parent [with ...];
566    --
567    --    which gets treated as
568    --
569    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
570    --
571    --  For untagged types the returned value is an association list. The list
572    --  starts from the association (Parent_Base => Derived_Base), and then it
573    --  contains a sequence of the associations of the form
574    --
575    --    (Old_Component => New_Component),
576    --
577    --  where Old_Component is the Entity_Id of a component in Parent_Base and
578    --  New_Component is the Entity_Id of the corresponding component in
579    --  Derived_Base. For untagged records, this association list is needed when
580    --  copying the record declaration for the derived base. In the tagged case
581    --  the value returned is irrelevant.
582
583    function Is_Valid_Constraint_Kind
584      (T_Kind          : Type_Kind;
585       Constraint_Kind : Node_Kind) return Boolean;
586    --  Returns True if it is legal to apply the given kind of constraint to the
587    --  given kind of type (index constraint to an array type, for example).
588
589    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
590    --  Create new modular type. Verify that modulus is in bounds
591
592    procedure New_Concatenation_Op (Typ : Entity_Id);
593    --  Create an abbreviated declaration for an operator in order to
594    --  materialize concatenation on array types.
595
596    procedure Ordinary_Fixed_Point_Type_Declaration
597      (T   : Entity_Id;
598       Def : Node_Id);
599    --  Create a new ordinary fixed point type, and apply the constraint to
600    --  obtain subtype of it.
601
602    procedure Prepare_Private_Subtype_Completion
603      (Id          : Entity_Id;
604       Related_Nod : Node_Id);
605    --  Id is a subtype of some private type. Creates the full declaration
606    --  associated with Id whenever possible, i.e. when the full declaration
607    --  of the base type is already known. Records each subtype into
608    --  Private_Dependents of the base type.
609
610    procedure Process_Incomplete_Dependents
611      (N      : Node_Id;
612       Full_T : Entity_Id;
613       Inc_T  : Entity_Id);
614    --  Process all entities that depend on an incomplete type. There include
615    --  subtypes, subprogram types that mention the incomplete type in their
616    --  profiles, and subprogram with access parameters that designate the
617    --  incomplete type.
618
619    --  Inc_T is the defining identifier of an incomplete type declaration, its
620    --  Ekind is E_Incomplete_Type.
621    --
622    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
623    --
624    --    Full_T is N's defining identifier.
625    --
626    --  Subtypes of incomplete types with discriminants are completed when the
627    --  parent type is. This is simpler than private subtypes, because they can
628    --  only appear in the same scope, and there is no need to exchange views.
629    --  Similarly, access_to_subprogram types may have a parameter or a return
630    --  type that is an incomplete type, and that must be replaced with the
631    --  full type.
632    --
633    --  If the full type is tagged, subprogram with access parameters that
634    --  designated the incomplete may be primitive operations of the full type,
635    --  and have to be processed accordingly.
636
637    procedure Process_Real_Range_Specification (Def : Node_Id);
638    --  Given the type definition for a real type, this procedure processes and
639    --  checks the real range specification of this type definition if one is
640    --  present. If errors are found, error messages are posted, and the
641    --  Real_Range_Specification of Def is reset to Empty.
642
643    procedure Record_Type_Declaration
644      (T    : Entity_Id;
645       N    : Node_Id;
646       Prev : Entity_Id);
647    --  Process a record type declaration (for both untagged and tagged
648    --  records). Parameters T and N are exactly like in procedure
649    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
650    --  for this routine. If this is the completion of an incomplete type
651    --  declaration, Prev is the entity of the incomplete declaration, used for
652    --  cross-referencing. Otherwise Prev = T.
653
654    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
655    --  This routine is used to process the actual record type definition (both
656    --  for untagged and tagged records). Def is a record type definition node.
657    --  This procedure analyzes the components in this record type definition.
658    --  Prev_T is the entity for the enclosing record type. It is provided so
659    --  that its Has_Task flag can be set if any of the component have Has_Task
660    --  set. If the declaration is the completion of an incomplete type
661    --  declaration, Prev_T is the original incomplete type, whose full view is
662    --  the record type.
663
664    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
665    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
666    --  build a copy of the declaration tree of the parent, and we create
667    --  independently the list of components for the derived type. Semantic
668    --  information uses the component entities, but record representation
669    --  clauses are validated on the declaration tree. This procedure replaces
670    --  discriminants and components in the declaration with those that have
671    --  been created by Inherit_Components.
672
673    procedure Set_Fixed_Range
674      (E   : Entity_Id;
675       Loc : Source_Ptr;
676       Lo  : Ureal;
677       Hi  : Ureal);
678    --  Build a range node with the given bounds and set it as the Scalar_Range
679    --  of the given fixed-point type entity. Loc is the source location used
680    --  for the constructed range. See body for further details.
681
682    procedure Set_Scalar_Range_For_Subtype
683      (Def_Id : Entity_Id;
684       R      : Node_Id;
685       Subt   : Entity_Id);
686    --  This routine is used to set the scalar range field for a subtype given
687    --  Def_Id, the entity for the subtype, and R, the range expression for the
688    --  scalar range. Subt provides the parent subtype to be used to analyze,
689    --  resolve, and check the given range.
690
691    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
692    --  Create a new signed integer entity, and apply the constraint to obtain
693    --  the required first named subtype of this type.
694
695    procedure Set_Stored_Constraint_From_Discriminant_Constraint
696      (E : Entity_Id);
697    --  E is some record type. This routine computes E's Stored_Constraint
698    --  from its Discriminant_Constraint.
699
700    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
701    --  Check that an entity in a list of progenitors is an interface,
702    --  emit error otherwise.
703
704    -----------------------
705    -- Access_Definition --
706    -----------------------
707
708    function Access_Definition
709      (Related_Nod : Node_Id;
710       N           : Node_Id) return Entity_Id
711    is
712       Anon_Type           : Entity_Id;
713       Anon_Scope          : Entity_Id;
714       Desig_Type          : Entity_Id;
715       Enclosing_Prot_Type : Entity_Id := Empty;
716
717    begin
718       Check_SPARK_Restriction ("access type is not allowed", N);
719
720       if Is_Entry (Current_Scope)
721         and then Is_Task_Type (Etype (Scope (Current_Scope)))
722       then
723          Error_Msg_N ("task entries cannot have access parameters", N);
724          return Empty;
725       end if;
726
727       --  Ada 2005: for an object declaration the corresponding anonymous
728       --  type is declared in the current scope.
729
730       --  If the access definition is the return type of another access to
731       --  function, scope is the current one, because it is the one of the
732       --  current type declaration, except for the pathological case below.
733
734       if Nkind_In (Related_Nod, N_Object_Declaration,
735                                 N_Access_Function_Definition)
736       then
737          Anon_Scope := Current_Scope;
738
739          --  A pathological case: function returning access functions that
740          --  return access functions, etc. Each anonymous access type created
741          --  is in the enclosing scope of the outermost function.
742
743          declare
744             Par : Node_Id;
745
746          begin
747             Par := Related_Nod;
748             while Nkind_In (Par, N_Access_Function_Definition,
749                                  N_Access_Definition)
750             loop
751                Par := Parent (Par);
752             end loop;
753
754             if Nkind (Par) = N_Function_Specification then
755                Anon_Scope := Scope (Defining_Entity (Par));
756             end if;
757          end;
758
759       --  For the anonymous function result case, retrieve the scope of the
760       --  function specification's associated entity rather than using the
761       --  current scope. The current scope will be the function itself if the
762       --  formal part is currently being analyzed, but will be the parent scope
763       --  in the case of a parameterless function, and we always want to use
764       --  the function's parent scope. Finally, if the function is a child
765       --  unit, we must traverse the tree to retrieve the proper entity.
766
767       elsif Nkind (Related_Nod) = N_Function_Specification
768         and then Nkind (Parent (N)) /= N_Parameter_Specification
769       then
770          --  If the current scope is a protected type, the anonymous access
771          --  is associated with one of the protected operations, and must
772          --  be available in the scope that encloses the protected declaration.
773          --  Otherwise the type is in the scope enclosing the subprogram.
774
775          --  If the function has formals, The return type of a subprogram
776          --  declaration is analyzed in the scope of the subprogram (see
777          --  Process_Formals) and thus the protected type, if present, is
778          --  the scope of the current function scope.
779
780          if Ekind (Current_Scope) = E_Protected_Type then
781             Enclosing_Prot_Type := Current_Scope;
782
783          elsif Ekind (Current_Scope) = E_Function
784            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
785          then
786             Enclosing_Prot_Type := Scope (Current_Scope);
787          end if;
788
789          if Present (Enclosing_Prot_Type) then
790             Anon_Scope := Scope (Enclosing_Prot_Type);
791
792          else
793             Anon_Scope := Scope (Defining_Entity (Related_Nod));
794          end if;
795
796       --  For an access type definition, if the current scope is a child
797       --  unit it is the scope of the type.
798
799       elsif Is_Compilation_Unit (Current_Scope) then
800          Anon_Scope := Current_Scope;
801
802       --  For access formals, access components, and access discriminants, the
803       --  scope is that of the enclosing declaration,
804
805       else
806          Anon_Scope := Scope (Current_Scope);
807       end if;
808
809       Anon_Type :=
810         Create_Itype
811           (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
812
813       if All_Present (N)
814         and then Ada_Version >= Ada_2005
815       then
816          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
817       end if;
818
819       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
820       --  the corresponding semantic routine
821
822       if Present (Access_To_Subprogram_Definition (N)) then
823
824          --  Compiler runtime units are compiled in Ada 2005 mode when building
825          --  the runtime library but must also be compilable in Ada 95 mode
826          --  (when bootstrapping the compiler).
827
828          Check_Compiler_Unit (N);
829
830          Access_Subprogram_Declaration
831            (T_Name => Anon_Type,
832             T_Def  => Access_To_Subprogram_Definition (N));
833
834          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
835             Set_Ekind
836               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
837          else
838             Set_Ekind
839               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
840          end if;
841
842          Set_Can_Use_Internal_Rep
843            (Anon_Type, not Always_Compatible_Rep_On_Target);
844
845          --  If the anonymous access is associated with a protected operation,
846          --  create a reference to it after the enclosing protected definition
847          --  because the itype will be used in the subsequent bodies.
848
849          if Ekind (Current_Scope) = E_Protected_Type then
850             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
851          end if;
852
853          return Anon_Type;
854       end if;
855
856       Find_Type (Subtype_Mark (N));
857       Desig_Type := Entity (Subtype_Mark (N));
858
859       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
860       Set_Etype (Anon_Type, Anon_Type);
861
862       --  Make sure the anonymous access type has size and alignment fields
863       --  set, as required by gigi. This is necessary in the case of the
864       --  Task_Body_Procedure.
865
866       if not Has_Private_Component (Desig_Type) then
867          Layout_Type (Anon_Type);
868       end if;
869
870       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
871       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
872       --  the null value is allowed. In Ada 95 the null value is never allowed.
873
874       if Ada_Version >= Ada_2005 then
875          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
876       else
877          Set_Can_Never_Be_Null (Anon_Type, True);
878       end if;
879
880       --  The anonymous access type is as public as the discriminated type or
881       --  subprogram that defines it. It is imported (for back-end purposes)
882       --  if the designated type is.
883
884       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
885
886       --  Ada 2005 (AI-231): Propagate the access-constant attribute
887
888       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
889
890       --  The context is either a subprogram declaration, object declaration,
891       --  or an access discriminant, in a private or a full type declaration.
892       --  In the case of a subprogram, if the designated type is incomplete,
893       --  the operation will be a primitive operation of the full type, to be
894       --  updated subsequently. If the type is imported through a limited_with
895       --  clause, the subprogram is not a primitive operation of the type
896       --  (which is declared elsewhere in some other scope).
897
898       if Ekind (Desig_Type) = E_Incomplete_Type
899         and then not From_With_Type (Desig_Type)
900         and then Is_Overloadable (Current_Scope)
901       then
902          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
903          Set_Has_Delayed_Freeze (Current_Scope);
904       end if;
905
906       --  Ada 2005: if the designated type is an interface that may contain
907       --  tasks, create a Master entity for the declaration. This must be done
908       --  before expansion of the full declaration, because the declaration may
909       --  include an expression that is an allocator, whose expansion needs the
910       --  proper Master for the created tasks.
911
912       if Nkind (Related_Nod) = N_Object_Declaration
913         and then Expander_Active
914       then
915          if Is_Interface (Desig_Type)
916            and then Is_Limited_Record (Desig_Type)
917          then
918             Build_Class_Wide_Master (Anon_Type);
919
920          --  Similarly, if the type is an anonymous access that designates
921          --  tasks, create a master entity for it in the current context.
922
923          elsif Has_Task (Desig_Type)
924            and then Comes_From_Source (Related_Nod)
925          then
926             Build_Master_Entity (Defining_Identifier (Related_Nod));
927             Build_Master_Renaming (Anon_Type);
928          end if;
929       end if;
930
931       --  For a private component of a protected type, it is imperative that
932       --  the back-end elaborate the type immediately after the protected
933       --  declaration, because this type will be used in the declarations
934       --  created for the component within each protected body, so we must
935       --  create an itype reference for it now.
936
937       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
938          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
939
940       --  Similarly, if the access definition is the return result of a
941       --  function, create an itype reference for it because it will be used
942       --  within the function body. For a regular function that is not a
943       --  compilation unit, insert reference after the declaration. For a
944       --  protected operation, insert it after the enclosing protected type
945       --  declaration. In either case, do not create a reference for a type
946       --  obtained through a limited_with clause, because this would introduce
947       --  semantic dependencies.
948
949       --  Similarly, do not create a reference if the designated type is a
950       --  generic formal, because no use of it will reach the backend.
951
952       elsif Nkind (Related_Nod) = N_Function_Specification
953         and then not From_With_Type (Desig_Type)
954         and then not Is_Generic_Type (Desig_Type)
955       then
956          if Present (Enclosing_Prot_Type) then
957             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
958
959          elsif Is_List_Member (Parent (Related_Nod))
960            and then Nkind (Parent (N)) /= N_Parameter_Specification
961          then
962             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
963          end if;
964
965       --  Finally, create an itype reference for an object declaration of an
966       --  anonymous access type. This is strictly necessary only for deferred
967       --  constants, but in any case will avoid out-of-scope problems in the
968       --  back-end.
969
970       elsif Nkind (Related_Nod) = N_Object_Declaration then
971          Build_Itype_Reference (Anon_Type, Related_Nod);
972       end if;
973
974       return Anon_Type;
975    end Access_Definition;
976
977    -----------------------------------
978    -- Access_Subprogram_Declaration --
979    -----------------------------------
980
981    procedure Access_Subprogram_Declaration
982      (T_Name : Entity_Id;
983       T_Def  : Node_Id)
984    is
985       procedure Check_For_Premature_Usage (Def : Node_Id);
986       --  Check that type T_Name is not used, directly or recursively, as a
987       --  parameter or a return type in Def. Def is either a subtype, an
988       --  access_definition, or an access_to_subprogram_definition.
989
990       -------------------------------
991       -- Check_For_Premature_Usage --
992       -------------------------------
993
994       procedure Check_For_Premature_Usage (Def : Node_Id) is
995          Param : Node_Id;
996
997       begin
998          --  Check for a subtype mark
999
1000          if Nkind (Def) in N_Has_Etype then
1001             if Etype (Def) = T_Name then
1002                Error_Msg_N
1003                  ("type& cannot be used before end of its declaration", Def);
1004             end if;
1005
1006          --  If this is not a subtype, then this is an access_definition
1007
1008          elsif Nkind (Def) = N_Access_Definition then
1009             if Present (Access_To_Subprogram_Definition (Def)) then
1010                Check_For_Premature_Usage
1011                  (Access_To_Subprogram_Definition (Def));
1012             else
1013                Check_For_Premature_Usage (Subtype_Mark (Def));
1014             end if;
1015
1016          --  The only cases left are N_Access_Function_Definition and
1017          --  N_Access_Procedure_Definition.
1018
1019          else
1020             if Present (Parameter_Specifications (Def)) then
1021                Param := First (Parameter_Specifications (Def));
1022                while Present (Param) loop
1023                   Check_For_Premature_Usage (Parameter_Type (Param));
1024                   Param := Next (Param);
1025                end loop;
1026             end if;
1027
1028             if Nkind (Def) = N_Access_Function_Definition then
1029                Check_For_Premature_Usage (Result_Definition (Def));
1030             end if;
1031          end if;
1032       end Check_For_Premature_Usage;
1033
1034       --  Local variables
1035
1036       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1037       Formal     : Entity_Id;
1038       D_Ityp     : Node_Id;
1039       Desig_Type : constant Entity_Id :=
1040                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1041
1042    --  Start of processing for Access_Subprogram_Declaration
1043
1044    begin
1045       Check_SPARK_Restriction ("access type is not allowed", T_Def);
1046
1047       --  Associate the Itype node with the inner full-type declaration or
1048       --  subprogram spec or entry body. This is required to handle nested
1049       --  anonymous declarations. For example:
1050
1051       --      procedure P
1052       --       (X : access procedure
1053       --                     (Y : access procedure
1054       --                                   (Z : access T)))
1055
1056       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1057       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1058                                    N_Private_Type_Declaration,
1059                                    N_Private_Extension_Declaration,
1060                                    N_Procedure_Specification,
1061                                    N_Function_Specification,
1062                                    N_Entry_Body)
1063
1064                    or else
1065                  Nkind_In (D_Ityp, N_Object_Declaration,
1066                                    N_Object_Renaming_Declaration,
1067                                    N_Formal_Object_Declaration,
1068                                    N_Formal_Type_Declaration,
1069                                    N_Task_Type_Declaration,
1070                                    N_Protected_Type_Declaration))
1071       loop
1072          D_Ityp := Parent (D_Ityp);
1073          pragma Assert (D_Ityp /= Empty);
1074       end loop;
1075
1076       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1077
1078       if Nkind_In (D_Ityp, N_Procedure_Specification,
1079                            N_Function_Specification)
1080       then
1081          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1082
1083       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1084                               N_Object_Declaration,
1085                               N_Object_Renaming_Declaration,
1086                               N_Formal_Type_Declaration)
1087       then
1088          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1089       end if;
1090
1091       if Nkind (T_Def) = N_Access_Function_Definition then
1092          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1093             declare
1094                Acc : constant Node_Id := Result_Definition (T_Def);
1095
1096             begin
1097                if Present (Access_To_Subprogram_Definition (Acc))
1098                  and then
1099                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1100                then
1101                   Set_Etype
1102                     (Desig_Type,
1103                        Replace_Anonymous_Access_To_Protected_Subprogram
1104                          (T_Def));
1105
1106                else
1107                   Set_Etype
1108                     (Desig_Type,
1109                        Access_Definition (T_Def, Result_Definition (T_Def)));
1110                end if;
1111             end;
1112
1113          else
1114             Analyze (Result_Definition (T_Def));
1115
1116             declare
1117                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1118
1119             begin
1120                --  If a null exclusion is imposed on the result type, then
1121                --  create a null-excluding itype (an access subtype) and use
1122                --  it as the function's Etype.
1123
1124                if Is_Access_Type (Typ)
1125                  and then Null_Exclusion_In_Return_Present (T_Def)
1126                then
1127                   Set_Etype  (Desig_Type,
1128                     Create_Null_Excluding_Itype
1129                       (T           => Typ,
1130                        Related_Nod => T_Def,
1131                        Scope_Id    => Current_Scope));
1132
1133                else
1134                   if From_With_Type (Typ) then
1135
1136                      --  AI05-151: Incomplete types are allowed in all basic
1137                      --  declarations, including access to subprograms.
1138
1139                      if Ada_Version >= Ada_2012 then
1140                         null;
1141
1142                      else
1143                         Error_Msg_NE
1144                          ("illegal use of incomplete type&",
1145                           Result_Definition (T_Def), Typ);
1146                      end if;
1147
1148                   elsif Ekind (Current_Scope) = E_Package
1149                     and then In_Private_Part (Current_Scope)
1150                   then
1151                      if Ekind (Typ) = E_Incomplete_Type then
1152                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1153
1154                      elsif Is_Class_Wide_Type (Typ)
1155                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1156                      then
1157                         Append_Elmt
1158                           (Desig_Type, Private_Dependents (Etype (Typ)));
1159                      end if;
1160                   end if;
1161
1162                   Set_Etype (Desig_Type, Typ);
1163                end if;
1164             end;
1165          end if;
1166
1167          if not (Is_Type (Etype (Desig_Type))) then
1168             Error_Msg_N
1169               ("expect type in function specification",
1170                Result_Definition (T_Def));
1171          end if;
1172
1173       else
1174          Set_Etype (Desig_Type, Standard_Void_Type);
1175       end if;
1176
1177       if Present (Formals) then
1178          Push_Scope (Desig_Type);
1179
1180          --  A bit of a kludge here. These kludges will be removed when Itypes
1181          --  have proper parent pointers to their declarations???
1182
1183          --  Kludge 1) Link defining_identifier of formals. Required by
1184          --  First_Formal to provide its functionality.
1185
1186          declare
1187             F : Node_Id;
1188
1189          begin
1190             F := First (Formals);
1191
1192             --  In ASIS mode, the access_to_subprogram may be analyzed twice,
1193             --  when it is part of an unconstrained type and subtype expansion
1194             --  is disabled. To avoid back-end problems with shared profiles,
1195             --  use previous subprogram type as the designated type, and then
1196             --  remove scope added above.
1197
1198             if ASIS_Mode
1199               and then Present (Scope (Defining_Identifier (F)))
1200             then
1201                Set_Etype                    (T_Name, T_Name);
1202                Init_Size_Align              (T_Name);
1203                Set_Directly_Designated_Type (T_Name,
1204                  Scope (Defining_Identifier (F)));
1205                End_Scope;
1206                return;
1207             end if;
1208
1209             while Present (F) loop
1210                if No (Parent (Defining_Identifier (F))) then
1211                   Set_Parent (Defining_Identifier (F), F);
1212                end if;
1213
1214                Next (F);
1215             end loop;
1216          end;
1217
1218          Process_Formals (Formals, Parent (T_Def));
1219
1220          --  Kludge 2) End_Scope requires that the parent pointer be set to
1221          --  something reasonable, but Itypes don't have parent pointers. So
1222          --  we set it and then unset it ???
1223
1224          Set_Parent (Desig_Type, T_Name);
1225          End_Scope;
1226          Set_Parent (Desig_Type, Empty);
1227       end if;
1228
1229       --  Check for premature usage of the type being defined
1230
1231       Check_For_Premature_Usage (T_Def);
1232
1233       --  The return type and/or any parameter type may be incomplete. Mark the
1234       --  subprogram_type as depending on the incomplete type, so that it can
1235       --  be updated when the full type declaration is seen. This only applies
1236       --  to incomplete types declared in some enclosing scope, not to limited
1237       --  views from other packages.
1238       --  Prior to Ada 2012, access to functions can only have in_parameters.
1239
1240       if Present (Formals) then
1241          Formal := First_Formal (Desig_Type);
1242          while Present (Formal) loop
1243             if Ekind (Formal) /= E_In_Parameter
1244               and then Nkind (T_Def) = N_Access_Function_Definition
1245               and then Ada_Version < Ada_2012
1246             then
1247                Error_Msg_N ("functions can only have IN parameters", Formal);
1248             end if;
1249
1250             if Ekind (Etype (Formal)) = E_Incomplete_Type
1251               and then In_Open_Scopes (Scope (Etype (Formal)))
1252             then
1253                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1254                Set_Has_Delayed_Freeze (Desig_Type);
1255             end if;
1256
1257             Next_Formal (Formal);
1258          end loop;
1259       end if;
1260
1261       --  Check whether an indirect call without actuals may be possible. This
1262       --  is used when resolving calls whose result is then indexed.
1263
1264       May_Need_Actuals (Desig_Type);
1265
1266       --  If the return type is incomplete, this is legal as long as the type
1267       --  is declared in the current scope and will be completed in it (rather
1268       --  than being part of limited view).
1269
1270       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1271         and then not Has_Delayed_Freeze (Desig_Type)
1272         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1273       then
1274          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1275          Set_Has_Delayed_Freeze (Desig_Type);
1276       end if;
1277
1278       Check_Delayed_Subprogram (Desig_Type);
1279
1280       if Protected_Present (T_Def) then
1281          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1282          Set_Convention (Desig_Type, Convention_Protected);
1283       else
1284          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1285       end if;
1286
1287       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1288
1289       Set_Etype                    (T_Name, T_Name);
1290       Init_Size_Align              (T_Name);
1291       Set_Directly_Designated_Type (T_Name, Desig_Type);
1292
1293       Generate_Reference_To_Formals (T_Name);
1294
1295       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1296
1297       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1298
1299       Check_Restriction (No_Access_Subprograms, T_Def);
1300    end Access_Subprogram_Declaration;
1301
1302    ----------------------------
1303    -- Access_Type_Declaration --
1304    ----------------------------
1305
1306    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1307       P : constant Node_Id := Parent (Def);
1308       S : constant Node_Id := Subtype_Indication (Def);
1309
1310       Full_Desig : Entity_Id;
1311
1312    begin
1313       Check_SPARK_Restriction ("access type is not allowed", Def);
1314
1315       --  Check for permissible use of incomplete type
1316
1317       if Nkind (S) /= N_Subtype_Indication then
1318          Analyze (S);
1319
1320          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1321             Set_Directly_Designated_Type (T, Entity (S));
1322          else
1323             Set_Directly_Designated_Type (T,
1324               Process_Subtype (S, P, T, 'P'));
1325          end if;
1326
1327       else
1328          Set_Directly_Designated_Type (T,
1329            Process_Subtype (S, P, T, 'P'));
1330       end if;
1331
1332       if All_Present (Def) or Constant_Present (Def) then
1333          Set_Ekind (T, E_General_Access_Type);
1334       else
1335          Set_Ekind (T, E_Access_Type);
1336       end if;
1337
1338       Full_Desig := Designated_Type (T);
1339
1340       if Base_Type (Full_Desig) = T then
1341          Error_Msg_N ("access type cannot designate itself", S);
1342
1343       --  In Ada 2005, the type may have a limited view through some unit in
1344       --  its own context, allowing the following circularity that cannot be
1345       --  detected earlier
1346
1347       elsif Is_Class_Wide_Type (Full_Desig)
1348         and then Etype (Full_Desig) = T
1349       then
1350          Error_Msg_N
1351            ("access type cannot designate its own classwide type", S);
1352
1353          --  Clean up indication of tagged status to prevent cascaded errors
1354
1355          Set_Is_Tagged_Type (T, False);
1356       end if;
1357
1358       Set_Etype (T, T);
1359
1360       --  If the type has appeared already in a with_type clause, it is frozen
1361       --  and the pointer size is already set. Else, initialize.
1362
1363       if not From_With_Type (T) then
1364          Init_Size_Align (T);
1365       end if;
1366
1367       --  Note that Has_Task is always false, since the access type itself
1368       --  is not a task type. See Einfo for more description on this point.
1369       --  Exactly the same consideration applies to Has_Controlled_Component.
1370
1371       Set_Has_Task (T, False);
1372       Set_Has_Controlled_Component (T, False);
1373
1374       --  Initialize field Finalization_Master explicitly to Empty, to avoid
1375       --  problems where an incomplete view of this entity has been previously
1376       --  established by a limited with and an overlaid version of this field
1377       --  (Stored_Constraint) was initialized for the incomplete view.
1378
1379       --  This reset is performed in most cases except where the access type
1380       --  has been created for the purposes of allocating or deallocating a
1381       --  build-in-place object. Such access types have explicitly set pools
1382       --  and finalization masters.
1383
1384       if No (Associated_Storage_Pool (T)) then
1385          Set_Finalization_Master (T, Empty);
1386       end if;
1387
1388       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1389       --  attributes
1390
1391       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1392       Set_Is_Access_Constant (T, Constant_Present (Def));
1393    end Access_Type_Declaration;
1394
1395    ----------------------------------
1396    -- Add_Interface_Tag_Components --
1397    ----------------------------------
1398
1399    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1400       Loc      : constant Source_Ptr := Sloc (N);
1401       L        : List_Id;
1402       Last_Tag : Node_Id;
1403
1404       procedure Add_Tag (Iface : Entity_Id);
1405       --  Add tag for one of the progenitor interfaces
1406
1407       -------------
1408       -- Add_Tag --
1409       -------------
1410
1411       procedure Add_Tag (Iface : Entity_Id) is
1412          Decl   : Node_Id;
1413          Def    : Node_Id;
1414          Tag    : Entity_Id;
1415          Offset : Entity_Id;
1416
1417       begin
1418          pragma Assert (Is_Tagged_Type (Iface) and then Is_Interface (Iface));
1419
1420          --  This is a reasonable place to propagate predicates
1421
1422          if Has_Predicates (Iface) then
1423             Set_Has_Predicates (Typ);
1424          end if;
1425
1426          Def :=
1427            Make_Component_Definition (Loc,
1428              Aliased_Present    => True,
1429              Subtype_Indication =>
1430                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1431
1432          Tag := Make_Temporary (Loc, 'V');
1433
1434          Decl :=
1435            Make_Component_Declaration (Loc,
1436              Defining_Identifier  => Tag,
1437              Component_Definition => Def);
1438
1439          Analyze_Component_Declaration (Decl);
1440
1441          Set_Analyzed (Decl);
1442          Set_Ekind               (Tag, E_Component);
1443          Set_Is_Tag              (Tag);
1444          Set_Is_Aliased          (Tag);
1445          Set_Related_Type        (Tag, Iface);
1446          Init_Component_Location (Tag);
1447
1448          pragma Assert (Is_Frozen (Iface));
1449
1450          Set_DT_Entry_Count    (Tag,
1451            DT_Entry_Count (First_Entity (Iface)));
1452
1453          if No (Last_Tag) then
1454             Prepend (Decl, L);
1455          else
1456             Insert_After (Last_Tag, Decl);
1457          end if;
1458
1459          Last_Tag := Decl;
1460
1461          --  If the ancestor has discriminants we need to give special support
1462          --  to store the offset_to_top value of the secondary dispatch tables.
1463          --  For this purpose we add a supplementary component just after the
1464          --  field that contains the tag associated with each secondary DT.
1465
1466          if Typ /= Etype (Typ) and then Has_Discriminants (Etype (Typ)) then
1467             Def :=
1468               Make_Component_Definition (Loc,
1469                 Subtype_Indication =>
1470                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1471
1472             Offset := Make_Temporary (Loc, 'V');
1473
1474             Decl :=
1475               Make_Component_Declaration (Loc,
1476                 Defining_Identifier  => Offset,
1477                 Component_Definition => Def);
1478
1479             Analyze_Component_Declaration (Decl);
1480
1481             Set_Analyzed (Decl);
1482             Set_Ekind               (Offset, E_Component);
1483             Set_Is_Aliased          (Offset);
1484             Set_Related_Type        (Offset, Iface);
1485             Init_Component_Location (Offset);
1486             Insert_After (Last_Tag, Decl);
1487             Last_Tag := Decl;
1488          end if;
1489       end Add_Tag;
1490
1491       --  Local variables
1492
1493       Elmt : Elmt_Id;
1494       Ext  : Node_Id;
1495       Comp : Node_Id;
1496
1497    --  Start of processing for Add_Interface_Tag_Components
1498
1499    begin
1500       if not RTE_Available (RE_Interface_Tag) then
1501          Error_Msg
1502            ("(Ada 2005) interface types not supported by this run-time!",
1503             Sloc (N));
1504          return;
1505       end if;
1506
1507       if Ekind (Typ) /= E_Record_Type
1508         or else (Is_Concurrent_Record_Type (Typ)
1509                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1510         or else (not Is_Concurrent_Record_Type (Typ)
1511                   and then No (Interfaces (Typ))
1512                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1513       then
1514          return;
1515       end if;
1516
1517       --  Find the current last tag
1518
1519       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1520          Ext := Record_Extension_Part (Type_Definition (N));
1521       else
1522          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1523          Ext := Type_Definition (N);
1524       end if;
1525
1526       Last_Tag := Empty;
1527
1528       if not (Present (Component_List (Ext))) then
1529          Set_Null_Present (Ext, False);
1530          L := New_List;
1531          Set_Component_List (Ext,
1532            Make_Component_List (Loc,
1533              Component_Items => L,
1534              Null_Present => False));
1535       else
1536          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1537             L := Component_Items
1538                    (Component_List
1539                      (Record_Extension_Part
1540                        (Type_Definition (N))));
1541          else
1542             L := Component_Items
1543                    (Component_List
1544                      (Type_Definition (N)));
1545          end if;
1546
1547          --  Find the last tag component
1548
1549          Comp := First (L);
1550          while Present (Comp) loop
1551             if Nkind (Comp) = N_Component_Declaration
1552               and then Is_Tag (Defining_Identifier (Comp))
1553             then
1554                Last_Tag := Comp;
1555             end if;
1556
1557             Next (Comp);
1558          end loop;
1559       end if;
1560
1561       --  At this point L references the list of components and Last_Tag
1562       --  references the current last tag (if any). Now we add the tag
1563       --  corresponding with all the interfaces that are not implemented
1564       --  by the parent.
1565
1566       if Present (Interfaces (Typ)) then
1567          Elmt := First_Elmt (Interfaces (Typ));
1568          while Present (Elmt) loop
1569             Add_Tag (Node (Elmt));
1570             Next_Elmt (Elmt);
1571          end loop;
1572       end if;
1573    end Add_Interface_Tag_Components;
1574
1575    -------------------------------------
1576    -- Add_Internal_Interface_Entities --
1577    -------------------------------------
1578
1579    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1580       Elmt          : Elmt_Id;
1581       Iface         : Entity_Id;
1582       Iface_Elmt    : Elmt_Id;
1583       Iface_Prim    : Entity_Id;
1584       Ifaces_List   : Elist_Id;
1585       New_Subp      : Entity_Id := Empty;
1586       Prim          : Entity_Id;
1587       Restore_Scope : Boolean := False;
1588
1589    begin
1590       pragma Assert (Ada_Version >= Ada_2005
1591         and then Is_Record_Type (Tagged_Type)
1592         and then Is_Tagged_Type (Tagged_Type)
1593         and then Has_Interfaces (Tagged_Type)
1594         and then not Is_Interface (Tagged_Type));
1595
1596       --  Ensure that the internal entities are added to the scope of the type
1597
1598       if Scope (Tagged_Type) /= Current_Scope then
1599          Push_Scope (Scope (Tagged_Type));
1600          Restore_Scope := True;
1601       end if;
1602
1603       Collect_Interfaces (Tagged_Type, Ifaces_List);
1604
1605       Iface_Elmt := First_Elmt (Ifaces_List);
1606       while Present (Iface_Elmt) loop
1607          Iface := Node (Iface_Elmt);
1608
1609          --  Originally we excluded here from this processing interfaces that
1610          --  are parents of Tagged_Type because their primitives are located
1611          --  in the primary dispatch table (and hence no auxiliary internal
1612          --  entities are required to handle secondary dispatch tables in such
1613          --  case). However, these auxiliary entities are also required to
1614          --  handle derivations of interfaces in formals of generics (see
1615          --  Derive_Subprograms).
1616
1617          Elmt := First_Elmt (Primitive_Operations (Iface));
1618          while Present (Elmt) loop
1619             Iface_Prim := Node (Elmt);
1620
1621             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1622                Prim :=
1623                  Find_Primitive_Covering_Interface
1624                    (Tagged_Type => Tagged_Type,
1625                     Iface_Prim  => Iface_Prim);
1626
1627                if No (Prim) and then Serious_Errors_Detected > 0 then
1628                   goto Continue;
1629                end if;
1630
1631                pragma Assert (Present (Prim));
1632
1633                --  Ada 2012 (AI05-0197): If the name of the covering primitive
1634                --  differs from the name of the interface primitive then it is
1635                --  a private primitive inherited from a parent type. In such
1636                --  case, given that Tagged_Type covers the interface, the
1637                --  inherited private primitive becomes visible. For such
1638                --  purpose we add a new entity that renames the inherited
1639                --  private primitive.
1640
1641                if Chars (Prim) /= Chars (Iface_Prim) then
1642                   pragma Assert (Has_Suffix (Prim, 'P'));
1643                   Derive_Subprogram
1644                     (New_Subp     => New_Subp,
1645                      Parent_Subp  => Iface_Prim,
1646                      Derived_Type => Tagged_Type,
1647                      Parent_Type  => Iface);
1648                   Set_Alias (New_Subp, Prim);
1649                   Set_Is_Abstract_Subprogram
1650                     (New_Subp, Is_Abstract_Subprogram (Prim));
1651                end if;
1652
1653                Derive_Subprogram
1654                  (New_Subp     => New_Subp,
1655                   Parent_Subp  => Iface_Prim,
1656                   Derived_Type => Tagged_Type,
1657                   Parent_Type  => Iface);
1658
1659                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1660                --  associated with interface types. These entities are
1661                --  only registered in the list of primitives of its
1662                --  corresponding tagged type because they are only used
1663                --  to fill the contents of the secondary dispatch tables.
1664                --  Therefore they are removed from the homonym chains.
1665
1666                Set_Is_Hidden (New_Subp);
1667                Set_Is_Internal (New_Subp);
1668                Set_Alias (New_Subp, Prim);
1669                Set_Is_Abstract_Subprogram
1670                  (New_Subp, Is_Abstract_Subprogram (Prim));
1671                Set_Interface_Alias (New_Subp, Iface_Prim);
1672
1673                --  If the returned type is an interface then propagate it to
1674                --  the returned type. Needed by the thunk to generate the code
1675                --  which displaces "this" to reference the corresponding
1676                --  secondary dispatch table in the returned object.
1677
1678                if Is_Interface (Etype (Iface_Prim)) then
1679                   Set_Etype (New_Subp, Etype (Iface_Prim));
1680                end if;
1681
1682                --  Internal entities associated with interface types are
1683                --  only registered in the list of primitives of the tagged
1684                --  type. They are only used to fill the contents of the
1685                --  secondary dispatch tables. Therefore they are not needed
1686                --  in the homonym chains.
1687
1688                Remove_Homonym (New_Subp);
1689
1690                --  Hidden entities associated with interfaces must have set
1691                --  the Has_Delay_Freeze attribute to ensure that, in case of
1692                --  locally defined tagged types (or compiling with static
1693                --  dispatch tables generation disabled) the corresponding
1694                --  entry of the secondary dispatch table is filled when
1695                --  such an entity is frozen.
1696
1697                Set_Has_Delayed_Freeze (New_Subp);
1698             end if;
1699
1700             <<Continue>>
1701             Next_Elmt (Elmt);
1702          end loop;
1703
1704          Next_Elmt (Iface_Elmt);
1705       end loop;
1706
1707       if Restore_Scope then
1708          Pop_Scope;
1709       end if;
1710    end Add_Internal_Interface_Entities;
1711
1712    -----------------------------------
1713    -- Analyze_Component_Declaration --
1714    -----------------------------------
1715
1716    procedure Analyze_Component_Declaration (N : Node_Id) is
1717       Id  : constant Entity_Id := Defining_Identifier (N);
1718       E   : constant Node_Id   := Expression (N);
1719       Typ : constant Node_Id   :=
1720               Subtype_Indication (Component_Definition (N));
1721       T   : Entity_Id;
1722       P   : Entity_Id;
1723
1724       function Contains_POC (Constr : Node_Id) return Boolean;
1725       --  Determines whether a constraint uses the discriminant of a record
1726       --  type thus becoming a per-object constraint (POC).
1727
1728       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1729       --  Typ is the type of the current component, check whether this type is
1730       --  a limited type. Used to validate declaration against that of
1731       --  enclosing record.
1732
1733       ------------------
1734       -- Contains_POC --
1735       ------------------
1736
1737       function Contains_POC (Constr : Node_Id) return Boolean is
1738       begin
1739          --  Prevent cascaded errors
1740
1741          if Error_Posted (Constr) then
1742             return False;
1743          end if;
1744
1745          case Nkind (Constr) is
1746             when N_Attribute_Reference =>
1747                return
1748                  Attribute_Name (Constr) = Name_Access
1749                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1750
1751             when N_Discriminant_Association =>
1752                return Denotes_Discriminant (Expression (Constr));
1753
1754             when N_Identifier =>
1755                return Denotes_Discriminant (Constr);
1756
1757             when N_Index_Or_Discriminant_Constraint =>
1758                declare
1759                   IDC : Node_Id;
1760
1761                begin
1762                   IDC := First (Constraints (Constr));
1763                   while Present (IDC) loop
1764
1765                      --  One per-object constraint is sufficient
1766
1767                      if Contains_POC (IDC) then
1768                         return True;
1769                      end if;
1770
1771                      Next (IDC);
1772                   end loop;
1773
1774                   return False;
1775                end;
1776
1777             when N_Range =>
1778                return Denotes_Discriminant (Low_Bound (Constr))
1779                         or else
1780                       Denotes_Discriminant (High_Bound (Constr));
1781
1782             when N_Range_Constraint =>
1783                return Denotes_Discriminant (Range_Expression (Constr));
1784
1785             when others =>
1786                return False;
1787
1788          end case;
1789       end Contains_POC;
1790
1791       ----------------------
1792       -- Is_Known_Limited --
1793       ----------------------
1794
1795       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1796          P : constant Entity_Id := Etype (Typ);
1797          R : constant Entity_Id := Root_Type (Typ);
1798
1799       begin
1800          if Is_Limited_Record (Typ) then
1801             return True;
1802
1803          --  If the root type is limited (and not a limited interface)
1804          --  so is the current type
1805
1806          elsif Is_Limited_Record (R)
1807            and then (not Is_Interface (R) or else not Is_Limited_Interface (R))
1808          then
1809             return True;
1810
1811          --  Else the type may have a limited interface progenitor, but a
1812          --  limited record parent.
1813
1814          elsif R /= P and then Is_Limited_Record (P) then
1815             return True;
1816
1817          else
1818             return False;
1819          end if;
1820       end Is_Known_Limited;
1821
1822    --  Start of processing for Analyze_Component_Declaration
1823
1824    begin
1825       Generate_Definition (Id);
1826       Enter_Name (Id);
1827
1828       if Present (Typ) then
1829          T := Find_Type_Of_Object
1830                 (Subtype_Indication (Component_Definition (N)), N);
1831
1832          if not Nkind_In (Typ, N_Identifier, N_Expanded_Name) then
1833             Check_SPARK_Restriction ("subtype mark required", Typ);
1834          end if;
1835
1836       --  Ada 2005 (AI-230): Access Definition case
1837
1838       else
1839          pragma Assert (Present
1840                           (Access_Definition (Component_Definition (N))));
1841
1842          T := Access_Definition
1843                 (Related_Nod => N,
1844                  N => Access_Definition (Component_Definition (N)));
1845          Set_Is_Local_Anonymous_Access (T);
1846
1847          --  Ada 2005 (AI-254)
1848
1849          if Present (Access_To_Subprogram_Definition
1850                       (Access_Definition (Component_Definition (N))))
1851            and then Protected_Present (Access_To_Subprogram_Definition
1852                                         (Access_Definition
1853                                           (Component_Definition (N))))
1854          then
1855             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1856          end if;
1857       end if;
1858
1859       --  If the subtype is a constrained subtype of the enclosing record,
1860       --  (which must have a partial view) the back-end does not properly
1861       --  handle the recursion. Rewrite the component declaration with an
1862       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1863       --  the tree directly because side effects have already been removed from
1864       --  discriminant constraints.
1865
1866       if Ekind (T) = E_Access_Subtype
1867         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1868         and then Comes_From_Source (T)
1869         and then Nkind (Parent (T)) = N_Subtype_Declaration
1870         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1871       then
1872          Rewrite
1873            (Subtype_Indication (Component_Definition (N)),
1874              New_Copy_Tree (Subtype_Indication (Parent (T))));
1875          T := Find_Type_Of_Object
1876                  (Subtype_Indication (Component_Definition (N)), N);
1877       end if;
1878
1879       --  If the component declaration includes a default expression, then we
1880       --  check that the component is not of a limited type (RM 3.7(5)),
1881       --  and do the special preanalysis of the expression (see section on
1882       --  "Handling of Default and Per-Object Expressions" in the spec of
1883       --  package Sem).
1884
1885       if Present (E) then
1886          Check_SPARK_Restriction ("default expression is not allowed", E);
1887          Preanalyze_Spec_Expression (E, T);
1888          Check_Initialization (T, E);
1889
1890          if Ada_Version >= Ada_2005
1891            and then Ekind (T) = E_Anonymous_Access_Type
1892            and then Etype (E) /= Any_Type
1893          then
1894             --  Check RM 3.9.2(9): "if the expected type for an expression is
1895             --  an anonymous access-to-specific tagged type, then the object
1896             --  designated by the expression shall not be dynamically tagged
1897             --  unless it is a controlling operand in a call on a dispatching
1898             --  operation"
1899
1900             if Is_Tagged_Type (Directly_Designated_Type (T))
1901               and then
1902                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1903               and then
1904                 Ekind (Directly_Designated_Type (Etype (E))) =
1905                   E_Class_Wide_Type
1906             then
1907                Error_Msg_N
1908                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1909             end if;
1910
1911             --  (Ada 2005: AI-230): Accessibility check for anonymous
1912             --  components
1913
1914             if Type_Access_Level (Etype (E)) >
1915                Deepest_Type_Access_Level (T)
1916             then
1917                Error_Msg_N
1918                  ("expression has deeper access level than component " &
1919                   "(RM 3.10.2 (12.2))", E);
1920             end if;
1921
1922             --  The initialization expression is a reference to an access
1923             --  discriminant. The type of the discriminant is always deeper
1924             --  than any access type.
1925
1926             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1927               and then Is_Entity_Name (E)
1928               and then Ekind (Entity (E)) = E_In_Parameter
1929               and then Present (Discriminal_Link (Entity (E)))
1930             then
1931                Error_Msg_N
1932                  ("discriminant has deeper accessibility level than target",
1933                   E);
1934             end if;
1935          end if;
1936       end if;
1937
1938       --  The parent type may be a private view with unknown discriminants,
1939       --  and thus unconstrained. Regular components must be constrained.
1940
1941       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1942          if Is_Class_Wide_Type (T) then
1943             Error_Msg_N
1944                ("class-wide subtype with unknown discriminants" &
1945                  " in component declaration",
1946                  Subtype_Indication (Component_Definition (N)));
1947          else
1948             Error_Msg_N
1949               ("unconstrained subtype in component declaration",
1950                Subtype_Indication (Component_Definition (N)));
1951          end if;
1952
1953       --  Components cannot be abstract, except for the special case of
1954       --  the _Parent field (case of extending an abstract tagged type)
1955
1956       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1957          Error_Msg_N ("type of a component cannot be abstract", N);
1958       end if;
1959
1960       Set_Etype (Id, T);
1961       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1962
1963       --  The component declaration may have a per-object constraint, set
1964       --  the appropriate flag in the defining identifier of the subtype.
1965
1966       if Present (Subtype_Indication (Component_Definition (N))) then
1967          declare
1968             Sindic : constant Node_Id :=
1969                        Subtype_Indication (Component_Definition (N));
1970          begin
1971             if Nkind (Sindic) = N_Subtype_Indication
1972               and then Present (Constraint (Sindic))
1973               and then Contains_POC (Constraint (Sindic))
1974             then
1975                Set_Has_Per_Object_Constraint (Id);
1976             end if;
1977          end;
1978       end if;
1979
1980       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1981       --  out some static checks.
1982
1983       if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (T) then
1984          Null_Exclusion_Static_Checks (N);
1985       end if;
1986
1987       --  If this component is private (or depends on a private type), flag the
1988       --  record type to indicate that some operations are not available.
1989
1990       P := Private_Component (T);
1991
1992       if Present (P) then
1993
1994          --  Check for circular definitions
1995
1996          if P = Any_Type then
1997             Set_Etype (Id, Any_Type);
1998
1999          --  There is a gap in the visibility of operations only if the
2000          --  component type is not defined in the scope of the record type.
2001
2002          elsif Scope (P) = Scope (Current_Scope) then
2003             null;
2004
2005          elsif Is_Limited_Type (P) then
2006             Set_Is_Limited_Composite (Current_Scope);
2007
2008          else
2009             Set_Is_Private_Composite (Current_Scope);
2010          end if;
2011       end if;
2012
2013       if P /= Any_Type
2014         and then Is_Limited_Type (T)
2015         and then Chars (Id) /= Name_uParent
2016         and then Is_Tagged_Type (Current_Scope)
2017       then
2018          if Is_Derived_Type (Current_Scope)
2019            and then not Is_Known_Limited (Current_Scope)
2020          then
2021             Error_Msg_N
2022               ("extension of nonlimited type cannot have limited components",
2023                N);
2024
2025             if Is_Interface (Root_Type (Current_Scope)) then
2026                Error_Msg_N
2027                  ("\limitedness is not inherited from limited interface", N);
2028                Error_Msg_N ("\add LIMITED to type indication", N);
2029             end if;
2030
2031             Explain_Limited_Type (T, N);
2032             Set_Etype (Id, Any_Type);
2033             Set_Is_Limited_Composite (Current_Scope, False);
2034
2035          elsif not Is_Derived_Type (Current_Scope)
2036            and then not Is_Limited_Record (Current_Scope)
2037            and then not Is_Concurrent_Type (Current_Scope)
2038          then
2039             Error_Msg_N
2040               ("nonlimited tagged type cannot have limited components", N);
2041             Explain_Limited_Type (T, N);
2042             Set_Etype (Id, Any_Type);
2043             Set_Is_Limited_Composite (Current_Scope, False);
2044          end if;
2045       end if;
2046
2047       Set_Original_Record_Component (Id, Id);
2048
2049       if Has_Aspects (N) then
2050          Analyze_Aspect_Specifications (N, Id);
2051       end if;
2052
2053       Analyze_Dimension (N);
2054    end Analyze_Component_Declaration;
2055
2056    --------------------------
2057    -- Analyze_Declarations --
2058    --------------------------
2059
2060    procedure Analyze_Declarations (L : List_Id) is
2061       Decl : Node_Id;
2062
2063       procedure Adjust_Decl;
2064       --  Adjust Decl not to include implicit label declarations, since these
2065       --  have strange Sloc values that result in elaboration check problems.
2066       --  (They have the sloc of the label as found in the source, and that
2067       --  is ahead of the current declarative part).
2068
2069       procedure Remove_Visible_Refinements (Spec_Id : Entity_Id);
2070       --  Spec_Id is the entity of a package that may define abstract states.
2071       --  If the states have visible refinement, remove the visibility of each
2072       --  constituent at the end of the package body declarations.
2073
2074       -----------------
2075       -- Adjust_Decl --
2076       -----------------
2077
2078       procedure Adjust_Decl is
2079       begin
2080          while Present (Prev (Decl))
2081            and then Nkind (Decl) = N_Implicit_Label_Declaration
2082          loop
2083             Prev (Decl);
2084          end loop;
2085       end Adjust_Decl;
2086
2087       --------------------------------
2088       -- Remove_Visible_Refinements --
2089       --------------------------------
2090
2091       procedure Remove_Visible_Refinements (Spec_Id : Entity_Id) is
2092          State_Elmt : Elmt_Id;
2093       begin
2094          if Present (Abstract_States (Spec_Id)) then
2095             State_Elmt := First_Elmt (Abstract_States (Spec_Id));
2096             while Present (State_Elmt) loop
2097                Set_Has_Visible_Refinement (Node (State_Elmt), False);
2098                Next_Elmt (State_Elmt);
2099             end loop;
2100          end if;
2101       end Remove_Visible_Refinements;
2102
2103       --  Local variables
2104
2105       Body_Id     : Entity_Id;
2106       Context     : Node_Id;
2107       Freeze_From : Entity_Id := Empty;
2108       Next_Decl   : Node_Id;
2109       Prag        : Node_Id;
2110       Spec_Id     : Entity_Id;
2111
2112       In_Package_Body : Boolean := False;
2113       --  Flag set when the current declaration list belongs to a package body
2114
2115    --  Start of processing for Analyze_Declarations
2116
2117    begin
2118       if Restriction_Check_Required (SPARK_05) then
2119          Check_Later_Vs_Basic_Declarations (L, During_Parsing => False);
2120       end if;
2121
2122       Decl := First (L);
2123       while Present (Decl) loop
2124
2125          --  Package spec cannot contain a package declaration in SPARK
2126
2127          if Nkind (Decl) = N_Package_Declaration
2128            and then Nkind (Parent (L)) = N_Package_Specification
2129          then
2130             Check_SPARK_Restriction
2131               ("package specification cannot contain a package declaration",
2132                Decl);
2133          end if;
2134
2135          --  Complete analysis of declaration
2136
2137          Analyze (Decl);
2138          Next_Decl := Next (Decl);
2139
2140          if No (Freeze_From) then
2141             Freeze_From := First_Entity (Current_Scope);
2142          end if;
2143
2144          --  At the end of a declarative part, freeze remaining entities
2145          --  declared in it. The end of the visible declarations of package
2146          --  specification is not the end of a declarative part if private
2147          --  declarations are present. The end of a package declaration is a
2148          --  freezing point only if it a library package. A task definition or
2149          --  protected type definition is not a freeze point either. Finally,
2150          --  we do not freeze entities in generic scopes, because there is no
2151          --  code generated for them and freeze nodes will be generated for
2152          --  the instance.
2153
2154          --  The end of a package instantiation is not a freeze point, but
2155          --  for now we make it one, because the generic body is inserted
2156          --  (currently) immediately after. Generic instantiations will not
2157          --  be a freeze point once delayed freezing of bodies is implemented.
2158          --  (This is needed in any case for early instantiations ???).
2159
2160          if No (Next_Decl) then
2161             if Nkind_In (Parent (L), N_Component_List,
2162                                      N_Task_Definition,
2163                                      N_Protected_Definition)
2164             then
2165                null;
2166
2167             elsif Nkind (Parent (L)) /= N_Package_Specification then
2168                if Nkind (Parent (L)) = N_Package_Body then
2169                   Freeze_From := First_Entity (Current_Scope);
2170                end if;
2171
2172                Adjust_Decl;
2173                Freeze_All (Freeze_From, Decl);
2174                Freeze_From := Last_Entity (Current_Scope);
2175
2176             elsif Scope (Current_Scope) /= Standard_Standard
2177               and then not Is_Child_Unit (Current_Scope)
2178               and then No (Generic_Parent (Parent (L)))
2179             then
2180                null;
2181
2182             elsif L /= Visible_Declarations (Parent (L))
2183                or else No (Private_Declarations (Parent (L)))
2184                or else Is_Empty_List (Private_Declarations (Parent (L)))
2185             then
2186                Adjust_Decl;
2187                Freeze_All (Freeze_From, Decl);
2188                Freeze_From := Last_Entity (Current_Scope);
2189             end if;
2190
2191          --  If next node is a body then freeze all types before the body.
2192          --  An exception occurs for some expander-generated bodies. If these
2193          --  are generated at places where in general language rules would not
2194          --  allow a freeze point, then we assume that the expander has
2195          --  explicitly checked that all required types are properly frozen,
2196          --  and we do not cause general freezing here. This special circuit
2197          --  is used when the encountered body is marked as having already
2198          --  been analyzed.
2199
2200          --  In all other cases (bodies that come from source, and expander
2201          --  generated bodies that have not been analyzed yet), freeze all
2202          --  types now. Note that in the latter case, the expander must take
2203          --  care to attach the bodies at a proper place in the tree so as to
2204          --  not cause unwanted freezing at that point.
2205
2206          elsif not Analyzed (Next_Decl)
2207            and then (Nkind_In (Next_Decl, N_Subprogram_Body,
2208                                           N_Entry_Body,
2209                                           N_Package_Body,
2210                                           N_Protected_Body,
2211                                           N_Task_Body)
2212                        or else
2213                      Nkind (Next_Decl) in N_Body_Stub)
2214          then
2215             Adjust_Decl;
2216             Freeze_All (Freeze_From, Decl);
2217             Freeze_From := Last_Entity (Current_Scope);
2218          end if;
2219
2220          Decl := Next_Decl;
2221       end loop;
2222
2223       if Present (L) then
2224          Context := Parent (L);
2225
2226          --  Analyze pragmas Initializes and Initial_Condition of a package at
2227          --  the end of the visible declarations as the pragmas have visibility
2228          --  over the said region.
2229
2230          if Nkind (Context) = N_Package_Specification
2231            and then L = Visible_Declarations (Context)
2232          then
2233             Spec_Id := Defining_Entity (Parent (Context));
2234             Prag    := Get_Pragma (Spec_Id, Pragma_Initializes);
2235
2236             if Present (Prag) then
2237                Analyze_Initializes_In_Decl_Part (Prag);
2238             end if;
2239
2240             Prag := Get_Pragma (Spec_Id, Pragma_Initial_Condition);
2241
2242             if Present (Prag) then
2243                Analyze_Initial_Condition_In_Decl_Part (Prag);
2244             end if;
2245
2246          --  Analyze the state refinements within a package body now, after
2247          --  all hidden states have been encountered and freely visible.
2248          --  Refinements must be processed before pragmas Refined_Depends and
2249          --  Refined_Global because the last two may mention constituents.
2250
2251          elsif Nkind (Context) = N_Package_Body then
2252             In_Package_Body := True;
2253
2254             Body_Id := Defining_Entity (Context);
2255             Spec_Id := Corresponding_Spec (Context);
2256             Prag    := Get_Pragma (Body_Id, Pragma_Refined_State);
2257
2258             --  The analysis of pragma Refined_State detects whether the spec
2259             --  has abstract states available for refinement.
2260
2261             if Present (Prag) then
2262                Analyze_Refined_State_In_Decl_Part (Prag);
2263
2264             --  State refinement is required when the package declaration has
2265             --  abstract states. Null states are not considered.
2266
2267             elsif Present (Abstract_States (Spec_Id))
2268               and then not Has_Null_Abstract_State (Spec_Id)
2269             then
2270                Error_Msg_NE
2271                  ("package & requires state refinement", Context, Spec_Id);
2272             end if;
2273          end if;
2274       end if;
2275
2276       --  Analyze the contracts of a subprogram declaration or a body now due
2277       --  to delayed visibility requirements of aspects.
2278
2279       Decl := First (L);
2280       while Present (Decl) loop
2281          if Nkind (Decl) = N_Subprogram_Body then
2282             Analyze_Subprogram_Body_Contract (Defining_Entity (Decl));
2283
2284          elsif Nkind (Decl) = N_Subprogram_Declaration then
2285             Analyze_Subprogram_Contract (Defining_Entity (Decl));
2286          end if;
2287
2288          Next (Decl);
2289       end loop;
2290
2291       --  State refinements are visible upto the end the of the package body
2292       --  declarations. Hide the refinements from visibility to restore the
2293       --  original state conditions.
2294
2295       if In_Package_Body then
2296          Remove_Visible_Refinements (Spec_Id);
2297       end if;
2298    end Analyze_Declarations;
2299
2300    -----------------------------------
2301    -- Analyze_Full_Type_Declaration --
2302    -----------------------------------
2303
2304    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2305       Def    : constant Node_Id   := Type_Definition (N);
2306       Def_Id : constant Entity_Id := Defining_Identifier (N);
2307       T      : Entity_Id;
2308       Prev   : Entity_Id;
2309
2310       Is_Remote : constant Boolean :=
2311                     (Is_Remote_Types (Current_Scope)
2312                        or else Is_Remote_Call_Interface (Current_Scope))
2313                       and then not (In_Private_Part (Current_Scope)
2314                                      or else In_Package_Body (Current_Scope));
2315
2316       procedure Check_Ops_From_Incomplete_Type;
2317       --  If there is a tagged incomplete partial view of the type, traverse
2318       --  the primitives of the incomplete view and change the type of any
2319       --  controlling formals and result to indicate the full view. The
2320       --  primitives will be added to the full type's primitive operations
2321       --  list later in Sem_Disp.Check_Operation_From_Incomplete_Type (which
2322       --  is called from Process_Incomplete_Dependents).
2323
2324       ------------------------------------
2325       -- Check_Ops_From_Incomplete_Type --
2326       ------------------------------------
2327
2328       procedure Check_Ops_From_Incomplete_Type is
2329          Elmt   : Elmt_Id;
2330          Formal : Entity_Id;
2331          Op     : Entity_Id;
2332
2333       begin
2334          if Prev /= T
2335            and then Ekind (Prev) = E_Incomplete_Type
2336            and then Is_Tagged_Type (Prev)
2337            and then Is_Tagged_Type (T)
2338          then
2339             Elmt := First_Elmt (Primitive_Operations (Prev));
2340             while Present (Elmt) loop
2341                Op := Node (Elmt);
2342
2343                Formal := First_Formal (Op);
2344                while Present (Formal) loop
2345                   if Etype (Formal) = Prev then
2346                      Set_Etype (Formal, T);
2347                   end if;
2348
2349                   Next_Formal (Formal);
2350                end loop;
2351
2352                if Etype (Op) = Prev then
2353                   Set_Etype (Op, T);
2354                end if;
2355
2356                Next_Elmt (Elmt);
2357             end loop;
2358          end if;
2359       end Check_Ops_From_Incomplete_Type;
2360
2361    --  Start of processing for Analyze_Full_Type_Declaration
2362
2363    begin
2364       Prev := Find_Type_Name (N);
2365
2366       --  The full view, if present, now points to the current type
2367
2368       --  Ada 2005 (AI-50217): If the type was previously decorated when
2369       --  imported through a LIMITED WITH clause, it appears as incomplete
2370       --  but has no full view.
2371
2372       if Ekind (Prev) = E_Incomplete_Type
2373         and then Present (Full_View (Prev))
2374       then
2375          T := Full_View (Prev);
2376       else
2377          T := Prev;
2378       end if;
2379
2380       Set_Is_Pure (T, Is_Pure (Current_Scope));
2381
2382       --  We set the flag Is_First_Subtype here. It is needed to set the
2383       --  corresponding flag for the Implicit class-wide-type created
2384       --  during tagged types processing.
2385
2386       Set_Is_First_Subtype (T, True);
2387
2388       --  Only composite types other than array types are allowed to have
2389       --  discriminants.
2390
2391       case Nkind (Def) is
2392
2393          --  For derived types, the rule will be checked once we've figured
2394          --  out the parent type.
2395
2396          when N_Derived_Type_Definition =>
2397             null;
2398
2399          --  For record types, discriminants are allowed, unless we are in
2400          --  SPARK.
2401
2402          when N_Record_Definition =>
2403             if Present (Discriminant_Specifications (N)) then
2404                Check_SPARK_Restriction
2405                  ("discriminant type is not allowed",
2406                   Defining_Identifier
2407                     (First (Discriminant_Specifications (N))));
2408             end if;
2409
2410          when others =>
2411             if Present (Discriminant_Specifications (N)) then
2412                Error_Msg_N
2413                  ("elementary or array type cannot have discriminants",
2414                   Defining_Identifier
2415                     (First (Discriminant_Specifications (N))));
2416             end if;
2417       end case;
2418
2419       --  Elaborate the type definition according to kind, and generate
2420       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2421       --  already done (this happens during the reanalysis that follows a call
2422       --  to the high level optimizer).
2423
2424       if not Analyzed (T) then
2425          Set_Analyzed (T);
2426
2427          case Nkind (Def) is
2428
2429             when N_Access_To_Subprogram_Definition =>
2430                Access_Subprogram_Declaration (T, Def);
2431
2432                --  If this is a remote access to subprogram, we must create the
2433                --  equivalent fat pointer type, and related subprograms.
2434
2435                if Is_Remote then
2436                   Process_Remote_AST_Declaration (N);
2437                end if;
2438
2439                --  Validate categorization rule against access type declaration
2440                --  usually a violation in Pure unit, Shared_Passive unit.
2441
2442                Validate_Access_Type_Declaration (T, N);
2443
2444             when N_Access_To_Object_Definition =>
2445                Access_Type_Declaration (T, Def);
2446
2447                --  Validate categorization rule against access type declaration
2448                --  usually a violation in Pure unit, Shared_Passive unit.
2449
2450                Validate_Access_Type_Declaration (T, N);
2451
2452                --  If we are in a Remote_Call_Interface package and define a
2453                --  RACW, then calling stubs and specific stream attributes
2454                --  must be added.
2455
2456                if Is_Remote
2457                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2458                then
2459                   Add_RACW_Features (Def_Id);
2460                end if;
2461
2462                --  Set no strict aliasing flag if config pragma seen
2463
2464                if Opt.No_Strict_Aliasing then
2465                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
2466                end if;
2467
2468             when N_Array_Type_Definition =>
2469                Array_Type_Declaration (T, Def);
2470
2471             when N_Derived_Type_Definition =>
2472                Derived_Type_Declaration (T, N, T /= Def_Id);
2473
2474             when N_Enumeration_Type_Definition =>
2475                Enumeration_Type_Declaration (T, Def);
2476
2477             when N_Floating_Point_Definition =>
2478                Floating_Point_Type_Declaration (T, Def);
2479
2480             when N_Decimal_Fixed_Point_Definition =>
2481                Decimal_Fixed_Point_Type_Declaration (T, Def);
2482
2483             when N_Ordinary_Fixed_Point_Definition =>
2484                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2485
2486             when N_Signed_Integer_Type_Definition =>
2487                Signed_Integer_Type_Declaration (T, Def);
2488
2489             when N_Modular_Type_Definition =>
2490                Modular_Type_Declaration (T, Def);
2491
2492             when N_Record_Definition =>
2493                Record_Type_Declaration (T, N, Prev);
2494
2495             --  If declaration has a parse error, nothing to elaborate.
2496
2497             when N_Error =>
2498                null;
2499
2500             when others =>
2501                raise Program_Error;
2502
2503          end case;
2504       end if;
2505
2506       if Etype (T) = Any_Type then
2507          return;
2508       end if;
2509
2510       --  Controlled type is not allowed in SPARK
2511
2512       if Is_Visibly_Controlled (T) then
2513          Check_SPARK_Restriction ("controlled type is not allowed", N);
2514       end if;
2515
2516       --  Some common processing for all types
2517
2518       Set_Depends_On_Private (T, Has_Private_Component (T));
2519       Check_Ops_From_Incomplete_Type;
2520
2521       --  Both the declared entity, and its anonymous base type if one
2522       --  was created, need freeze nodes allocated.
2523
2524       declare
2525          B : constant Entity_Id := Base_Type (T);
2526
2527       begin
2528          --  In the case where the base type differs from the first subtype, we
2529          --  pre-allocate a freeze node, and set the proper link to the first
2530          --  subtype. Freeze_Entity will use this preallocated freeze node when
2531          --  it freezes the entity.
2532
2533          --  This does not apply if the base type is a generic type, whose
2534          --  declaration is independent of the current derived definition.
2535
2536          if B /= T and then not Is_Generic_Type (B) then
2537             Ensure_Freeze_Node (B);
2538             Set_First_Subtype_Link (Freeze_Node (B), T);
2539          end if;
2540
2541          --  A type that is imported through a limited_with clause cannot
2542          --  generate any code, and thus need not be frozen. However, an access
2543          --  type with an imported designated type needs a finalization list,
2544          --  which may be referenced in some other package that has non-limited
2545          --  visibility on the designated type. Thus we must create the
2546          --  finalization list at the point the access type is frozen, to
2547          --  prevent unsatisfied references at link time.
2548
2549          if not From_With_Type (T) or else Is_Access_Type (T) then
2550             Set_Has_Delayed_Freeze (T);
2551          end if;
2552       end;
2553
2554       --  Case where T is the full declaration of some private type which has
2555       --  been swapped in Defining_Identifier (N).
2556
2557       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2558          Process_Full_View (N, T, Def_Id);
2559
2560          --  Record the reference. The form of this is a little strange, since
2561          --  the full declaration has been swapped in. So the first parameter
2562          --  here represents the entity to which a reference is made which is
2563          --  the "real" entity, i.e. the one swapped in, and the second
2564          --  parameter provides the reference location.
2565
2566          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2567          --  since we don't want a complaint about the full type being an
2568          --  unwanted reference to the private type
2569
2570          declare
2571             B : constant Boolean := Has_Pragma_Unreferenced (T);
2572          begin
2573             Set_Has_Pragma_Unreferenced (T, False);
2574             Generate_Reference (T, T, 'c');
2575             Set_Has_Pragma_Unreferenced (T, B);
2576          end;
2577
2578          Set_Completion_Referenced (Def_Id);
2579
2580       --  For completion of incomplete type, process incomplete dependents
2581       --  and always mark the full type as referenced (it is the incomplete
2582       --  type that we get for any real reference).
2583
2584       elsif Ekind (Prev) = E_Incomplete_Type then
2585          Process_Incomplete_Dependents (N, T, Prev);
2586          Generate_Reference (Prev, Def_Id, 'c');
2587          Set_Completion_Referenced (Def_Id);
2588
2589       --  If not private type or incomplete type completion, this is a real
2590       --  definition of a new entity, so record it.
2591
2592       else
2593          Generate_Definition (Def_Id);
2594       end if;
2595
2596       if Chars (Scope (Def_Id)) = Name_System
2597         and then Chars (Def_Id) = Name_Address
2598         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2599       then
2600          Set_Is_Descendent_Of_Address (Def_Id);
2601          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2602          Set_Is_Descendent_Of_Address (Prev);
2603       end if;
2604
2605       Set_Optimize_Alignment_Flags (Def_Id);
2606       Check_Eliminated (Def_Id);
2607
2608       --  If the declaration is a completion and aspects are present, apply
2609       --  them to the entity for the type which is currently the partial
2610       --  view, but which is the one that will be frozen.
2611
2612       if Has_Aspects (N) then
2613          if Prev /= Def_Id then
2614             Analyze_Aspect_Specifications (N, Prev);
2615          else
2616             Analyze_Aspect_Specifications (N, Def_Id);
2617          end if;
2618       end if;
2619    end Analyze_Full_Type_Declaration;
2620
2621    ----------------------------------
2622    -- Analyze_Incomplete_Type_Decl --
2623    ----------------------------------
2624
2625    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2626       F : constant Boolean := Is_Pure (Current_Scope);
2627       T : Entity_Id;
2628
2629    begin
2630       Check_SPARK_Restriction ("incomplete type is not allowed", N);
2631
2632       Generate_Definition (Defining_Identifier (N));
2633
2634       --  Process an incomplete declaration. The identifier must not have been
2635       --  declared already in the scope. However, an incomplete declaration may
2636       --  appear in the private part of a package, for a private type that has
2637       --  already been declared.
2638
2639       --  In this case, the discriminants (if any) must match
2640
2641       T := Find_Type_Name (N);
2642
2643       Set_Ekind (T, E_Incomplete_Type);
2644       Init_Size_Align (T);
2645       Set_Is_First_Subtype (T, True);
2646       Set_Etype (T, T);
2647
2648       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2649       --  incomplete types.
2650
2651       if Tagged_Present (N) then
2652          Set_Is_Tagged_Type (T);
2653          Make_Class_Wide_Type (T);
2654          Set_Direct_Primitive_Operations (T, New_Elmt_List);
2655       end if;
2656
2657       Push_Scope (T);
2658
2659       Set_Stored_Constraint (T, No_Elist);
2660
2661       if Present (Discriminant_Specifications (N)) then
2662          Process_Discriminants (N);
2663       end if;
2664
2665       End_Scope;
2666
2667       --  If the type has discriminants, non-trivial subtypes may be
2668       --  declared before the full view of the type. The full views of those
2669       --  subtypes will be built after the full view of the type.
2670
2671       Set_Private_Dependents (T, New_Elmt_List);
2672       Set_Is_Pure            (T, F);
2673    end Analyze_Incomplete_Type_Decl;
2674
2675    -----------------------------------
2676    -- Analyze_Interface_Declaration --
2677    -----------------------------------
2678
2679    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2680       CW : constant Entity_Id := Class_Wide_Type (T);
2681
2682    begin
2683       Set_Is_Tagged_Type (T);
2684
2685       Set_Is_Limited_Record (T, Limited_Present (Def)
2686                                   or else Task_Present (Def)
2687                                   or else Protected_Present (Def)
2688                                   or else Synchronized_Present (Def));
2689
2690       --  Type is abstract if full declaration carries keyword, or if previous
2691       --  partial view did.
2692
2693       Set_Is_Abstract_Type (T);
2694       Set_Is_Interface (T);
2695
2696       --  Type is a limited interface if it includes the keyword limited, task,
2697       --  protected, or synchronized.
2698
2699       Set_Is_Limited_Interface
2700         (T, Limited_Present (Def)
2701               or else Protected_Present (Def)
2702               or else Synchronized_Present (Def)
2703               or else Task_Present (Def));
2704
2705       Set_Interfaces (T, New_Elmt_List);
2706       Set_Direct_Primitive_Operations (T, New_Elmt_List);
2707
2708       --  Complete the decoration of the class-wide entity if it was already
2709       --  built (i.e. during the creation of the limited view)
2710
2711       if Present (CW) then
2712          Set_Is_Interface (CW);
2713          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2714       end if;
2715
2716       --  Check runtime support for synchronized interfaces
2717
2718       if VM_Target = No_VM
2719         and then (Is_Task_Interface (T)
2720                    or else Is_Protected_Interface (T)
2721                    or else Is_Synchronized_Interface (T))
2722         and then not RTE_Available (RE_Select_Specific_Data)
2723       then
2724          Error_Msg_CRT ("synchronized interfaces", T);
2725       end if;
2726    end Analyze_Interface_Declaration;
2727
2728    -----------------------------
2729    -- Analyze_Itype_Reference --
2730    -----------------------------
2731
2732    --  Nothing to do. This node is placed in the tree only for the benefit of
2733    --  back end processing, and has no effect on the semantic processing.
2734
2735    procedure Analyze_Itype_Reference (N : Node_Id) is
2736    begin
2737       pragma Assert (Is_Itype (Itype (N)));
2738       null;
2739    end Analyze_Itype_Reference;
2740
2741    --------------------------------
2742    -- Analyze_Number_Declaration --
2743    --------------------------------
2744
2745    procedure Analyze_Number_Declaration (N : Node_Id) is
2746       Id    : constant Entity_Id := Defining_Identifier (N);
2747       E     : constant Node_Id   := Expression (N);
2748       T     : Entity_Id;
2749       Index : Interp_Index;
2750       It    : Interp;
2751
2752    begin
2753       Generate_Definition (Id);
2754       Enter_Name (Id);
2755
2756       --  This is an optimization of a common case of an integer literal
2757
2758       if Nkind (E) = N_Integer_Literal then
2759          Set_Is_Static_Expression (E, True);
2760          Set_Etype                (E, Universal_Integer);
2761
2762          Set_Etype     (Id, Universal_Integer);
2763          Set_Ekind     (Id, E_Named_Integer);
2764          Set_Is_Frozen (Id, True);
2765          return;
2766       end if;
2767
2768       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2769
2770       --  Process expression, replacing error by integer zero, to avoid
2771       --  cascaded errors or aborts further along in the processing
2772
2773       --  Replace Error by integer zero, which seems least likely to cause
2774       --  cascaded errors.
2775
2776       if E = Error then
2777          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2778          Set_Error_Posted (E);
2779       end if;
2780
2781       Analyze (E);
2782
2783       --  Verify that the expression is static and numeric. If
2784       --  the expression is overloaded, we apply the preference
2785       --  rule that favors root numeric types.
2786
2787       if not Is_Overloaded (E) then
2788          T := Etype (E);
2789
2790       else
2791          T := Any_Type;
2792
2793          Get_First_Interp (E, Index, It);
2794          while Present (It.Typ) loop
2795             if (Is_Integer_Type (It.Typ) or else Is_Real_Type (It.Typ))
2796               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2797             then
2798                if T = Any_Type then
2799                   T := It.Typ;
2800
2801                elsif It.Typ = Universal_Real
2802                  or else It.Typ = Universal_Integer
2803                then
2804                   --  Choose universal interpretation over any other
2805
2806                   T := It.Typ;
2807                   exit;
2808                end if;
2809             end if;
2810
2811             Get_Next_Interp (Index, It);
2812          end loop;
2813       end if;
2814
2815       if Is_Integer_Type (T)  then
2816          Resolve (E, T);
2817          Set_Etype (Id, Universal_Integer);
2818          Set_Ekind (Id, E_Named_Integer);
2819
2820       elsif Is_Real_Type (T) then
2821
2822          --  Because the real value is converted to universal_real, this is a
2823          --  legal context for a universal fixed expression.
2824
2825          if T = Universal_Fixed then
2826             declare
2827                Loc  : constant Source_Ptr := Sloc (N);
2828                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2829                         Subtype_Mark =>
2830                           New_Occurrence_Of (Universal_Real, Loc),
2831                         Expression => Relocate_Node (E));
2832
2833             begin
2834                Rewrite (E, Conv);
2835                Analyze (E);
2836             end;
2837
2838          elsif T = Any_Fixed then
2839             Error_Msg_N ("illegal context for mixed mode operation", E);
2840
2841             --  Expression is of the form : universal_fixed * integer. Try to
2842             --  resolve as universal_real.
2843
2844             T := Universal_Real;
2845             Set_Etype (E, T);
2846          end if;
2847
2848          Resolve (E, T);
2849          Set_Etype (Id, Universal_Real);
2850          Set_Ekind (Id, E_Named_Real);
2851
2852       else
2853          Wrong_Type (E, Any_Numeric);
2854          Resolve (E, T);
2855
2856          Set_Etype               (Id, T);
2857          Set_Ekind               (Id, E_Constant);
2858          Set_Never_Set_In_Source (Id, True);
2859          Set_Is_True_Constant    (Id, True);
2860          return;
2861       end if;
2862
2863       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2864          Set_Etype (E, Etype (Id));
2865       end if;
2866
2867       if not Is_OK_Static_Expression (E) then
2868          Flag_Non_Static_Expr
2869            ("non-static expression used in number declaration!", E);
2870          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2871          Set_Etype (E, Any_Type);
2872       end if;
2873    end Analyze_Number_Declaration;
2874
2875    --------------------------------
2876    -- Analyze_Object_Declaration --
2877    --------------------------------
2878
2879    procedure Analyze_Object_Declaration (N : Node_Id) is
2880       Loc   : constant Source_Ptr := Sloc (N);
2881       Id    : constant Entity_Id  := Defining_Identifier (N);
2882       T     : Entity_Id;
2883       Act_T : Entity_Id;
2884
2885       E : Node_Id := Expression (N);
2886       --  E is set to Expression (N) throughout this routine. When
2887       --  Expression (N) is modified, E is changed accordingly.
2888
2889       Prev_Entity : Entity_Id := Empty;
2890
2891       function Count_Tasks (T : Entity_Id) return Uint;
2892       --  This function is called when a non-generic library level object of a
2893       --  task type is declared. Its function is to count the static number of
2894       --  tasks declared within the type (it is only called if Has_Tasks is set
2895       --  for T). As a side effect, if an array of tasks with non-static bounds
2896       --  or a variant record type is encountered, Check_Restrictions is called
2897       --  indicating the count is unknown.
2898
2899       -----------------
2900       -- Count_Tasks --
2901       -----------------
2902
2903       function Count_Tasks (T : Entity_Id) return Uint is
2904          C : Entity_Id;
2905          X : Node_Id;
2906          V : Uint;
2907
2908       begin
2909          if Is_Task_Type (T) then
2910             return Uint_1;
2911
2912          elsif Is_Record_Type (T) then
2913             if Has_Discriminants (T) then
2914                Check_Restriction (Max_Tasks, N);
2915                return Uint_0;
2916
2917             else
2918                V := Uint_0;
2919                C := First_Component (T);
2920                while Present (C) loop
2921                   V := V + Count_Tasks (Etype (C));
2922                   Next_Component (C);
2923                end loop;
2924
2925                return V;
2926             end if;
2927
2928          elsif Is_Array_Type (T) then
2929             X := First_Index (T);
2930             V := Count_Tasks (Component_Type (T));
2931             while Present (X) loop
2932                C := Etype (X);
2933
2934                if not Is_Static_Subtype (C) then
2935                   Check_Restriction (Max_Tasks, N);
2936                   return Uint_0;
2937                else
2938                   V := V * (UI_Max (Uint_0,
2939                                     Expr_Value (Type_High_Bound (C)) -
2940                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2941                end if;
2942
2943                Next_Index (X);
2944             end loop;
2945
2946             return V;
2947
2948          else
2949             return Uint_0;
2950          end if;
2951       end Count_Tasks;
2952
2953    --  Start of processing for Analyze_Object_Declaration
2954
2955    begin
2956       --  There are three kinds of implicit types generated by an
2957       --  object declaration:
2958
2959       --   1. Those generated by the original Object Definition
2960
2961       --   2. Those generated by the Expression
2962
2963       --   3. Those used to constrain the Object Definition with the
2964       --      expression constraints when the definition is unconstrained.
2965
2966       --  They must be generated in this order to avoid order of elaboration
2967       --  issues. Thus the first step (after entering the name) is to analyze
2968       --  the object definition.
2969
2970       if Constant_Present (N) then
2971          Prev_Entity := Current_Entity_In_Scope (Id);
2972
2973          if Present (Prev_Entity)
2974            and then
2975
2976              --  If the homograph is an implicit subprogram, it is overridden
2977              --  by the current declaration.
2978
2979              ((Is_Overloadable (Prev_Entity)
2980                 and then Is_Inherited_Operation (Prev_Entity))
2981
2982                --  The current object is a discriminal generated for an entry
2983                --  family index. Even though the index is a constant, in this
2984                --  particular context there is no true constant redeclaration.
2985                --  Enter_Name will handle the visibility.
2986
2987                or else
2988                 (Is_Discriminal (Id)
2989                    and then Ekind (Discriminal_Link (Id)) =
2990                               E_Entry_Index_Parameter)
2991
2992                --  The current object is the renaming for a generic declared
2993                --  within the instance.
2994
2995                or else
2996                 (Ekind (Prev_Entity) = E_Package
2997                   and then Nkind (Parent (Prev_Entity)) =
2998                                          N_Package_Renaming_Declaration
2999                   and then not Comes_From_Source (Prev_Entity)
3000                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
3001          then
3002             Prev_Entity := Empty;
3003          end if;
3004       end if;
3005
3006       if Present (Prev_Entity) then
3007          Constant_Redeclaration (Id, N, T);
3008
3009          Generate_Reference (Prev_Entity, Id, 'c');
3010          Set_Completion_Referenced (Id);
3011
3012          if Error_Posted (N) then
3013
3014             --  Type mismatch or illegal redeclaration, Do not analyze
3015             --  expression to avoid cascaded errors.
3016
3017             T := Find_Type_Of_Object (Object_Definition (N), N);
3018             Set_Etype (Id, T);
3019             Set_Ekind (Id, E_Variable);
3020             goto Leave;
3021          end if;
3022
3023       --  In the normal case, enter identifier at the start to catch premature
3024       --  usage in the initialization expression.
3025
3026       else
3027          Generate_Definition (Id);
3028          Enter_Name (Id);
3029
3030          Mark_Coextensions (N, Object_Definition (N));
3031
3032          T := Find_Type_Of_Object (Object_Definition (N), N);
3033
3034          if Nkind (Object_Definition (N)) = N_Access_Definition
3035            and then Present
3036                       (Access_To_Subprogram_Definition (Object_Definition (N)))
3037            and then Protected_Present
3038                       (Access_To_Subprogram_Definition (Object_Definition (N)))
3039          then
3040             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
3041          end if;
3042
3043          if Error_Posted (Id) then
3044             Set_Etype (Id, T);
3045             Set_Ekind (Id, E_Variable);
3046             goto Leave;
3047          end if;
3048       end if;
3049
3050       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
3051       --  out some static checks
3052
3053       if Ada_Version >= Ada_2005
3054         and then Can_Never_Be_Null (T)
3055       then
3056          --  In case of aggregates we must also take care of the correct
3057          --  initialization of nested aggregates bug this is done at the
3058          --  point of the analysis of the aggregate (see sem_aggr.adb)
3059
3060          if Present (Expression (N))
3061            and then Nkind (Expression (N)) = N_Aggregate
3062          then
3063             null;
3064
3065          else
3066             declare
3067                Save_Typ : constant Entity_Id := Etype (Id);
3068             begin
3069                Set_Etype (Id, T); --  Temp. decoration for static checks
3070                Null_Exclusion_Static_Checks (N);
3071                Set_Etype (Id, Save_Typ);
3072             end;
3073          end if;
3074       end if;
3075
3076       --  Object is marked pure if it is in a pure scope
3077
3078       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3079
3080       --  If deferred constant, make sure context is appropriate. We detect
3081       --  a deferred constant as a constant declaration with no expression.
3082       --  A deferred constant can appear in a package body if its completion
3083       --  is by means of an interface pragma.
3084
3085       if Constant_Present (N) and then No (E) then
3086
3087          --  A deferred constant may appear in the declarative part of the
3088          --  following constructs:
3089
3090          --     blocks
3091          --     entry bodies
3092          --     extended return statements
3093          --     package specs
3094          --     package bodies
3095          --     subprogram bodies
3096          --     task bodies
3097
3098          --  When declared inside a package spec, a deferred constant must be
3099          --  completed by a full constant declaration or pragma Import. In all
3100          --  other cases, the only proper completion is pragma Import. Extended
3101          --  return statements are flagged as invalid contexts because they do
3102          --  not have a declarative part and so cannot accommodate the pragma.
3103
3104          if Ekind (Current_Scope) = E_Return_Statement then
3105             Error_Msg_N
3106               ("invalid context for deferred constant declaration (RM 7.4)",
3107                N);
3108             Error_Msg_N
3109               ("\declaration requires an initialization expression",
3110                 N);
3111             Set_Constant_Present (N, False);
3112
3113          --  In Ada 83, deferred constant must be of private type
3114
3115          elsif not Is_Private_Type (T) then
3116             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
3117                Error_Msg_N
3118                  ("(Ada 83) deferred constant must be private type", N);
3119             end if;
3120          end if;
3121
3122       --  If not a deferred constant, then object declaration freezes its type
3123
3124       else
3125          Check_Fully_Declared (T, N);
3126          Freeze_Before (N, T);
3127       end if;
3128
3129       --  If the object was created by a constrained array definition, then
3130       --  set the link in both the anonymous base type and anonymous subtype
3131       --  that are built to represent the array type to point to the object.
3132
3133       if Nkind (Object_Definition (Declaration_Node (Id))) =
3134                         N_Constrained_Array_Definition
3135       then
3136          Set_Related_Array_Object (T, Id);
3137          Set_Related_Array_Object (Base_Type (T), Id);
3138       end if;
3139
3140       --  Special checks for protected objects not at library level
3141
3142       if Is_Protected_Type (T)
3143         and then not Is_Library_Level_Entity (Id)
3144       then
3145          Check_Restriction (No_Local_Protected_Objects, Id);
3146
3147          --  Protected objects with interrupt handlers must be at library level
3148
3149          --  Ada 2005: this test is not needed (and the corresponding clause
3150          --  in the RM is removed) because accessibility checks are sufficient
3151          --  to make handlers not at the library level illegal.
3152
3153          --  AI05-0303: the AI is in fact a binding interpretation, and thus
3154          --  applies to the '95 version of the language as well.
3155
3156          if Has_Interrupt_Handler (T) and then Ada_Version < Ada_95 then
3157             Error_Msg_N
3158               ("interrupt object can only be declared at library level", Id);
3159          end if;
3160       end if;
3161
3162       --  The actual subtype of the object is the nominal subtype, unless
3163       --  the nominal one is unconstrained and obtained from the expression.
3164
3165       Act_T := T;
3166
3167       --  These checks should be performed before the initialization expression
3168       --  is considered, so that the Object_Definition node is still the same
3169       --  as in source code.
3170
3171       --  In SPARK, the nominal subtype shall be given by a subtype mark and
3172       --  shall not be unconstrained. (The only exception to this is the
3173       --  admission of declarations of constants of type String.)
3174
3175       if not
3176         Nkind_In (Object_Definition (N), N_Identifier, N_Expanded_Name)
3177       then
3178          Check_SPARK_Restriction
3179            ("subtype mark required", Object_Definition (N));
3180
3181       elsif Is_Array_Type (T)
3182         and then not Is_Constrained (T)
3183         and then T /= Standard_String
3184       then
3185          Check_SPARK_Restriction
3186            ("subtype mark of constrained type expected",
3187             Object_Definition (N));
3188       end if;
3189
3190       --  There are no aliased objects in SPARK
3191
3192       if Aliased_Present (N) then
3193          Check_SPARK_Restriction ("aliased object is not allowed", N);
3194       end if;
3195
3196       --  Process initialization expression if present and not in error
3197
3198       if Present (E) and then E /= Error then
3199
3200          --  Generate an error in case of CPP class-wide object initialization.
3201          --  Required because otherwise the expansion of the class-wide
3202          --  assignment would try to use 'size to initialize the object
3203          --  (primitive that is not available in CPP tagged types).
3204
3205          if Is_Class_Wide_Type (Act_T)
3206            and then
3207              (Is_CPP_Class (Root_Type (Etype (Act_T)))
3208                or else
3209                  (Present (Full_View (Root_Type (Etype (Act_T))))
3210                    and then
3211                      Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
3212          then
3213             Error_Msg_N
3214               ("predefined assignment not available for 'C'P'P tagged types",
3215                E);
3216          end if;
3217
3218          Mark_Coextensions (N, E);
3219          Analyze (E);
3220
3221          --  In case of errors detected in the analysis of the expression,
3222          --  decorate it with the expected type to avoid cascaded errors
3223
3224          if No (Etype (E)) then
3225             Set_Etype (E, T);
3226          end if;
3227
3228          --  If an initialization expression is present, then we set the
3229          --  Is_True_Constant flag. It will be reset if this is a variable
3230          --  and it is indeed modified.
3231
3232          Set_Is_True_Constant (Id, True);
3233
3234          --  If we are analyzing a constant declaration, set its completion
3235          --  flag after analyzing and resolving the expression.
3236
3237          if Constant_Present (N) then
3238             Set_Has_Completion (Id);
3239          end if;
3240
3241          --  Set type and resolve (type may be overridden later on). Note:
3242          --  Ekind (Id) must still be E_Void at this point so that incorrect
3243          --  early usage within E is properly diagnosed.
3244
3245          Set_Etype (Id, T);
3246          Resolve (E, T);
3247
3248          --  No further action needed if E is a call to an inlined function
3249          --  which returns an unconstrained type and it has been expanded into
3250          --  a procedure call. In that case N has been replaced by an object
3251          --  declaration without initializing expression and it has been
3252          --  analyzed (see Expand_Inlined_Call).
3253
3254          if Debug_Flag_Dot_K
3255            and then Expander_Active
3256            and then Nkind (E) = N_Function_Call
3257            and then Nkind (Name (E)) in N_Has_Entity
3258            and then Is_Inlined (Entity (Name (E)))
3259            and then not Is_Constrained (Etype (E))
3260            and then Analyzed (N)
3261            and then No (Expression (N))
3262          then
3263             return;
3264          end if;
3265
3266          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3267          --  node (which was marked already-analyzed), we need to set the type
3268          --  to something other than Any_Access in order to keep gigi happy.
3269
3270          if Etype (E) = Any_Access then
3271             Set_Etype (E, T);
3272          end if;
3273
3274          --  If the object is an access to variable, the initialization
3275          --  expression cannot be an access to constant.
3276
3277          if Is_Access_Type (T)
3278            and then not Is_Access_Constant (T)
3279            and then Is_Access_Type (Etype (E))
3280            and then Is_Access_Constant (Etype (E))
3281          then
3282             Error_Msg_N
3283               ("access to variable cannot be initialized "
3284                & "with an access-to-constant expression", E);
3285          end if;
3286
3287          if not Assignment_OK (N) then
3288             Check_Initialization (T, E);
3289          end if;
3290
3291          Check_Unset_Reference (E);
3292
3293          --  If this is a variable, then set current value. If this is a
3294          --  declared constant of a scalar type with a static expression,
3295          --  indicate that it is always valid.
3296
3297          if not Constant_Present (N) then
3298             if Compile_Time_Known_Value (E) then
3299                Set_Current_Value (Id, E);
3300             end if;
3301
3302          elsif Is_Scalar_Type (T)
3303            and then Is_OK_Static_Expression (E)
3304          then
3305             Set_Is_Known_Valid (Id);
3306          end if;
3307
3308          --  Deal with setting of null flags
3309
3310          if Is_Access_Type (T) then
3311             if Known_Non_Null (E) then
3312                Set_Is_Known_Non_Null (Id, True);
3313             elsif Known_Null (E)
3314               and then not Can_Never_Be_Null (Id)
3315             then
3316                Set_Is_Known_Null (Id, True);
3317             end if;
3318          end if;
3319
3320          --  Check incorrect use of dynamically tagged expressions
3321
3322          if Is_Tagged_Type (T) then
3323             Check_Dynamically_Tagged_Expression
3324               (Expr        => E,
3325                Typ         => T,
3326                Related_Nod => N);
3327          end if;
3328
3329          Apply_Scalar_Range_Check (E, T);
3330          Apply_Static_Length_Check (E, T);
3331
3332          if Nkind (Original_Node (N)) = N_Object_Declaration
3333            and then Comes_From_Source (Original_Node (N))
3334
3335            --  Only call test if needed
3336
3337            and then Restriction_Check_Required (SPARK_05)
3338            and then not Is_SPARK_Initialization_Expr (Original_Node (E))
3339          then
3340             Check_SPARK_Restriction
3341               ("initialization expression is not appropriate", E);
3342          end if;
3343       end if;
3344
3345       --  If the No_Streams restriction is set, check that the type of the
3346       --  object is not, and does not contain, any subtype derived from
3347       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3348       --  Has_Stream just for efficiency reasons. There is no point in
3349       --  spending time on a Has_Stream check if the restriction is not set.
3350
3351       if Restriction_Check_Required (No_Streams) then
3352          if Has_Stream (T) then
3353             Check_Restriction (No_Streams, N);
3354          end if;
3355       end if;
3356
3357       --  Deal with predicate check before we start to do major rewriting. It
3358       --  is OK to initialize and then check the initialized value, since the
3359       --  object goes out of scope if we get a predicate failure. Note that we
3360       --  do this in the analyzer and not the expander because the analyzer
3361       --  does some substantial rewriting in some cases.
3362
3363       --  We need a predicate check if the type has predicates, and if either
3364       --  there is an initializing expression, or for default initialization
3365       --  when we have at least one case of an explicit default initial value.
3366
3367       if not Suppress_Assignment_Checks (N)
3368         and then Present (Predicate_Function (T))
3369         and then
3370           (Present (E)
3371             or else
3372               Is_Partially_Initialized_Type (T, Include_Implicit => False))
3373       then
3374          --  If the type has a static predicate and the expression is known at
3375          --  compile time, see if the expression satisfies the predicate.
3376
3377          if Present (E) then
3378             Check_Expression_Against_Static_Predicate (E, T);
3379          end if;
3380
3381          Insert_After (N,
3382            Make_Predicate_Check (T, New_Occurrence_Of (Id, Loc)));
3383       end if;
3384
3385       --  Case of unconstrained type
3386
3387       if Is_Indefinite_Subtype (T) then
3388
3389          --  In SPARK, a declaration of unconstrained type is allowed
3390          --  only for constants of type string.
3391
3392          if Is_String_Type (T) and then not Constant_Present (N) then
3393             Check_SPARK_Restriction
3394               ("declaration of object of unconstrained type not allowed", N);
3395          end if;
3396
3397          --  Nothing to do in deferred constant case
3398
3399          if Constant_Present (N) and then No (E) then
3400             null;
3401
3402          --  Case of no initialization present
3403
3404          elsif No (E) then
3405             if No_Initialization (N) then
3406                null;
3407
3408             elsif Is_Class_Wide_Type (T) then
3409                Error_Msg_N
3410                  ("initialization required in class-wide declaration ", N);
3411
3412             else
3413                Error_Msg_N
3414                  ("unconstrained subtype not allowed (need initialization)",
3415                   Object_Definition (N));
3416
3417                if Is_Record_Type (T) and then Has_Discriminants (T) then
3418                   Error_Msg_N
3419                     ("\provide initial value or explicit discriminant values",
3420                      Object_Definition (N));
3421
3422                   Error_Msg_NE
3423                     ("\or give default discriminant values for type&",
3424                      Object_Definition (N), T);
3425
3426                elsif Is_Array_Type (T) then
3427                   Error_Msg_N
3428                     ("\provide initial value or explicit array bounds",
3429                      Object_Definition (N));
3430                end if;
3431             end if;
3432
3433          --  Case of initialization present but in error. Set initial
3434          --  expression as absent (but do not make above complaints)
3435
3436          elsif E = Error then
3437             Set_Expression (N, Empty);
3438             E := Empty;
3439
3440          --  Case of initialization present
3441
3442          else
3443             --  Check restrictions in Ada 83
3444
3445             if not Constant_Present (N) then
3446
3447                --  Unconstrained variables not allowed in Ada 83 mode
3448
3449                if Ada_Version = Ada_83
3450                  and then Comes_From_Source (Object_Definition (N))
3451                then
3452                   Error_Msg_N
3453                     ("(Ada 83) unconstrained variable not allowed",
3454                      Object_Definition (N));
3455                end if;
3456             end if;
3457
3458             --  Now we constrain the variable from the initializing expression
3459
3460             --  If the expression is an aggregate, it has been expanded into
3461             --  individual assignments. Retrieve the actual type from the
3462             --  expanded construct.
3463
3464             if Is_Array_Type (T)
3465               and then No_Initialization (N)
3466               and then Nkind (Original_Node (E)) = N_Aggregate
3467             then
3468                Act_T := Etype (E);
3469
3470             --  In case of class-wide interface object declarations we delay
3471             --  the generation of the equivalent record type declarations until
3472             --  its expansion because there are cases in they are not required.
3473
3474             elsif Is_Interface (T) then
3475                null;
3476
3477             else
3478                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3479                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3480             end if;
3481
3482             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3483
3484             if Aliased_Present (N) then
3485                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3486             end if;
3487
3488             Freeze_Before (N, Act_T);
3489             Freeze_Before (N, T);
3490          end if;
3491
3492       elsif Is_Array_Type (T)
3493         and then No_Initialization (N)
3494         and then Nkind (Original_Node (E)) = N_Aggregate
3495       then
3496          if not Is_Entity_Name (Object_Definition (N)) then
3497             Act_T := Etype (E);
3498             Check_Compile_Time_Size (Act_T);
3499
3500             if Aliased_Present (N) then
3501                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3502             end if;
3503          end if;
3504
3505          --  When the given object definition and the aggregate are specified
3506          --  independently, and their lengths might differ do a length check.
3507          --  This cannot happen if the aggregate is of the form (others =>...)
3508
3509          if not Is_Constrained (T) then
3510             null;
3511
3512          elsif Nkind (E) = N_Raise_Constraint_Error then
3513
3514             --  Aggregate is statically illegal. Place back in declaration
3515
3516             Set_Expression (N, E);
3517             Set_No_Initialization (N, False);
3518
3519          elsif T = Etype (E) then
3520             null;
3521
3522          elsif Nkind (E) = N_Aggregate
3523            and then Present (Component_Associations (E))
3524            and then Present (Choices (First (Component_Associations (E))))
3525            and then Nkind (First
3526             (Choices (First (Component_Associations (E))))) = N_Others_Choice
3527          then
3528             null;
3529
3530          else
3531             Apply_Length_Check (E, T);
3532          end if;
3533
3534       --  If the type is limited unconstrained with defaulted discriminants and
3535       --  there is no expression, then the object is constrained by the
3536       --  defaults, so it is worthwhile building the corresponding subtype.
3537
3538       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
3539         and then not Is_Constrained (T)
3540         and then Has_Discriminants (T)
3541       then
3542          if No (E) then
3543             Act_T := Build_Default_Subtype (T, N);
3544          else
3545             --  Ada 2005:  a limited object may be initialized by means of an
3546             --  aggregate. If the type has default discriminants it has an
3547             --  unconstrained nominal type, Its actual subtype will be obtained
3548             --  from the aggregate, and not from the default discriminants.
3549
3550             Act_T := Etype (E);
3551          end if;
3552
3553          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
3554
3555       elsif Present (Underlying_Type (T))
3556         and then not Is_Constrained (Underlying_Type (T))
3557         and then Has_Discriminants (Underlying_Type (T))
3558         and then Nkind (E) = N_Function_Call
3559         and then Constant_Present (N)
3560       then
3561          --  The back-end has problems with constants of a discriminated type
3562          --  with defaults, if the initial value is a function call. We
3563          --  generate an intermediate temporary for the result of the call.
3564          --  It is unclear why this should make it acceptable to gcc. ???
3565
3566          Remove_Side_Effects (E);
3567
3568       --  If this is a constant declaration of an unconstrained type and
3569       --  the initialization is an aggregate, we can use the subtype of the
3570       --  aggregate for the declared entity because it is immutable.
3571
3572       elsif not Is_Constrained (T)
3573         and then Has_Discriminants (T)
3574         and then Constant_Present (N)
3575         and then not Has_Unchecked_Union (T)
3576         and then Nkind (E) = N_Aggregate
3577       then
3578          Act_T := Etype (E);
3579       end if;
3580
3581       --  Check No_Wide_Characters restriction
3582
3583       Check_Wide_Character_Restriction (T, Object_Definition (N));
3584
3585       --  Indicate this is not set in source. Certainly true for constants, and
3586       --  true for variables so far (will be reset for a variable if and when
3587       --  we encounter a modification in the source).
3588
3589       Set_Never_Set_In_Source (Id, True);
3590
3591       --  Now establish the proper kind and type of the object
3592
3593       if Constant_Present (N) then
3594          Set_Ekind            (Id, E_Constant);
3595          Set_Is_True_Constant (Id);
3596
3597       else
3598          Set_Ekind (Id, E_Variable);
3599
3600          --  A variable is set as shared passive if it appears in a shared
3601          --  passive package, and is at the outer level. This is not done for
3602          --  entities generated during expansion, because those are always
3603          --  manipulated locally.
3604
3605          if Is_Shared_Passive (Current_Scope)
3606            and then Is_Library_Level_Entity (Id)
3607            and then Comes_From_Source (Id)
3608          then
3609             Set_Is_Shared_Passive (Id);
3610             Check_Shared_Var (Id, T, N);
3611          end if;
3612
3613          --  Set Has_Initial_Value if initializing expression present. Note
3614          --  that if there is no initializing expression, we leave the state
3615          --  of this flag unchanged (usually it will be False, but notably in
3616          --  the case of exception choice variables, it will already be true).
3617
3618          if Present (E) then
3619             Set_Has_Initial_Value (Id, True);
3620          end if;
3621       end if;
3622
3623       --  Initialize alignment and size and capture alignment setting
3624
3625       Init_Alignment               (Id);
3626       Init_Esize                   (Id);
3627       Set_Optimize_Alignment_Flags (Id);
3628
3629       --  Deal with aliased case
3630
3631       if Aliased_Present (N) then
3632          Set_Is_Aliased (Id);
3633
3634          --  If the object is aliased and the type is unconstrained with
3635          --  defaulted discriminants and there is no expression, then the
3636          --  object is constrained by the defaults, so it is worthwhile
3637          --  building the corresponding subtype.
3638
3639          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3640          --  unconstrained, then only establish an actual subtype if the
3641          --  nominal subtype is indefinite. In definite cases the object is
3642          --  unconstrained in Ada 2005.
3643
3644          if No (E)
3645            and then Is_Record_Type (T)
3646            and then not Is_Constrained (T)
3647            and then Has_Discriminants (T)
3648            and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
3649          then
3650             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3651          end if;
3652       end if;
3653
3654       --  Now we can set the type of the object
3655
3656       Set_Etype (Id, Act_T);
3657
3658       --  Object is marked to be treated as volatile if type is volatile and
3659       --  we clear the Current_Value setting that may have been set above.
3660
3661       if Treat_As_Volatile (Etype (Id)) then
3662          Set_Treat_As_Volatile (Id);
3663          Set_Current_Value (Id, Empty);
3664       end if;
3665
3666       --  Deal with controlled types
3667
3668       if Has_Controlled_Component (Etype (Id))
3669         or else Is_Controlled (Etype (Id))
3670       then
3671          if not Is_Library_Level_Entity (Id) then
3672             Check_Restriction (No_Nested_Finalization, N);
3673          else
3674             Validate_Controlled_Object (Id);
3675          end if;
3676       end if;
3677
3678       if Has_Task (Etype (Id)) then
3679          Check_Restriction (No_Tasking, N);
3680
3681          --  Deal with counting max tasks
3682
3683          --  Nothing to do if inside a generic
3684
3685          if Inside_A_Generic then
3686             null;
3687
3688          --  If library level entity, then count tasks
3689
3690          elsif Is_Library_Level_Entity (Id) then
3691             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3692
3693          --  If not library level entity, then indicate we don't know max
3694          --  tasks and also check task hierarchy restriction and blocking
3695          --  operation (since starting a task is definitely blocking!)
3696
3697          else
3698             Check_Restriction (Max_Tasks, N);
3699             Check_Restriction (No_Task_Hierarchy, N);
3700             Check_Potentially_Blocking_Operation (N);
3701          end if;
3702
3703          --  A rather specialized test. If we see two tasks being declared
3704          --  of the same type in the same object declaration, and the task
3705          --  has an entry with an address clause, we know that program error
3706          --  will be raised at run time since we can't have two tasks with
3707          --  entries at the same address.
3708
3709          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3710             declare
3711                E : Entity_Id;
3712
3713             begin
3714                E := First_Entity (Etype (Id));
3715                while Present (E) loop
3716                   if Ekind (E) = E_Entry
3717                     and then Present (Get_Attribute_Definition_Clause
3718                                         (E, Attribute_Address))
3719                   then
3720                      Error_Msg_N
3721                        ("??more than one task with same entry address", N);
3722                      Error_Msg_N
3723                        ("\??Program_Error will be raised at run time", N);
3724                      Insert_Action (N,
3725                        Make_Raise_Program_Error (Loc,
3726                          Reason => PE_Duplicated_Entry_Address));
3727                      exit;
3728                   end if;
3729
3730                   Next_Entity (E);
3731                end loop;
3732             end;
3733          end if;
3734       end if;
3735
3736       --  Some simple constant-propagation: if the expression is a constant
3737       --  string initialized with a literal, share the literal. This avoids
3738       --  a run-time copy.
3739
3740       if Present (E)
3741         and then Is_Entity_Name (E)
3742         and then Ekind (Entity (E)) = E_Constant
3743         and then Base_Type (Etype (E)) = Standard_String
3744       then
3745          declare
3746             Val : constant Node_Id := Constant_Value (Entity (E));
3747          begin
3748             if Present (Val)
3749               and then Nkind (Val) = N_String_Literal
3750             then
3751                Rewrite (E, New_Copy (Val));
3752             end if;
3753          end;
3754       end if;
3755
3756       --  Another optimization: if the nominal subtype is unconstrained and
3757       --  the expression is a function call that returns an unconstrained
3758       --  type, rewrite the declaration as a renaming of the result of the
3759       --  call. The exceptions below are cases where the copy is expected,
3760       --  either by the back end (Aliased case) or by the semantics, as for
3761       --  initializing controlled types or copying tags for classwide types.
3762
3763       if Present (E)
3764         and then Nkind (E) = N_Explicit_Dereference
3765         and then Nkind (Original_Node (E)) = N_Function_Call
3766         and then not Is_Library_Level_Entity (Id)
3767         and then not Is_Constrained (Underlying_Type (T))
3768         and then not Is_Aliased (Id)
3769         and then not Is_Class_Wide_Type (T)
3770         and then not Is_Controlled (T)
3771         and then not Has_Controlled_Component (Base_Type (T))
3772         and then Expander_Active
3773       then
3774          Rewrite (N,
3775            Make_Object_Renaming_Declaration (Loc,
3776              Defining_Identifier => Id,
3777              Access_Definition   => Empty,
3778              Subtype_Mark        => New_Occurrence_Of
3779                                       (Base_Type (Etype (Id)), Loc),
3780              Name                => E));
3781
3782          Set_Renamed_Object (Id, E);
3783
3784          --  Force generation of debugging information for the constant and for
3785          --  the renamed function call.
3786
3787          Set_Debug_Info_Needed (Id);
3788          Set_Debug_Info_Needed (Entity (Prefix (E)));
3789       end if;
3790
3791       if Present (Prev_Entity)
3792         and then Is_Frozen (Prev_Entity)
3793         and then not Error_Posted (Id)
3794       then
3795          Error_Msg_N ("full constant declaration appears too late", N);
3796       end if;
3797
3798       Check_Eliminated (Id);
3799
3800       --  Deal with setting In_Private_Part flag if in private part
3801
3802       if Ekind (Scope (Id)) = E_Package
3803         and then In_Private_Part (Scope (Id))
3804       then
3805          Set_In_Private_Part (Id);
3806       end if;
3807
3808       --  Check for violation of No_Local_Timing_Events
3809
3810       if Restriction_Check_Required (No_Local_Timing_Events)
3811         and then not Is_Library_Level_Entity (Id)
3812         and then Is_RTE (Etype (Id), RE_Timing_Event)
3813       then
3814          Check_Restriction (No_Local_Timing_Events, N);
3815       end if;
3816
3817    <<Leave>>
3818       --  Initialize the refined state of a variable here because this is a
3819       --  common destination for legal and illegal object declarations.
3820
3821       if Ekind (Id) = E_Variable then
3822          Set_Refined_State (Id, Empty);
3823       end if;
3824
3825       if Has_Aspects (N) then
3826          Analyze_Aspect_Specifications (N, Id);
3827       end if;
3828
3829       Analyze_Dimension (N);
3830
3831       --  Verify whether the object declaration introduces an illegal hidden
3832       --  state within a package subject to a null abstract state.
3833
3834       if Formal_Extensions and then Ekind (Id) = E_Variable then
3835          Check_No_Hidden_State (Id);
3836       end if;
3837    end Analyze_Object_Declaration;
3838
3839    ---------------------------
3840    -- Analyze_Others_Choice --
3841    ---------------------------
3842
3843    --  Nothing to do for the others choice node itself, the semantic analysis
3844    --  of the others choice will occur as part of the processing of the parent
3845
3846    procedure Analyze_Others_Choice (N : Node_Id) is
3847       pragma Warnings (Off, N);
3848    begin
3849       null;
3850    end Analyze_Others_Choice;
3851
3852    -------------------------------------------
3853    -- Analyze_Private_Extension_Declaration --
3854    -------------------------------------------
3855
3856    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3857       T           : constant Entity_Id := Defining_Identifier (N);
3858       Indic       : constant Node_Id   := Subtype_Indication (N);
3859       Parent_Type : Entity_Id;
3860       Parent_Base : Entity_Id;
3861
3862    begin
3863       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3864
3865       if Is_Non_Empty_List (Interface_List (N)) then
3866          declare
3867             Intf : Node_Id;
3868             T    : Entity_Id;
3869
3870          begin
3871             Intf := First (Interface_List (N));
3872             while Present (Intf) loop
3873                T := Find_Type_Of_Subtype_Indic (Intf);
3874
3875                Diagnose_Interface (Intf, T);
3876                Next (Intf);
3877             end loop;
3878          end;
3879       end if;
3880
3881       Generate_Definition (T);
3882
3883       --  For other than Ada 2012, just enter the name in the current scope
3884
3885       if Ada_Version < Ada_2012 then
3886          Enter_Name (T);
3887
3888       --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
3889       --  case of private type that completes an incomplete type.
3890
3891       else
3892          declare
3893             Prev : Entity_Id;
3894
3895          begin
3896             Prev := Find_Type_Name (N);
3897
3898             pragma Assert (Prev = T
3899               or else (Ekind (Prev) = E_Incomplete_Type
3900                          and then Present (Full_View (Prev))
3901                          and then Full_View (Prev) = T));
3902          end;
3903       end if;
3904
3905       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3906       Parent_Base := Base_Type (Parent_Type);
3907
3908       if Parent_Type = Any_Type
3909         or else Etype (Parent_Type) = Any_Type
3910       then
3911          Set_Ekind (T, Ekind (Parent_Type));
3912          Set_Etype (T, Any_Type);
3913          goto Leave;
3914
3915       elsif not Is_Tagged_Type (Parent_Type) then
3916          Error_Msg_N
3917            ("parent of type extension must be a tagged type ", Indic);
3918          goto Leave;
3919
3920       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3921          Error_Msg_N ("premature derivation of incomplete type", Indic);
3922          goto Leave;
3923
3924       elsif Is_Concurrent_Type (Parent_Type) then
3925          Error_Msg_N
3926            ("parent type of a private extension cannot be "
3927             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3928
3929          Set_Etype              (T, Any_Type);
3930          Set_Ekind              (T, E_Limited_Private_Type);
3931          Set_Private_Dependents (T, New_Elmt_List);
3932          Set_Error_Posted       (T);
3933          goto Leave;
3934       end if;
3935
3936       --  Perhaps the parent type should be changed to the class-wide type's
3937       --  specific type in this case to prevent cascading errors ???
3938
3939       if Is_Class_Wide_Type (Parent_Type) then
3940          Error_Msg_N
3941            ("parent of type extension must not be a class-wide type", Indic);
3942          goto Leave;
3943       end if;
3944
3945       if (not Is_Package_Or_Generic_Package (Current_Scope)
3946            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3947         or else In_Private_Part (Current_Scope)
3948
3949       then
3950          Error_Msg_N ("invalid context for private extension", N);
3951       end if;
3952
3953       --  Set common attributes
3954
3955       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3956       Set_Scope            (T, Current_Scope);
3957       Set_Ekind            (T, E_Record_Type_With_Private);
3958       Init_Size_Align      (T);
3959
3960       Set_Etype            (T,            Parent_Base);
3961       Set_Has_Task         (T, Has_Task  (Parent_Base));
3962
3963       Set_Convention       (T, Convention     (Parent_Type));
3964       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3965       Set_Is_First_Subtype (T);
3966       Make_Class_Wide_Type (T);
3967
3968       if Unknown_Discriminants_Present (N) then
3969          Set_Discriminant_Constraint (T, No_Elist);
3970       end if;
3971
3972       Build_Derived_Record_Type (N, Parent_Type, T);
3973
3974       --  Propagate inherited invariant information. The new type has
3975       --  invariants, if the parent type has inheritable invariants,
3976       --  and these invariants can in turn be inherited.
3977
3978       if Has_Inheritable_Invariants (Parent_Type) then
3979          Set_Has_Inheritable_Invariants (T);
3980          Set_Has_Invariants (T);
3981       end if;
3982
3983       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3984       --  synchronized formal derived type.
3985
3986       if Ada_Version >= Ada_2005
3987         and then Synchronized_Present (N)
3988       then
3989          Set_Is_Limited_Record (T);
3990
3991          --  Formal derived type case
3992
3993          if Is_Generic_Type (T) then
3994
3995             --  The parent must be a tagged limited type or a synchronized
3996             --  interface.
3997
3998             if (not Is_Tagged_Type (Parent_Type)
3999                   or else not Is_Limited_Type (Parent_Type))
4000               and then
4001                (not Is_Interface (Parent_Type)
4002                   or else not Is_Synchronized_Interface (Parent_Type))
4003             then
4004                Error_Msg_NE ("parent type of & must be tagged limited " &
4005                              "or synchronized", N, T);
4006             end if;
4007
4008             --  The progenitors (if any) must be limited or synchronized
4009             --  interfaces.
4010
4011             if Present (Interfaces (T)) then
4012                declare
4013                   Iface      : Entity_Id;
4014                   Iface_Elmt : Elmt_Id;
4015
4016                begin
4017                   Iface_Elmt := First_Elmt (Interfaces (T));
4018                   while Present (Iface_Elmt) loop
4019                      Iface := Node (Iface_Elmt);
4020
4021                      if not Is_Limited_Interface (Iface)
4022                        and then not Is_Synchronized_Interface (Iface)
4023                      then
4024                         Error_Msg_NE ("progenitor & must be limited " &
4025                                       "or synchronized", N, Iface);
4026                      end if;
4027
4028                      Next_Elmt (Iface_Elmt);
4029                   end loop;
4030                end;
4031             end if;
4032
4033          --  Regular derived extension, the parent must be a limited or
4034          --  synchronized interface.
4035
4036          else
4037             if not Is_Interface (Parent_Type)
4038               or else (not Is_Limited_Interface (Parent_Type)
4039                          and then
4040                        not Is_Synchronized_Interface (Parent_Type))
4041             then
4042                Error_Msg_NE
4043                  ("parent type of & must be limited interface", N, T);
4044             end if;
4045          end if;
4046
4047       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
4048       --  extension with a synchronized parent must be explicitly declared
4049       --  synchronized, because the full view will be a synchronized type.
4050       --  This must be checked before the check for limited types below,
4051       --  to ensure that types declared limited are not allowed to extend
4052       --  synchronized interfaces.
4053
4054       elsif Is_Interface (Parent_Type)
4055         and then Is_Synchronized_Interface (Parent_Type)
4056         and then not Synchronized_Present (N)
4057       then
4058          Error_Msg_NE
4059            ("private extension of& must be explicitly synchronized",
4060              N, Parent_Type);
4061
4062       elsif Limited_Present (N) then
4063          Set_Is_Limited_Record (T);
4064
4065          if not Is_Limited_Type (Parent_Type)
4066            and then
4067              (not Is_Interface (Parent_Type)
4068                or else not Is_Limited_Interface (Parent_Type))
4069          then
4070             Error_Msg_NE ("parent type& of limited extension must be limited",
4071               N, Parent_Type);
4072          end if;
4073       end if;
4074
4075    <<Leave>>
4076       if Has_Aspects (N) then
4077          Analyze_Aspect_Specifications (N, T);
4078       end if;
4079    end Analyze_Private_Extension_Declaration;
4080
4081    ---------------------------------
4082    -- Analyze_Subtype_Declaration --
4083    ---------------------------------
4084
4085    procedure Analyze_Subtype_Declaration
4086      (N    : Node_Id;
4087       Skip : Boolean := False)
4088    is
4089       Id       : constant Entity_Id := Defining_Identifier (N);
4090       T        : Entity_Id;
4091       R_Checks : Check_Result;
4092
4093    begin
4094       Generate_Definition (Id);
4095       Set_Is_Pure (Id, Is_Pure (Current_Scope));
4096       Init_Size_Align (Id);
4097
4098       --  The following guard condition on Enter_Name is to handle cases where
4099       --  the defining identifier has already been entered into the scope but
4100       --  the declaration as a whole needs to be analyzed.
4101
4102       --  This case in particular happens for derived enumeration types. The
4103       --  derived enumeration type is processed as an inserted enumeration type
4104       --  declaration followed by a rewritten subtype declaration. The defining
4105       --  identifier, however, is entered into the name scope very early in the
4106       --  processing of the original type declaration and therefore needs to be
4107       --  avoided here, when the created subtype declaration is analyzed. (See
4108       --  Build_Derived_Types)
4109
4110       --  This also happens when the full view of a private type is derived
4111       --  type with constraints. In this case the entity has been introduced
4112       --  in the private declaration.
4113
4114       --  Finally this happens in some complex cases when validity checks are
4115       --  enabled, where the same subtype declaration may be analyzed twice.
4116       --  This can happen if the subtype is created by the pre-analysis of
4117       --  an attribute tht gives the range of a loop statement, and the loop
4118       --  itself appears within an if_statement that will be rewritten during
4119       --  expansion.
4120
4121       if Skip
4122         or else (Present (Etype (Id))
4123                   and then (Is_Private_Type (Etype (Id))
4124                              or else Is_Task_Type (Etype (Id))
4125                              or else Is_Rewrite_Substitution (N)))
4126       then
4127          null;
4128
4129       elsif Current_Entity (Id) = Id then
4130          null;
4131
4132       else
4133          Enter_Name (Id);
4134       end if;
4135
4136       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
4137
4138       --  Class-wide equivalent types of records with unknown discriminants
4139       --  involve the generation of an itype which serves as the private view
4140       --  of a constrained record subtype. In such cases the base type of the
4141       --  current subtype we are processing is the private itype. Use the full
4142       --  of the private itype when decorating various attributes.
4143
4144       if Is_Itype (T)
4145         and then Is_Private_Type (T)
4146         and then Present (Full_View (T))
4147       then
4148          T := Full_View (T);
4149       end if;
4150
4151       --  Inherit common attributes
4152
4153       Set_Is_Volatile       (Id, Is_Volatile       (T));
4154       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
4155       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
4156       Set_Convention        (Id, Convention        (T));
4157
4158       --  If ancestor has predicates then so does the subtype, and in addition
4159       --  we must delay the freeze to properly arrange predicate inheritance.
4160
4161       --  The Ancestor_Type test is a big kludge, there seem to be cases in
4162       --  which T = ID, so the above tests and assignments do nothing???
4163
4164       if Has_Predicates (T)
4165         or else (Present (Ancestor_Subtype (T))
4166                   and then Has_Predicates (Ancestor_Subtype (T)))
4167       then
4168          Set_Has_Predicates (Id);
4169          Set_Has_Delayed_Freeze (Id);
4170       end if;
4171
4172       --  Subtype of Boolean cannot have a constraint in SPARK
4173
4174       if Is_Boolean_Type (T)
4175         and then Nkind (Subtype_Indication (N)) = N_Subtype_Indication
4176       then
4177          Check_SPARK_Restriction
4178            ("subtype of Boolean cannot have constraint", N);
4179       end if;
4180
4181       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4182          declare
4183             Cstr     : constant Node_Id := Constraint (Subtype_Indication (N));
4184             One_Cstr : Node_Id;
4185             Low      : Node_Id;
4186             High     : Node_Id;
4187
4188          begin
4189             if Nkind (Cstr) = N_Index_Or_Discriminant_Constraint then
4190                One_Cstr := First (Constraints (Cstr));
4191                while Present (One_Cstr) loop
4192
4193                   --  Index or discriminant constraint in SPARK must be a
4194                   --  subtype mark.
4195
4196                   if not
4197                     Nkind_In (One_Cstr, N_Identifier, N_Expanded_Name)
4198                   then
4199                      Check_SPARK_Restriction
4200                        ("subtype mark required", One_Cstr);
4201
4202                   --  String subtype must have a lower bound of 1 in SPARK.
4203                   --  Note that we do not need to test for the non-static case
4204                   --  here, since that was already taken care of in
4205                   --  Process_Range_Expr_In_Decl.
4206
4207                   elsif Base_Type (T) = Standard_String then
4208                      Get_Index_Bounds (One_Cstr, Low, High);
4209
4210                      if Is_OK_Static_Expression (Low)
4211                        and then Expr_Value (Low) /= 1
4212                      then
4213                         Check_SPARK_Restriction
4214                           ("String subtype must have lower bound of 1", N);
4215                      end if;
4216                   end if;
4217
4218                   Next (One_Cstr);
4219                end loop;
4220             end if;
4221          end;
4222       end if;
4223
4224       --  In the case where there is no constraint given in the subtype
4225       --  indication, Process_Subtype just returns the Subtype_Mark, so its
4226       --  semantic attributes must be established here.
4227
4228       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
4229          Set_Etype (Id, Base_Type (T));
4230
4231          --  Subtype of unconstrained array without constraint is not allowed
4232          --  in SPARK.
4233
4234          if Is_Array_Type (T)
4235            and then not Is_Constrained (T)
4236          then
4237             Check_SPARK_Restriction
4238               ("subtype of unconstrained array must have constraint", N);
4239          end if;
4240
4241          case Ekind (T) is
4242             when Array_Kind =>
4243                Set_Ekind                       (Id, E_Array_Subtype);
4244                Copy_Array_Subtype_Attributes   (Id, T);
4245
4246             when Decimal_Fixed_Point_Kind =>
4247                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
4248                Set_Digits_Value         (Id, Digits_Value       (T));
4249                Set_Delta_Value          (Id, Delta_Value        (T));
4250                Set_Scale_Value          (Id, Scale_Value        (T));
4251                Set_Small_Value          (Id, Small_Value        (T));
4252                Set_Scalar_Range         (Id, Scalar_Range       (T));
4253                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
4254                Set_Is_Constrained       (Id, Is_Constrained     (T));
4255                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4256                Set_RM_Size              (Id, RM_Size            (T));
4257
4258             when Enumeration_Kind =>
4259                Set_Ekind                (Id, E_Enumeration_Subtype);
4260                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
4261                Set_Scalar_Range         (Id, Scalar_Range       (T));
4262                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
4263                Set_Is_Constrained       (Id, Is_Constrained     (T));
4264                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4265                Set_RM_Size              (Id, RM_Size            (T));
4266
4267             when Ordinary_Fixed_Point_Kind =>
4268                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
4269                Set_Scalar_Range         (Id, Scalar_Range       (T));
4270                Set_Small_Value          (Id, Small_Value        (T));
4271                Set_Delta_Value          (Id, Delta_Value        (T));
4272                Set_Is_Constrained       (Id, Is_Constrained     (T));
4273                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4274                Set_RM_Size              (Id, RM_Size            (T));
4275
4276             when Float_Kind =>
4277                Set_Ekind                (Id, E_Floating_Point_Subtype);
4278                Set_Scalar_Range         (Id, Scalar_Range       (T));
4279                Set_Digits_Value         (Id, Digits_Value       (T));
4280                Set_Is_Constrained       (Id, Is_Constrained     (T));
4281
4282             when Signed_Integer_Kind =>
4283                Set_Ekind                (Id, E_Signed_Integer_Subtype);
4284                Set_Scalar_Range         (Id, Scalar_Range       (T));
4285                Set_Is_Constrained       (Id, Is_Constrained     (T));
4286                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4287                Set_RM_Size              (Id, RM_Size            (T));
4288
4289             when Modular_Integer_Kind =>
4290                Set_Ekind                (Id, E_Modular_Integer_Subtype);
4291                Set_Scalar_Range         (Id, Scalar_Range       (T));
4292                Set_Is_Constrained       (Id, Is_Constrained     (T));
4293                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4294                Set_RM_Size              (Id, RM_Size            (T));
4295
4296             when Class_Wide_Kind =>
4297                Set_Ekind                (Id, E_Class_Wide_Subtype);
4298                Set_First_Entity         (Id, First_Entity       (T));
4299                Set_Last_Entity          (Id, Last_Entity        (T));
4300                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
4301                Set_Cloned_Subtype       (Id, T);
4302                Set_Is_Tagged_Type       (Id, True);
4303                Set_Has_Unknown_Discriminants
4304                                         (Id, True);
4305
4306                if Ekind (T) = E_Class_Wide_Subtype then
4307                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
4308                end if;
4309
4310             when E_Record_Type | E_Record_Subtype =>
4311                Set_Ekind                (Id, E_Record_Subtype);
4312
4313                if Ekind (T) = E_Record_Subtype
4314                  and then Present (Cloned_Subtype (T))
4315                then
4316                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
4317                else
4318                   Set_Cloned_Subtype    (Id, T);
4319                end if;
4320
4321                Set_First_Entity         (Id, First_Entity       (T));
4322                Set_Last_Entity          (Id, Last_Entity        (T));
4323                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
4324                Set_Is_Constrained       (Id, Is_Constrained     (T));
4325                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
4326                Set_Has_Implicit_Dereference
4327                                         (Id, Has_Implicit_Dereference (T));
4328                Set_Has_Unknown_Discriminants
4329                                         (Id, Has_Unknown_Discriminants (T));
4330
4331                if Has_Discriminants (T) then
4332                   Set_Discriminant_Constraint
4333                                         (Id, Discriminant_Constraint (T));
4334                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4335
4336                elsif Has_Unknown_Discriminants (Id) then
4337                   Set_Discriminant_Constraint (Id, No_Elist);
4338                end if;
4339
4340                if Is_Tagged_Type (T) then
4341                   Set_Is_Tagged_Type    (Id);
4342                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
4343                   Set_Direct_Primitive_Operations
4344                                         (Id, Direct_Primitive_Operations (T));
4345                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
4346
4347                   if Is_Interface (T) then
4348                      Set_Is_Interface (Id);
4349                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
4350                   end if;
4351                end if;
4352
4353             when Private_Kind =>
4354                Set_Ekind              (Id, Subtype_Kind (Ekind        (T)));
4355                Set_Has_Discriminants  (Id, Has_Discriminants          (T));
4356                Set_Is_Constrained     (Id, Is_Constrained             (T));
4357                Set_First_Entity       (Id, First_Entity               (T));
4358                Set_Last_Entity        (Id, Last_Entity                (T));
4359                Set_Private_Dependents (Id, New_Elmt_List);
4360                Set_Is_Limited_Record  (Id, Is_Limited_Record          (T));
4361                Set_Has_Implicit_Dereference
4362                                       (Id, Has_Implicit_Dereference   (T));
4363                Set_Has_Unknown_Discriminants
4364                                       (Id, Has_Unknown_Discriminants  (T));
4365                Set_Known_To_Have_Preelab_Init
4366                                       (Id, Known_To_Have_Preelab_Init (T));
4367
4368                if Is_Tagged_Type (T) then
4369                   Set_Is_Tagged_Type              (Id);
4370                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
4371                   Set_Class_Wide_Type             (Id, Class_Wide_Type  (T));
4372                   Set_Direct_Primitive_Operations (Id,
4373                     Direct_Primitive_Operations (T));
4374                end if;
4375
4376                --  In general the attributes of the subtype of a private type
4377                --  are the attributes of the partial view of parent. However,
4378                --  the full view may be a discriminated type, and the subtype
4379                --  must share the discriminant constraint to generate correct
4380                --  calls to initialization procedures.
4381
4382                if Has_Discriminants (T) then
4383                   Set_Discriminant_Constraint
4384                     (Id, Discriminant_Constraint (T));
4385                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4386
4387                elsif Present (Full_View (T))
4388                  and then Has_Discriminants (Full_View (T))
4389                then
4390                   Set_Discriminant_Constraint
4391                     (Id, Discriminant_Constraint (Full_View (T)));
4392                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4393
4394                   --  This would seem semantically correct, but apparently
4395                   --  generates spurious errors about missing components ???
4396
4397                   --  Set_Has_Discriminants (Id);
4398                end if;
4399
4400                Prepare_Private_Subtype_Completion (Id, N);
4401
4402                --  If this is the subtype of a constrained private type with
4403                --  discriminants that has got a full view and we also have
4404                --  built a completion just above, show that the completion
4405                --  is a clone of the full view to the back-end.
4406
4407                if Has_Discriminants (T)
4408                   and then not Has_Unknown_Discriminants (T)
4409                   and then not Is_Empty_Elmt_List (Discriminant_Constraint (T))
4410                   and then Present (Full_View (T))
4411                   and then Present (Full_View (Id))
4412                then
4413                   Set_Cloned_Subtype (Full_View (Id), Full_View (T));
4414                end if;
4415
4416             when Access_Kind =>
4417                Set_Ekind             (Id, E_Access_Subtype);
4418                Set_Is_Constrained    (Id, Is_Constrained        (T));
4419                Set_Is_Access_Constant
4420                                      (Id, Is_Access_Constant    (T));
4421                Set_Directly_Designated_Type
4422                                      (Id, Designated_Type       (T));
4423                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4424
4425                --  A Pure library_item must not contain the declaration of a
4426                --  named access type, except within a subprogram, generic
4427                --  subprogram, task unit, or protected unit, or if it has
4428                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4429
4430                if Comes_From_Source (Id)
4431                  and then In_Pure_Unit
4432                  and then not In_Subprogram_Task_Protected_Unit
4433                  and then not No_Pool_Assigned (Id)
4434                then
4435                   Error_Msg_N
4436                     ("named access types not allowed in pure unit", N);
4437                end if;
4438
4439             when Concurrent_Kind =>
4440                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4441                Set_Corresponding_Record_Type (Id,
4442                                          Corresponding_Record_Type (T));
4443                Set_First_Entity         (Id, First_Entity          (T));
4444                Set_First_Private_Entity (Id, First_Private_Entity  (T));
4445                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4446                Set_Is_Constrained       (Id, Is_Constrained        (T));
4447                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4448                Set_Last_Entity          (Id, Last_Entity           (T));
4449
4450                if Has_Discriminants (T) then
4451                   Set_Discriminant_Constraint (Id,
4452                                            Discriminant_Constraint (T));
4453                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4454                end if;
4455
4456             when E_Incomplete_Type =>
4457                if Ada_Version >= Ada_2005 then
4458
4459                   --  In Ada 2005 an incomplete type can be explicitly tagged:
4460                   --  propagate indication.
4461
4462                   Set_Ekind              (Id, E_Incomplete_Subtype);
4463                   Set_Is_Tagged_Type     (Id, Is_Tagged_Type (T));
4464                   Set_Private_Dependents (Id, New_Elmt_List);
4465
4466                   --  Ada 2005 (AI-412): Decorate an incomplete subtype of an
4467                   --  incomplete type visible through a limited with clause.
4468
4469                   if From_With_Type (T)
4470                     and then Present (Non_Limited_View (T))
4471                   then
4472                      Set_From_With_Type   (Id);
4473                      Set_Non_Limited_View (Id, Non_Limited_View (T));
4474
4475                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
4476                   --  to the private dependents of the original incomplete
4477                   --  type for future transformation.
4478
4479                   else
4480                      Append_Elmt (Id, Private_Dependents (T));
4481                   end if;
4482
4483                --  If the subtype name denotes an incomplete type an error
4484                --  was already reported by Process_Subtype.
4485
4486                else
4487                   Set_Etype (Id, Any_Type);
4488                end if;
4489
4490             when others =>
4491                raise Program_Error;
4492          end case;
4493       end if;
4494
4495       if Etype (Id) = Any_Type then
4496          goto Leave;
4497       end if;
4498
4499       --  Some common processing on all types
4500
4501       Set_Size_Info      (Id, T);
4502       Set_First_Rep_Item (Id, First_Rep_Item (T));
4503
4504       --  If the parent type is a generic actual, so is the subtype. This may
4505       --  happen in a nested instance. Why Comes_From_Source test???
4506
4507       if not Comes_From_Source (N) then
4508          Set_Is_Generic_Actual_Type (Id, Is_Generic_Actual_Type (T));
4509       end if;
4510
4511       T := Etype (Id);
4512
4513       Set_Is_Immediately_Visible   (Id, True);
4514       Set_Depends_On_Private       (Id, Has_Private_Component (T));
4515       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
4516
4517       if Is_Interface (T) then
4518          Set_Is_Interface (Id);
4519       end if;
4520
4521       if Present (Generic_Parent_Type (N))
4522         and then
4523           (Nkind
4524             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
4525             or else Nkind
4526               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
4527                 /= N_Formal_Private_Type_Definition)
4528       then
4529          if Is_Tagged_Type (Id) then
4530
4531             --  If this is a generic actual subtype for a synchronized type,
4532             --  the primitive operations are those of the corresponding record
4533             --  for which there is a separate subtype declaration.
4534
4535             if Is_Concurrent_Type (Id) then
4536                null;
4537             elsif Is_Class_Wide_Type (Id) then
4538                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
4539             else
4540                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
4541             end if;
4542
4543          elsif Scope (Etype (Id)) /= Standard_Standard then
4544             Derive_Subprograms (Generic_Parent_Type (N), Id);
4545          end if;
4546       end if;
4547
4548       if Is_Private_Type (T)
4549         and then Present (Full_View (T))
4550       then
4551          Conditional_Delay (Id, Full_View (T));
4552
4553       --  The subtypes of components or subcomponents of protected types
4554       --  do not need freeze nodes, which would otherwise appear in the
4555       --  wrong scope (before the freeze node for the protected type). The
4556       --  proper subtypes are those of the subcomponents of the corresponding
4557       --  record.
4558
4559       elsif Ekind (Scope (Id)) /= E_Protected_Type
4560         and then Present (Scope (Scope (Id))) -- error defense!
4561         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
4562       then
4563          Conditional_Delay (Id, T);
4564       end if;
4565
4566       --  Check that Constraint_Error is raised for a scalar subtype indication
4567       --  when the lower or upper bound of a non-null range lies outside the
4568       --  range of the type mark.
4569
4570       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4571          if Is_Scalar_Type (Etype (Id))
4572             and then Scalar_Range (Id) /=
4573                      Scalar_Range (Etype (Subtype_Mark
4574                                            (Subtype_Indication (N))))
4575          then
4576             Apply_Range_Check
4577               (Scalar_Range (Id),
4578                Etype (Subtype_Mark (Subtype_Indication (N))));
4579
4580          --  In the array case, check compatibility for each index
4581
4582          elsif Is_Array_Type (Etype (Id))
4583            and then Present (First_Index (Id))
4584          then
4585             --  This really should be a subprogram that finds the indications
4586             --  to check???
4587
4588             declare
4589                Subt_Index   : Node_Id := First_Index (Id);
4590                Target_Index : Node_Id :=
4591                                 First_Index (Etype
4592                                   (Subtype_Mark (Subtype_Indication (N))));
4593                Has_Dyn_Chk  : Boolean := Has_Dynamic_Range_Check (N);
4594
4595             begin
4596                while Present (Subt_Index) loop
4597                   if ((Nkind (Subt_Index) = N_Identifier
4598                          and then Ekind (Entity (Subt_Index)) in Scalar_Kind)
4599                        or else Nkind (Subt_Index) = N_Subtype_Indication)
4600                     and then
4601                       Nkind (Scalar_Range (Etype (Subt_Index))) = N_Range
4602                   then
4603                      declare
4604                         Target_Typ : constant Entity_Id :=
4605                                        Etype (Target_Index);
4606                      begin
4607                         R_Checks :=
4608                           Get_Range_Checks
4609                             (Scalar_Range (Etype (Subt_Index)),
4610                              Target_Typ,
4611                              Etype (Subt_Index),
4612                              Defining_Identifier (N));
4613
4614                         --  Reset Has_Dynamic_Range_Check on the subtype to
4615                         --  prevent elision of the index check due to a dynamic
4616                         --  check generated for a preceding index (needed since
4617                         --  Insert_Range_Checks tries to avoid generating
4618                         --  redundant checks on a given declaration).
4619
4620                         Set_Has_Dynamic_Range_Check (N, False);
4621
4622                         Insert_Range_Checks
4623                           (R_Checks,
4624                            N,
4625                            Target_Typ,
4626                            Sloc (Defining_Identifier (N)));
4627
4628                         --  Record whether this index involved a dynamic check
4629
4630                         Has_Dyn_Chk :=
4631                           Has_Dyn_Chk or else Has_Dynamic_Range_Check (N);
4632                      end;
4633                   end if;
4634
4635                   Next_Index (Subt_Index);
4636                   Next_Index (Target_Index);
4637                end loop;
4638
4639                --  Finally, mark whether the subtype involves dynamic checks
4640
4641                Set_Has_Dynamic_Range_Check (N, Has_Dyn_Chk);
4642             end;
4643          end if;
4644       end if;
4645
4646       --  Make sure that generic actual types are properly frozen. The subtype
4647       --  is marked as a generic actual type when the enclosing instance is
4648       --  analyzed, so here we identify the subtype from the tree structure.
4649
4650       if Expander_Active
4651         and then Is_Generic_Actual_Type (Id)
4652         and then In_Instance
4653         and then not Comes_From_Source (N)
4654         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
4655         and then Is_Frozen (T)
4656       then
4657          Freeze_Before (N, Id);
4658       end if;
4659
4660       Set_Optimize_Alignment_Flags (Id);
4661       Check_Eliminated (Id);
4662
4663    <<Leave>>
4664       if Has_Aspects (N) then
4665          Analyze_Aspect_Specifications (N, Id);
4666       end if;
4667
4668       Analyze_Dimension (N);
4669    end Analyze_Subtype_Declaration;
4670
4671    --------------------------------
4672    -- Analyze_Subtype_Indication --
4673    --------------------------------
4674
4675    procedure Analyze_Subtype_Indication (N : Node_Id) is
4676       T : constant Entity_Id := Subtype_Mark (N);
4677       R : constant Node_Id   := Range_Expression (Constraint (N));
4678
4679    begin
4680       Analyze (T);
4681
4682       if R /= Error then
4683          Analyze (R);
4684          Set_Etype (N, Etype (R));
4685          Resolve (R, Entity (T));
4686       else
4687          Set_Error_Posted (R);
4688          Set_Error_Posted (T);
4689       end if;
4690    end Analyze_Subtype_Indication;
4691
4692    --------------------------
4693    -- Analyze_Variant_Part --
4694    --------------------------
4695
4696    procedure Analyze_Variant_Part (N : Node_Id) is
4697       Discr_Name : Node_Id;
4698       Discr_Type : Entity_Id;
4699
4700       procedure Process_Variant (A : Node_Id);
4701       --  Analyze declarations for a single variant
4702
4703       package Analyze_Variant_Choices is
4704         new Generic_Analyze_Choices (Process_Variant);
4705       use Analyze_Variant_Choices;
4706
4707       ---------------------
4708       -- Process_Variant --
4709       ---------------------
4710
4711       procedure Process_Variant (A : Node_Id) is
4712          CL : constant Node_Id := Component_List (A);
4713       begin
4714          if not Null_Present (CL) then
4715             Analyze_Declarations (Component_Items (CL));
4716
4717             if Present (Variant_Part (CL)) then
4718                Analyze (Variant_Part (CL));
4719             end if;
4720          end if;
4721       end Process_Variant;
4722
4723    --  Start of processing for Analyze_Variant_Part
4724
4725    begin
4726       Discr_Name := Name (N);
4727       Analyze (Discr_Name);
4728
4729       --  If Discr_Name bad, get out (prevent cascaded errors)
4730
4731       if Etype (Discr_Name) = Any_Type then
4732          return;
4733       end if;
4734
4735       --  Check invalid discriminant in variant part
4736
4737       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4738          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4739       end if;
4740
4741       Discr_Type := Etype (Entity (Discr_Name));
4742
4743       if not Is_Discrete_Type (Discr_Type) then
4744          Error_Msg_N
4745            ("discriminant in a variant part must be of a discrete type",
4746              Name (N));
4747          return;
4748       end if;
4749
4750       --  Now analyze the choices, which also analyzes the declarations that
4751       --  are associated with each choice.
4752
4753       Analyze_Choices (Variants (N), Discr_Type);
4754
4755       --  Note: we used to instantiate and call Check_Choices here to check
4756       --  that the choices covered the discriminant, but it's too early to do
4757       --  that because of statically predicated subtypes, whose analysis may
4758       --  be deferred to their freeze point which may be as late as the freeze
4759       --  point of the containing record. So this call is now to be found in
4760       --  Freeze_Record_Declaration.
4761
4762    end Analyze_Variant_Part;
4763
4764    ----------------------------
4765    -- Array_Type_Declaration --
4766    ----------------------------
4767
4768    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4769       Component_Def : constant Node_Id := Component_Definition (Def);
4770       Component_Typ : constant Node_Id := Subtype_Indication (Component_Def);
4771       Element_Type  : Entity_Id;
4772       Implicit_Base : Entity_Id;
4773       Index         : Node_Id;
4774       Related_Id    : Entity_Id := Empty;
4775       Nb_Index      : Nat;
4776       P             : constant Node_Id := Parent (Def);
4777       Priv          : Entity_Id;
4778
4779    begin
4780       if Nkind (Def) = N_Constrained_Array_Definition then
4781          Index := First (Discrete_Subtype_Definitions (Def));
4782       else
4783          Index := First (Subtype_Marks (Def));
4784       end if;
4785
4786       --  Find proper names for the implicit types which may be public. In case
4787       --  of anonymous arrays we use the name of the first object of that type
4788       --  as prefix.
4789
4790       if No (T) then
4791          Related_Id := Defining_Identifier (P);
4792       else
4793          Related_Id := T;
4794       end if;
4795
4796       Nb_Index := 1;
4797       while Present (Index) loop
4798          Analyze (Index);
4799
4800          if not Nkind_In (Index, N_Identifier, N_Expanded_Name) then
4801             Check_SPARK_Restriction ("subtype mark required", Index);
4802          end if;
4803
4804          --  Add a subtype declaration for each index of private array type
4805          --  declaration whose etype is also private. For example:
4806
4807          --     package Pkg is
4808          --        type Index is private;
4809          --     private
4810          --        type Table is array (Index) of ...
4811          --     end;
4812
4813          --  This is currently required by the expander for the internally
4814          --  generated equality subprogram of records with variant parts in
4815          --  which the etype of some component is such private type.
4816
4817          if Ekind (Current_Scope) = E_Package
4818            and then In_Private_Part (Current_Scope)
4819            and then Has_Private_Declaration (Etype (Index))
4820          then
4821             declare
4822                Loc   : constant Source_Ptr := Sloc (Def);
4823                New_E : Entity_Id;
4824                Decl  : Entity_Id;
4825
4826             begin
4827                New_E := Make_Temporary (Loc, 'T');
4828                Set_Is_Internal (New_E);
4829
4830                Decl :=
4831                  Make_Subtype_Declaration (Loc,
4832                    Defining_Identifier => New_E,
4833                    Subtype_Indication  =>
4834                      New_Occurrence_Of (Etype (Index), Loc));
4835
4836                Insert_Before (Parent (Def), Decl);
4837                Analyze (Decl);
4838                Set_Etype (Index, New_E);
4839
4840                --  If the index is a range the Entity attribute is not
4841                --  available. Example:
4842
4843                --     package Pkg is
4844                --        type T is private;
4845                --     private
4846                --        type T is new Natural;
4847                --        Table : array (T(1) .. T(10)) of Boolean;
4848                --     end Pkg;
4849
4850                if Nkind (Index) /= N_Range then
4851                   Set_Entity (Index, New_E);
4852                end if;
4853             end;
4854          end if;
4855
4856          Make_Index (Index, P, Related_Id, Nb_Index);
4857
4858          --  Check error of subtype with predicate for index type
4859
4860          Bad_Predicated_Subtype_Use
4861            ("subtype& has predicate, not allowed as index subtype",
4862             Index, Etype (Index));
4863
4864          --  Move to next index
4865
4866          Next_Index (Index);
4867          Nb_Index := Nb_Index + 1;
4868       end loop;
4869
4870       --  Process subtype indication if one is present
4871
4872       if Present (Component_Typ) then
4873          Element_Type := Process_Subtype (Component_Typ, P, Related_Id, 'C');
4874
4875          Set_Etype (Component_Typ, Element_Type);
4876
4877          if not Nkind_In (Component_Typ, N_Identifier, N_Expanded_Name) then
4878             Check_SPARK_Restriction ("subtype mark required", Component_Typ);
4879          end if;
4880
4881       --  Ada 2005 (AI-230): Access Definition case
4882
4883       else pragma Assert (Present (Access_Definition (Component_Def)));
4884
4885          --  Indicate that the anonymous access type is created by the
4886          --  array type declaration.
4887
4888          Element_Type := Access_Definition
4889                            (Related_Nod => P,
4890                             N           => Access_Definition (Component_Def));
4891          Set_Is_Local_Anonymous_Access (Element_Type);
4892
4893          --  Propagate the parent. This field is needed if we have to generate
4894          --  the master_id associated with an anonymous access to task type
4895          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4896
4897          Set_Parent (Element_Type, Parent (T));
4898
4899          --  Ada 2005 (AI-230): In case of components that are anonymous access
4900          --  types the level of accessibility depends on the enclosing type
4901          --  declaration
4902
4903          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4904
4905          --  Ada 2005 (AI-254)
4906
4907          declare
4908             CD : constant Node_Id :=
4909                    Access_To_Subprogram_Definition
4910                      (Access_Definition (Component_Def));
4911          begin
4912             if Present (CD) and then Protected_Present (CD) then
4913                Element_Type :=
4914                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4915             end if;
4916          end;
4917       end if;
4918
4919       --  Constrained array case
4920
4921       if No (T) then
4922          T := Create_Itype (E_Void, P, Related_Id, 'T');
4923       end if;
4924
4925       if Nkind (Def) = N_Constrained_Array_Definition then
4926
4927          --  Establish Implicit_Base as unconstrained base type
4928
4929          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4930
4931          Set_Etype              (Implicit_Base, Implicit_Base);
4932          Set_Scope              (Implicit_Base, Current_Scope);
4933          Set_Has_Delayed_Freeze (Implicit_Base);
4934
4935          --  The constrained array type is a subtype of the unconstrained one
4936
4937          Set_Ekind          (T, E_Array_Subtype);
4938          Init_Size_Align    (T);
4939          Set_Etype          (T, Implicit_Base);
4940          Set_Scope          (T, Current_Scope);
4941          Set_Is_Constrained (T, True);
4942          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4943          Set_Has_Delayed_Freeze (T);
4944
4945          --  Complete setup of implicit base type
4946
4947          Set_First_Index       (Implicit_Base, First_Index (T));
4948          Set_Component_Type    (Implicit_Base, Element_Type);
4949          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4950          Set_Component_Size    (Implicit_Base, Uint_0);
4951          Set_Packed_Array_Type (Implicit_Base, Empty);
4952          Set_Has_Controlled_Component
4953                                (Implicit_Base, Has_Controlled_Component
4954                                                         (Element_Type)
4955                                                  or else Is_Controlled
4956                                                         (Element_Type));
4957          Set_Finalize_Storage_Only
4958                                (Implicit_Base, Finalize_Storage_Only
4959                                                         (Element_Type));
4960
4961       --  Unconstrained array case
4962
4963       else
4964          Set_Ekind                    (T, E_Array_Type);
4965          Init_Size_Align              (T);
4966          Set_Etype                    (T, T);
4967          Set_Scope                    (T, Current_Scope);
4968          Set_Component_Size           (T, Uint_0);
4969          Set_Is_Constrained           (T, False);
4970          Set_First_Index              (T, First (Subtype_Marks (Def)));
4971          Set_Has_Delayed_Freeze       (T, True);
4972          Set_Has_Task                 (T, Has_Task      (Element_Type));
4973          Set_Has_Controlled_Component (T, Has_Controlled_Component
4974                                                         (Element_Type)
4975                                             or else
4976                                           Is_Controlled (Element_Type));
4977          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4978                                                         (Element_Type));
4979       end if;
4980
4981       --  Common attributes for both cases
4982
4983       Set_Component_Type (Base_Type (T), Element_Type);
4984       Set_Packed_Array_Type (T, Empty);
4985
4986       if Aliased_Present (Component_Definition (Def)) then
4987          Check_SPARK_Restriction
4988            ("aliased is not allowed", Component_Definition (Def));
4989          Set_Has_Aliased_Components (Etype (T));
4990       end if;
4991
4992       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4993       --  array type to ensure that objects of this type are initialized.
4994
4995       if Ada_Version >= Ada_2005
4996         and then Can_Never_Be_Null (Element_Type)
4997       then
4998          Set_Can_Never_Be_Null (T);
4999
5000          if Null_Exclusion_Present (Component_Definition (Def))
5001
5002             --  No need to check itypes because in their case this check was
5003             --  done at their point of creation
5004
5005            and then not Is_Itype (Element_Type)
5006          then
5007             Error_Msg_N
5008               ("`NOT NULL` not allowed (null already excluded)",
5009                Subtype_Indication (Component_Definition (Def)));
5010          end if;
5011       end if;
5012
5013       Priv := Private_Component (Element_Type);
5014
5015       if Present (Priv) then
5016
5017          --  Check for circular definitions
5018
5019          if Priv = Any_Type then
5020             Set_Component_Type (Etype (T), Any_Type);
5021
5022          --  There is a gap in the visibility of operations on the composite
5023          --  type only if the component type is defined in a different scope.
5024
5025          elsif Scope (Priv) = Current_Scope then
5026             null;
5027
5028          elsif Is_Limited_Type (Priv) then
5029             Set_Is_Limited_Composite (Etype (T));
5030             Set_Is_Limited_Composite (T);
5031          else
5032             Set_Is_Private_Composite (Etype (T));
5033             Set_Is_Private_Composite (T);
5034          end if;
5035       end if;
5036
5037       --  A syntax error in the declaration itself may lead to an empty index
5038       --  list, in which case do a minimal patch.
5039
5040       if No (First_Index (T)) then
5041          Error_Msg_N ("missing index definition in array type declaration", T);
5042
5043          declare
5044             Indexes : constant List_Id :=
5045                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
5046          begin
5047             Set_Discrete_Subtype_Definitions (Def, Indexes);
5048             Set_First_Index (T, First (Indexes));
5049             return;
5050          end;
5051       end if;
5052
5053       --  Create a concatenation operator for the new type. Internal array
5054       --  types created for packed entities do not need such, they are
5055       --  compatible with the user-defined type.
5056
5057       if Number_Dimensions (T) = 1
5058          and then not Is_Packed_Array_Type (T)
5059       then
5060          New_Concatenation_Op (T);
5061       end if;
5062
5063       --  In the case of an unconstrained array the parser has already verified
5064       --  that all the indexes are unconstrained but we still need to make sure
5065       --  that the element type is constrained.
5066
5067       if Is_Indefinite_Subtype (Element_Type) then
5068          Error_Msg_N
5069            ("unconstrained element type in array declaration",
5070             Subtype_Indication (Component_Def));
5071
5072       elsif Is_Abstract_Type (Element_Type) then
5073          Error_Msg_N
5074            ("the type of a component cannot be abstract",
5075             Subtype_Indication (Component_Def));
5076       end if;
5077
5078       --  There may be an invariant declared for the component type, but
5079       --  the construction of the component invariant checking procedure
5080       --  takes place during expansion.
5081    end Array_Type_Declaration;
5082
5083    ------------------------------------------------------
5084    -- Replace_Anonymous_Access_To_Protected_Subprogram --
5085    ------------------------------------------------------
5086
5087    function Replace_Anonymous_Access_To_Protected_Subprogram
5088      (N : Node_Id) return Entity_Id
5089    is
5090       Loc : constant Source_Ptr := Sloc (N);
5091
5092       Curr_Scope : constant Scope_Stack_Entry :=
5093                      Scope_Stack.Table (Scope_Stack.Last);
5094
5095       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
5096
5097       Acc : Node_Id;
5098       --  Access definition in declaration
5099
5100       Comp : Node_Id;
5101       --  Object definition or formal definition with an access definition
5102
5103       Decl : Node_Id;
5104       --  Declaration of anonymous access to subprogram type
5105
5106       Spec : Node_Id;
5107       --  Original specification in access to subprogram
5108
5109       P : Node_Id;
5110
5111    begin
5112       Set_Is_Internal (Anon);
5113
5114       case Nkind (N) is
5115          when N_Component_Declaration       |
5116            N_Unconstrained_Array_Definition |
5117            N_Constrained_Array_Definition   =>
5118             Comp := Component_Definition (N);
5119             Acc  := Access_Definition (Comp);
5120
5121          when N_Discriminant_Specification =>
5122             Comp := Discriminant_Type (N);
5123             Acc  := Comp;
5124
5125          when N_Parameter_Specification =>
5126             Comp := Parameter_Type (N);
5127             Acc  := Comp;
5128
5129          when N_Access_Function_Definition  =>
5130             Comp := Result_Definition (N);
5131             Acc  := Comp;
5132
5133          when N_Object_Declaration  =>
5134             Comp := Object_Definition (N);
5135             Acc  := Comp;
5136
5137          when N_Function_Specification =>
5138             Comp := Result_Definition (N);
5139             Acc  := Comp;
5140
5141          when others =>
5142             raise Program_Error;
5143       end case;
5144
5145       Spec := Access_To_Subprogram_Definition (Acc);
5146
5147       Decl :=
5148         Make_Full_Type_Declaration (Loc,
5149           Defining_Identifier => Anon,
5150           Type_Definition     => Copy_Separate_Tree (Spec));
5151
5152       Mark_Rewrite_Insertion (Decl);
5153
5154       --  In ASIS mode, analyze the profile on the original node, because
5155       --  the separate copy does not provide enough links to recover the
5156       --  original tree. Analysis is limited to type annotations, within
5157       --  a temporary scope that serves as an anonymous subprogram to collect
5158       --  otherwise useless temporaries and itypes.
5159
5160       if ASIS_Mode then
5161          declare
5162             Typ : constant Entity_Id :=  Make_Temporary (Loc, 'S');
5163
5164          begin
5165             if Nkind (Spec) = N_Access_Function_Definition then
5166                Set_Ekind (Typ, E_Function);
5167             else
5168                Set_Ekind (Typ, E_Procedure);
5169             end if;
5170
5171             Set_Parent (Typ, N);
5172             Set_Scope  (Typ, Current_Scope);
5173             Push_Scope (Typ);
5174
5175             Process_Formals (Parameter_Specifications (Spec), Spec);
5176
5177             if Nkind (Spec) = N_Access_Function_Definition then
5178                declare
5179                   Def : constant Node_Id := Result_Definition (Spec);
5180
5181                begin
5182                   --  The result might itself be an anonymous access type, so
5183                   --  have to recurse.
5184
5185                   if Nkind (Def) = N_Access_Definition then
5186                      if Present (Access_To_Subprogram_Definition (Def)) then
5187                         Set_Etype
5188                           (Def,
5189                            Replace_Anonymous_Access_To_Protected_Subprogram
5190                             (Spec));
5191                      else
5192                         Find_Type (Subtype_Mark (Def));
5193                      end if;
5194
5195                   else
5196                      Find_Type (Def);
5197                   end if;
5198                end;
5199             end if;
5200
5201             End_Scope;
5202          end;
5203       end if;
5204
5205       --  Insert the new declaration in the nearest enclosing scope. If the
5206       --  node is a body and N is its return type, the declaration belongs in
5207       --  the enclosing scope.
5208
5209       P := Parent (N);
5210
5211       if Nkind (P) = N_Subprogram_Body
5212         and then Nkind (N) = N_Function_Specification
5213       then
5214          P := Parent (P);
5215       end if;
5216
5217       while Present (P) and then not Has_Declarations (P) loop
5218          P := Parent (P);
5219       end loop;
5220
5221       pragma Assert (Present (P));
5222
5223       if Nkind (P) = N_Package_Specification then
5224          Prepend (Decl, Visible_Declarations (P));
5225       else
5226          Prepend (Decl, Declarations (P));
5227       end if;
5228
5229       --  Replace the anonymous type with an occurrence of the new declaration.
5230       --  In all cases the rewritten node does not have the null-exclusion
5231       --  attribute because (if present) it was already inherited by the
5232       --  anonymous entity (Anon). Thus, in case of components we do not
5233       --  inherit this attribute.
5234
5235       if Nkind (N) = N_Parameter_Specification then
5236          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5237          Set_Etype (Defining_Identifier (N), Anon);
5238          Set_Null_Exclusion_Present (N, False);
5239
5240       elsif Nkind (N) = N_Object_Declaration then
5241          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5242          Set_Etype (Defining_Identifier (N), Anon);
5243
5244       elsif Nkind (N) = N_Access_Function_Definition then
5245          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5246
5247       elsif Nkind (N) = N_Function_Specification then
5248          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5249          Set_Etype (Defining_Unit_Name (N), Anon);
5250
5251       else
5252          Rewrite (Comp,
5253            Make_Component_Definition (Loc,
5254              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
5255       end if;
5256
5257       Mark_Rewrite_Insertion (Comp);
5258
5259       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
5260          Analyze (Decl);
5261
5262       else
5263          --  Temporarily remove the current scope (record or subprogram) from
5264          --  the stack to add the new declarations to the enclosing scope.
5265
5266          Scope_Stack.Decrement_Last;
5267          Analyze (Decl);
5268          Set_Is_Itype (Anon);
5269          Scope_Stack.Append (Curr_Scope);
5270       end if;
5271
5272       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
5273       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
5274       return Anon;
5275    end Replace_Anonymous_Access_To_Protected_Subprogram;
5276
5277    -------------------------------
5278    -- Build_Derived_Access_Type --
5279    -------------------------------
5280
5281    procedure Build_Derived_Access_Type
5282      (N            : Node_Id;
5283       Parent_Type  : Entity_Id;
5284       Derived_Type : Entity_Id)
5285    is
5286       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
5287
5288       Desig_Type      : Entity_Id;
5289       Discr           : Entity_Id;
5290       Discr_Con_Elist : Elist_Id;
5291       Discr_Con_El    : Elmt_Id;
5292       Subt            : Entity_Id;
5293
5294    begin
5295       --  Set the designated type so it is available in case this is an access
5296       --  to a self-referential type, e.g. a standard list type with a next
5297       --  pointer. Will be reset after subtype is built.
5298
5299       Set_Directly_Designated_Type
5300         (Derived_Type, Designated_Type (Parent_Type));
5301
5302       Subt := Process_Subtype (S, N);
5303
5304       if Nkind (S) /= N_Subtype_Indication
5305         and then Subt /= Base_Type (Subt)
5306       then
5307          Set_Ekind (Derived_Type, E_Access_Subtype);
5308       end if;
5309
5310       if Ekind (Derived_Type) = E_Access_Subtype then
5311          declare
5312             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
5313             Ibase      : constant Entity_Id :=
5314                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
5315             Svg_Chars  : constant Name_Id   := Chars (Ibase);
5316             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
5317
5318          begin
5319             Copy_Node (Pbase, Ibase);
5320
5321             Set_Chars             (Ibase, Svg_Chars);
5322             Set_Next_Entity       (Ibase, Svg_Next_E);
5323             Set_Sloc              (Ibase, Sloc (Derived_Type));
5324             Set_Scope             (Ibase, Scope (Derived_Type));
5325             Set_Freeze_Node       (Ibase, Empty);
5326             Set_Is_Frozen         (Ibase, False);
5327             Set_Comes_From_Source (Ibase, False);
5328             Set_Is_First_Subtype  (Ibase, False);
5329
5330             Set_Etype (Ibase, Pbase);
5331             Set_Etype (Derived_Type, Ibase);
5332          end;
5333       end if;
5334
5335       Set_Directly_Designated_Type
5336         (Derived_Type, Designated_Type (Subt));
5337
5338       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
5339       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
5340       Set_Size_Info          (Derived_Type,                     Parent_Type);
5341       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
5342       Set_Depends_On_Private (Derived_Type,
5343                               Has_Private_Component (Derived_Type));
5344       Conditional_Delay      (Derived_Type, Subt);
5345
5346       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
5347       --  that it is not redundant.
5348
5349       if Null_Exclusion_Present (Type_Definition (N)) then
5350          Set_Can_Never_Be_Null (Derived_Type);
5351
5352          if Can_Never_Be_Null (Parent_Type)
5353            and then False
5354          then
5355             Error_Msg_NE
5356               ("`NOT NULL` not allowed (& already excludes null)",
5357                 N, Parent_Type);
5358          end if;
5359
5360       elsif Can_Never_Be_Null (Parent_Type) then
5361          Set_Can_Never_Be_Null (Derived_Type);
5362       end if;
5363
5364       --  Note: we do not copy the Storage_Size_Variable, since we always go to
5365       --  the root type for this information.
5366
5367       --  Apply range checks to discriminants for derived record case
5368       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
5369
5370       Desig_Type := Designated_Type (Derived_Type);
5371       if Is_Composite_Type (Desig_Type)
5372         and then (not Is_Array_Type (Desig_Type))
5373         and then Has_Discriminants (Desig_Type)
5374         and then Base_Type (Desig_Type) /= Desig_Type
5375       then
5376          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
5377          Discr_Con_El := First_Elmt (Discr_Con_Elist);
5378
5379          Discr := First_Discriminant (Base_Type (Desig_Type));
5380          while Present (Discr_Con_El) loop
5381             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
5382             Next_Elmt (Discr_Con_El);
5383             Next_Discriminant (Discr);
5384          end loop;
5385       end if;
5386    end Build_Derived_Access_Type;
5387
5388    ------------------------------
5389    -- Build_Derived_Array_Type --
5390    ------------------------------
5391
5392    procedure Build_Derived_Array_Type
5393      (N            : Node_Id;
5394       Parent_Type  : Entity_Id;
5395       Derived_Type : Entity_Id)
5396    is
5397       Loc           : constant Source_Ptr := Sloc (N);
5398       Tdef          : constant Node_Id    := Type_Definition (N);
5399       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5400       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5401       Implicit_Base : Entity_Id;
5402       New_Indic     : Node_Id;
5403
5404       procedure Make_Implicit_Base;
5405       --  If the parent subtype is constrained, the derived type is a subtype
5406       --  of an implicit base type derived from the parent base.
5407
5408       ------------------------
5409       -- Make_Implicit_Base --
5410       ------------------------
5411
5412       procedure Make_Implicit_Base is
5413       begin
5414          Implicit_Base :=
5415            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5416
5417          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
5418          Set_Etype (Implicit_Base, Parent_Base);
5419
5420          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
5421          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
5422
5423          Set_Has_Delayed_Freeze (Implicit_Base, True);
5424       end Make_Implicit_Base;
5425
5426    --  Start of processing for Build_Derived_Array_Type
5427
5428    begin
5429       if not Is_Constrained (Parent_Type) then
5430          if Nkind (Indic) /= N_Subtype_Indication then
5431             Set_Ekind (Derived_Type, E_Array_Type);
5432
5433             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
5434             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
5435
5436             Set_Has_Delayed_Freeze (Derived_Type, True);
5437
5438          else
5439             Make_Implicit_Base;
5440             Set_Etype (Derived_Type, Implicit_Base);
5441
5442             New_Indic :=
5443               Make_Subtype_Declaration (Loc,
5444                 Defining_Identifier => Derived_Type,
5445                 Subtype_Indication  =>
5446                   Make_Subtype_Indication (Loc,
5447                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
5448                     Constraint => Constraint (Indic)));
5449
5450             Rewrite (N, New_Indic);
5451             Analyze (N);
5452          end if;
5453
5454       else
5455          if Nkind (Indic) /= N_Subtype_Indication then
5456             Make_Implicit_Base;
5457
5458             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
5459             Set_Etype             (Derived_Type, Implicit_Base);
5460             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
5461
5462          else
5463             Error_Msg_N ("illegal constraint on constrained type", Indic);
5464          end if;
5465       end if;
5466
5467       --  If parent type is not a derived type itself, and is declared in
5468       --  closed scope (e.g. a subprogram), then we must explicitly introduce
5469       --  the new type's concatenation operator since Derive_Subprograms
5470       --  will not inherit the parent's operator. If the parent type is
5471       --  unconstrained, the operator is of the unconstrained base type.
5472
5473       if Number_Dimensions (Parent_Type) = 1
5474         and then not Is_Limited_Type (Parent_Type)
5475         and then not Is_Derived_Type (Parent_Type)
5476         and then not Is_Package_Or_Generic_Package
5477                        (Scope (Base_Type (Parent_Type)))
5478       then
5479          if not Is_Constrained (Parent_Type)
5480            and then Is_Constrained (Derived_Type)
5481          then
5482             New_Concatenation_Op (Implicit_Base);
5483          else
5484             New_Concatenation_Op (Derived_Type);
5485          end if;
5486       end if;
5487    end Build_Derived_Array_Type;
5488
5489    -----------------------------------
5490    -- Build_Derived_Concurrent_Type --
5491    -----------------------------------
5492
5493    procedure Build_Derived_Concurrent_Type
5494      (N            : Node_Id;
5495       Parent_Type  : Entity_Id;
5496       Derived_Type : Entity_Id)
5497    is
5498       Loc : constant Source_Ptr := Sloc (N);
5499
5500       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
5501       Corr_Decl        : Node_Id;
5502       Corr_Decl_Needed : Boolean;
5503       --  If the derived type has fewer discriminants than its parent, the
5504       --  corresponding record is also a derived type, in order to account for
5505       --  the bound discriminants. We create a full type declaration for it in
5506       --  this case.
5507
5508       Constraint_Present : constant Boolean :=
5509                              Nkind (Subtype_Indication (Type_Definition (N))) =
5510                                                           N_Subtype_Indication;
5511
5512       D_Constraint   : Node_Id;
5513       New_Constraint : Elist_Id;
5514       Old_Disc       : Entity_Id;
5515       New_Disc       : Entity_Id;
5516       New_N          : Node_Id;
5517
5518    begin
5519       Set_Stored_Constraint (Derived_Type, No_Elist);
5520       Corr_Decl_Needed := False;
5521       Old_Disc := Empty;
5522
5523       if Present (Discriminant_Specifications (N))
5524         and then Constraint_Present
5525       then
5526          Old_Disc := First_Discriminant (Parent_Type);
5527          New_Disc := First (Discriminant_Specifications (N));
5528          while Present (New_Disc) and then Present (Old_Disc) loop
5529             Next_Discriminant (Old_Disc);
5530             Next (New_Disc);
5531          end loop;
5532       end if;
5533
5534       if Present (Old_Disc) and then Expander_Active then
5535
5536          --  The new type has fewer discriminants, so we need to create a new
5537          --  corresponding record, which is derived from the corresponding
5538          --  record of the parent, and has a stored constraint that captures
5539          --  the values of the discriminant constraints. The corresponding
5540          --  record is needed only if expander is active and code generation is
5541          --  enabled.
5542
5543          --  The type declaration for the derived corresponding record has the
5544          --  same discriminant part and constraints as the current declaration.
5545          --  Copy the unanalyzed tree to build declaration.
5546
5547          Corr_Decl_Needed := True;
5548          New_N := Copy_Separate_Tree (N);
5549
5550          Corr_Decl :=
5551            Make_Full_Type_Declaration (Loc,
5552              Defining_Identifier         => Corr_Record,
5553              Discriminant_Specifications =>
5554                 Discriminant_Specifications (New_N),
5555              Type_Definition             =>
5556                Make_Derived_Type_Definition (Loc,
5557                  Subtype_Indication =>
5558                    Make_Subtype_Indication (Loc,
5559                      Subtype_Mark =>
5560                         New_Occurrence_Of
5561                           (Corresponding_Record_Type (Parent_Type), Loc),
5562                      Constraint   =>
5563                        Constraint
5564                          (Subtype_Indication (Type_Definition (New_N))))));
5565       end if;
5566
5567       --  Copy Storage_Size and Relative_Deadline variables if task case
5568
5569       if Is_Task_Type (Parent_Type) then
5570          Set_Storage_Size_Variable (Derived_Type,
5571            Storage_Size_Variable (Parent_Type));
5572          Set_Relative_Deadline_Variable (Derived_Type,
5573            Relative_Deadline_Variable (Parent_Type));
5574       end if;
5575
5576       if Present (Discriminant_Specifications (N)) then
5577          Push_Scope (Derived_Type);
5578          Check_Or_Process_Discriminants (N, Derived_Type);
5579
5580          if Constraint_Present then
5581             New_Constraint :=
5582               Expand_To_Stored_Constraint
5583                 (Parent_Type,
5584                  Build_Discriminant_Constraints
5585                    (Parent_Type,
5586                     Subtype_Indication (Type_Definition (N)), True));
5587          end if;
5588
5589          End_Scope;
5590
5591       elsif Constraint_Present then
5592
5593          --  Build constrained subtype, copying the constraint, and derive
5594          --  from it to create a derived constrained type.
5595
5596          declare
5597             Loc  : constant Source_Ptr := Sloc (N);
5598             Anon : constant Entity_Id :=
5599                      Make_Defining_Identifier (Loc,
5600                        Chars => New_External_Name (Chars (Derived_Type), 'T'));
5601             Decl : Node_Id;
5602
5603          begin
5604             Decl :=
5605               Make_Subtype_Declaration (Loc,
5606                 Defining_Identifier => Anon,
5607                 Subtype_Indication =>
5608                   New_Copy_Tree (Subtype_Indication (Type_Definition (N))));
5609             Insert_Before (N, Decl);
5610             Analyze (Decl);
5611
5612             Rewrite (Subtype_Indication (Type_Definition (N)),
5613               New_Occurrence_Of (Anon, Loc));
5614             Set_Analyzed (Derived_Type, False);
5615             Analyze (N);
5616             return;
5617          end;
5618       end if;
5619
5620       --  By default, operations and private data are inherited from parent.
5621       --  However, in the presence of bound discriminants, a new corresponding
5622       --  record will be created, see below.
5623
5624       Set_Has_Discriminants
5625         (Derived_Type, Has_Discriminants         (Parent_Type));
5626       Set_Corresponding_Record_Type
5627         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5628
5629       --  Is_Constrained is set according the parent subtype, but is set to
5630       --  False if the derived type is declared with new discriminants.
5631
5632       Set_Is_Constrained
5633         (Derived_Type,
5634          (Is_Constrained (Parent_Type) or else Constraint_Present)
5635            and then not Present (Discriminant_Specifications (N)));
5636
5637       if Constraint_Present then
5638          if not Has_Discriminants (Parent_Type) then
5639             Error_Msg_N ("untagged parent must have discriminants", N);
5640
5641          elsif Present (Discriminant_Specifications (N)) then
5642
5643             --  Verify that new discriminants are used to constrain old ones
5644
5645             D_Constraint :=
5646               First
5647                 (Constraints
5648                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5649
5650             Old_Disc := First_Discriminant (Parent_Type);
5651
5652             while Present (D_Constraint) loop
5653                if Nkind (D_Constraint) /= N_Discriminant_Association then
5654
5655                   --  Positional constraint. If it is a reference to a new
5656                   --  discriminant, it constrains the corresponding old one.
5657
5658                   if Nkind (D_Constraint) = N_Identifier then
5659                      New_Disc := First_Discriminant (Derived_Type);
5660                      while Present (New_Disc) loop
5661                         exit when Chars (New_Disc) = Chars (D_Constraint);
5662                         Next_Discriminant (New_Disc);
5663                      end loop;
5664
5665                      if Present (New_Disc) then
5666                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5667                      end if;
5668                   end if;
5669
5670                   Next_Discriminant (Old_Disc);
5671
5672                   --  if this is a named constraint, search by name for the old
5673                   --  discriminants constrained by the new one.
5674
5675                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5676
5677                   --  Find new discriminant with that name
5678
5679                   New_Disc := First_Discriminant (Derived_Type);
5680                   while Present (New_Disc) loop
5681                      exit when
5682                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5683                      Next_Discriminant (New_Disc);
5684                   end loop;
5685
5686                   if Present (New_Disc) then
5687
5688                      --  Verify that new discriminant renames some discriminant
5689                      --  of the parent type, and associate the new discriminant
5690                      --  with one or more old ones that it renames.
5691
5692                      declare
5693                         Selector : Node_Id;
5694
5695                      begin
5696                         Selector := First (Selector_Names (D_Constraint));
5697                         while Present (Selector) loop
5698                            Old_Disc := First_Discriminant (Parent_Type);
5699                            while Present (Old_Disc) loop
5700                               exit when Chars (Old_Disc) = Chars (Selector);
5701                               Next_Discriminant (Old_Disc);
5702                            end loop;
5703
5704                            if Present (Old_Disc) then
5705                               Set_Corresponding_Discriminant
5706                                 (New_Disc, Old_Disc);
5707                            end if;
5708
5709                            Next (Selector);
5710                         end loop;
5711                      end;
5712                   end if;
5713                end if;
5714
5715                Next (D_Constraint);
5716             end loop;
5717
5718             New_Disc := First_Discriminant (Derived_Type);
5719             while Present (New_Disc) loop
5720                if No (Corresponding_Discriminant (New_Disc)) then
5721                   Error_Msg_NE
5722                     ("new discriminant& must constrain old one", N, New_Disc);
5723
5724                elsif not
5725                  Subtypes_Statically_Compatible
5726                    (Etype (New_Disc),
5727                     Etype (Corresponding_Discriminant (New_Disc)))
5728                then
5729                   Error_Msg_NE
5730                     ("& not statically compatible with parent discriminant",
5731                       N, New_Disc);
5732                end if;
5733
5734                Next_Discriminant (New_Disc);
5735             end loop;
5736          end if;
5737
5738       elsif Present (Discriminant_Specifications (N)) then
5739          Error_Msg_N
5740            ("missing discriminant constraint in untagged derivation", N);
5741       end if;
5742
5743       --  The entity chain of the derived type includes the new discriminants
5744       --  but shares operations with the parent.
5745
5746       if Present (Discriminant_Specifications (N)) then
5747          Old_Disc := First_Discriminant (Parent_Type);
5748          while Present (Old_Disc) loop
5749             if No (Next_Entity (Old_Disc))
5750               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5751             then
5752                Set_Next_Entity
5753                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5754                exit;
5755             end if;
5756
5757             Next_Discriminant (Old_Disc);
5758          end loop;
5759
5760       else
5761          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5762          if Has_Discriminants (Parent_Type) then
5763             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5764             Set_Discriminant_Constraint (
5765               Derived_Type, Discriminant_Constraint (Parent_Type));
5766          end if;
5767       end if;
5768
5769       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5770
5771       Set_Has_Completion (Derived_Type);
5772
5773       if Corr_Decl_Needed then
5774          Set_Stored_Constraint (Derived_Type, New_Constraint);
5775          Insert_After (N, Corr_Decl);
5776          Analyze (Corr_Decl);
5777          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5778       end if;
5779    end Build_Derived_Concurrent_Type;
5780
5781    ------------------------------------
5782    -- Build_Derived_Enumeration_Type --
5783    ------------------------------------
5784
5785    procedure Build_Derived_Enumeration_Type
5786      (N            : Node_Id;
5787       Parent_Type  : Entity_Id;
5788       Derived_Type : Entity_Id)
5789    is
5790       Loc           : constant Source_Ptr := Sloc (N);
5791       Def           : constant Node_Id    := Type_Definition (N);
5792       Indic         : constant Node_Id    := Subtype_Indication (Def);
5793       Implicit_Base : Entity_Id;
5794       Literal       : Entity_Id;
5795       New_Lit       : Entity_Id;
5796       Literals_List : List_Id;
5797       Type_Decl     : Node_Id;
5798       Hi, Lo        : Node_Id;
5799       Rang_Expr     : Node_Id;
5800
5801    begin
5802       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5803       --  not have explicit literals lists we need to process types derived
5804       --  from them specially. This is handled by Derived_Standard_Character.
5805       --  If the parent type is a generic type, there are no literals either,
5806       --  and we construct the same skeletal representation as for the generic
5807       --  parent type.
5808
5809       if Is_Standard_Character_Type (Parent_Type) then
5810          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5811
5812       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5813          declare
5814             Lo : Node_Id;
5815             Hi : Node_Id;
5816
5817          begin
5818             if Nkind (Indic) /= N_Subtype_Indication then
5819                Lo :=
5820                   Make_Attribute_Reference (Loc,
5821                     Attribute_Name => Name_First,
5822                     Prefix         => New_Reference_To (Derived_Type, Loc));
5823                Set_Etype (Lo, Derived_Type);
5824
5825                Hi :=
5826                   Make_Attribute_Reference (Loc,
5827                     Attribute_Name => Name_Last,
5828                     Prefix         => New_Reference_To (Derived_Type, Loc));
5829                Set_Etype (Hi, Derived_Type);
5830
5831                Set_Scalar_Range (Derived_Type,
5832                   Make_Range (Loc,
5833                     Low_Bound  => Lo,
5834                     High_Bound => Hi));
5835             else
5836
5837                --   Analyze subtype indication and verify compatibility
5838                --   with parent type.
5839
5840                if Base_Type (Process_Subtype (Indic, N)) /=
5841                   Base_Type (Parent_Type)
5842                then
5843                   Error_Msg_N
5844                     ("illegal constraint for formal discrete type", N);
5845                end if;
5846             end if;
5847          end;
5848
5849       else
5850          --  If a constraint is present, analyze the bounds to catch
5851          --  premature usage of the derived literals.
5852
5853          if Nkind (Indic) = N_Subtype_Indication
5854            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5855          then
5856             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5857             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5858          end if;
5859
5860          --  Introduce an implicit base type for the derived type even if there
5861          --  is no constraint attached to it, since this seems closer to the
5862          --  Ada semantics. Build a full type declaration tree for the derived
5863          --  type using the implicit base type as the defining identifier. The
5864          --  build a subtype declaration tree which applies the constraint (if
5865          --  any) have it replace the derived type declaration.
5866
5867          Literal := First_Literal (Parent_Type);
5868          Literals_List := New_List;
5869          while Present (Literal)
5870            and then Ekind (Literal) = E_Enumeration_Literal
5871          loop
5872             --  Literals of the derived type have the same representation as
5873             --  those of the parent type, but this representation can be
5874             --  overridden by an explicit representation clause. Indicate
5875             --  that there is no explicit representation given yet. These
5876             --  derived literals are implicit operations of the new type,
5877             --  and can be overridden by explicit ones.
5878
5879             if Nkind (Literal) = N_Defining_Character_Literal then
5880                New_Lit :=
5881                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5882             else
5883                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5884             end if;
5885
5886             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5887             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5888             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5889             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5890             Set_Alias                (New_Lit, Literal);
5891             Set_Is_Known_Valid       (New_Lit, True);
5892
5893             Append (New_Lit, Literals_List);
5894             Next_Literal (Literal);
5895          end loop;
5896
5897          Implicit_Base :=
5898            Make_Defining_Identifier (Sloc (Derived_Type),
5899              Chars => New_External_Name (Chars (Derived_Type), 'B'));
5900
5901          --  Indicate the proper nature of the derived type. This must be done
5902          --  before analysis of the literals, to recognize cases when a literal
5903          --  may be hidden by a previous explicit function definition (cf.
5904          --  c83031a).
5905
5906          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5907          Set_Etype (Derived_Type, Implicit_Base);
5908
5909          Type_Decl :=
5910            Make_Full_Type_Declaration (Loc,
5911              Defining_Identifier => Implicit_Base,
5912              Discriminant_Specifications => No_List,
5913              Type_Definition =>
5914                Make_Enumeration_Type_Definition (Loc, Literals_List));
5915
5916          Mark_Rewrite_Insertion (Type_Decl);
5917          Insert_Before (N, Type_Decl);
5918          Analyze (Type_Decl);
5919
5920          --  After the implicit base is analyzed its Etype needs to be changed
5921          --  to reflect the fact that it is derived from the parent type which
5922          --  was ignored during analysis. We also set the size at this point.
5923
5924          Set_Etype (Implicit_Base, Parent_Type);
5925
5926          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5927          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5928          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5929
5930          --  Copy other flags from parent type
5931
5932          Set_Has_Non_Standard_Rep
5933                             (Implicit_Base, Has_Non_Standard_Rep
5934                                                            (Parent_Type));
5935          Set_Has_Pragma_Ordered
5936                             (Implicit_Base, Has_Pragma_Ordered
5937                                                            (Parent_Type));
5938          Set_Has_Delayed_Freeze (Implicit_Base);
5939
5940          --  Process the subtype indication including a validation check on the
5941          --  constraint, if any. If a constraint is given, its bounds must be
5942          --  implicitly converted to the new type.
5943
5944          if Nkind (Indic) = N_Subtype_Indication then
5945             declare
5946                R : constant Node_Id :=
5947                      Range_Expression (Constraint (Indic));
5948
5949             begin
5950                if Nkind (R) = N_Range then
5951                   Hi := Build_Scalar_Bound
5952                           (High_Bound (R), Parent_Type, Implicit_Base);
5953                   Lo := Build_Scalar_Bound
5954                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5955
5956                else
5957                   --  Constraint is a Range attribute. Replace with explicit
5958                   --  mention of the bounds of the prefix, which must be a
5959                   --  subtype.
5960
5961                   Analyze (Prefix (R));
5962                   Hi :=
5963                     Convert_To (Implicit_Base,
5964                       Make_Attribute_Reference (Loc,
5965                         Attribute_Name => Name_Last,
5966                         Prefix =>
5967                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5968
5969                   Lo :=
5970                     Convert_To (Implicit_Base,
5971                       Make_Attribute_Reference (Loc,
5972                         Attribute_Name => Name_First,
5973                         Prefix =>
5974                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5975                end if;
5976             end;
5977
5978          else
5979             Hi :=
5980               Build_Scalar_Bound
5981                 (Type_High_Bound (Parent_Type),
5982                  Parent_Type, Implicit_Base);
5983             Lo :=
5984                Build_Scalar_Bound
5985                  (Type_Low_Bound (Parent_Type),
5986                   Parent_Type, Implicit_Base);
5987          end if;
5988
5989          Rang_Expr :=
5990            Make_Range (Loc,
5991              Low_Bound  => Lo,
5992              High_Bound => Hi);
5993
5994          --  If we constructed a default range for the case where no range
5995          --  was given, then the expressions in the range must not freeze
5996          --  since they do not correspond to expressions in the source.
5997
5998          if Nkind (Indic) /= N_Subtype_Indication then
5999             Set_Must_Not_Freeze (Lo);
6000             Set_Must_Not_Freeze (Hi);
6001             Set_Must_Not_Freeze (Rang_Expr);
6002          end if;
6003
6004          Rewrite (N,
6005            Make_Subtype_Declaration (Loc,
6006              Defining_Identifier => Derived_Type,
6007              Subtype_Indication =>
6008                Make_Subtype_Indication (Loc,
6009                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
6010                  Constraint =>
6011                    Make_Range_Constraint (Loc,
6012                      Range_Expression => Rang_Expr))));
6013
6014          Analyze (N);
6015
6016          --  Apply a range check. Since this range expression doesn't have an
6017          --  Etype, we have to specifically pass the Source_Typ parameter. Is
6018          --  this right???
6019
6020          if Nkind (Indic) = N_Subtype_Indication then
6021             Apply_Range_Check (Range_Expression (Constraint (Indic)),
6022                                Parent_Type,
6023                                Source_Typ => Entity (Subtype_Mark (Indic)));
6024          end if;
6025       end if;
6026    end Build_Derived_Enumeration_Type;
6027
6028    --------------------------------
6029    -- Build_Derived_Numeric_Type --
6030    --------------------------------
6031
6032    procedure Build_Derived_Numeric_Type
6033      (N            : Node_Id;
6034       Parent_Type  : Entity_Id;
6035       Derived_Type : Entity_Id)
6036    is
6037       Loc           : constant Source_Ptr := Sloc (N);
6038       Tdef          : constant Node_Id    := Type_Definition (N);
6039       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
6040       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
6041       No_Constraint : constant Boolean    := Nkind (Indic) /=
6042                                                   N_Subtype_Indication;
6043       Implicit_Base : Entity_Id;
6044
6045       Lo : Node_Id;
6046       Hi : Node_Id;
6047
6048    begin
6049       --  Process the subtype indication including a validation check on
6050       --  the constraint if any.
6051
6052       Discard_Node (Process_Subtype (Indic, N));
6053
6054       --  Introduce an implicit base type for the derived type even if there
6055       --  is no constraint attached to it, since this seems closer to the Ada
6056       --  semantics.
6057
6058       Implicit_Base :=
6059         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
6060
6061       Set_Etype          (Implicit_Base, Parent_Base);
6062       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
6063       Set_Size_Info      (Implicit_Base,                 Parent_Base);
6064       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
6065       Set_Parent         (Implicit_Base, Parent (Derived_Type));
6066       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
6067
6068       --  Set RM Size for discrete type or decimal fixed-point type
6069       --  Ordinary fixed-point is excluded, why???
6070
6071       if Is_Discrete_Type (Parent_Base)
6072         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
6073       then
6074          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
6075       end if;
6076
6077       Set_Has_Delayed_Freeze (Implicit_Base);
6078
6079       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
6080       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
6081
6082       Set_Scalar_Range (Implicit_Base,
6083         Make_Range (Loc,
6084           Low_Bound  => Lo,
6085           High_Bound => Hi));
6086
6087       if Has_Infinities (Parent_Base) then
6088          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
6089       end if;
6090
6091       --  The Derived_Type, which is the entity of the declaration, is a
6092       --  subtype of the implicit base. Its Ekind is a subtype, even in the
6093       --  absence of an explicit constraint.
6094
6095       Set_Etype (Derived_Type, Implicit_Base);
6096
6097       --  If we did not have a constraint, then the Ekind is set from the
6098       --  parent type (otherwise Process_Subtype has set the bounds)
6099
6100       if No_Constraint then
6101          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
6102       end if;
6103
6104       --  If we did not have a range constraint, then set the range from the
6105       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
6106
6107       if No_Constraint
6108         or else not Has_Range_Constraint (Indic)
6109       then
6110          Set_Scalar_Range (Derived_Type,
6111            Make_Range (Loc,
6112              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
6113              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
6114          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
6115
6116          if Has_Infinities (Parent_Type) then
6117             Set_Includes_Infinities (Scalar_Range (Derived_Type));
6118          end if;
6119
6120          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
6121       end if;
6122
6123       Set_Is_Descendent_Of_Address (Derived_Type,
6124         Is_Descendent_Of_Address (Parent_Type));
6125       Set_Is_Descendent_Of_Address (Implicit_Base,
6126         Is_Descendent_Of_Address (Parent_Type));
6127
6128       --  Set remaining type-specific fields, depending on numeric type
6129
6130       if Is_Modular_Integer_Type (Parent_Type) then
6131          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
6132
6133          Set_Non_Binary_Modulus
6134            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
6135
6136          Set_Is_Known_Valid
6137            (Implicit_Base, Is_Known_Valid (Parent_Base));
6138
6139       elsif Is_Floating_Point_Type (Parent_Type) then
6140
6141          --  Digits of base type is always copied from the digits value of
6142          --  the parent base type, but the digits of the derived type will
6143          --  already have been set if there was a constraint present.
6144
6145          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6146          Set_Float_Rep    (Implicit_Base, Float_Rep    (Parent_Base));
6147
6148          if No_Constraint then
6149             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
6150          end if;
6151
6152       elsif Is_Fixed_Point_Type (Parent_Type) then
6153
6154          --  Small of base type and derived type are always copied from the
6155          --  parent base type, since smalls never change. The delta of the
6156          --  base type is also copied from the parent base type. However the
6157          --  delta of the derived type will have been set already if a
6158          --  constraint was present.
6159
6160          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
6161          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
6162          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
6163
6164          if No_Constraint then
6165             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
6166          end if;
6167
6168          --  The scale and machine radix in the decimal case are always
6169          --  copied from the parent base type.
6170
6171          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
6172             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
6173             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
6174
6175             Set_Machine_Radix_10
6176               (Derived_Type,  Machine_Radix_10 (Parent_Base));
6177             Set_Machine_Radix_10
6178               (Implicit_Base, Machine_Radix_10 (Parent_Base));
6179
6180             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6181
6182             if No_Constraint then
6183                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
6184
6185             else
6186                --  the analysis of the subtype_indication sets the
6187                --  digits value of the derived type.
6188
6189                null;
6190             end if;
6191          end if;
6192       end if;
6193
6194       --  The type of the bounds is that of the parent type, and they
6195       --  must be converted to the derived type.
6196
6197       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
6198
6199       --  The implicit_base should be frozen when the derived type is frozen,
6200       --  but note that it is used in the conversions of the bounds. For fixed
6201       --  types we delay the determination of the bounds until the proper
6202       --  freezing point. For other numeric types this is rejected by GCC, for
6203       --  reasons that are currently unclear (???), so we choose to freeze the
6204       --  implicit base now. In the case of integers and floating point types
6205       --  this is harmless because subsequent representation clauses cannot
6206       --  affect anything, but it is still baffling that we cannot use the
6207       --  same mechanism for all derived numeric types.
6208
6209       --  There is a further complication: actually some representation
6210       --  clauses can affect the implicit base type. For example, attribute
6211       --  definition clauses for stream-oriented attributes need to set the
6212       --  corresponding TSS entries on the base type, and this normally
6213       --  cannot be done after the base type is frozen, so the circuitry in
6214       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility
6215       --  and not use Set_TSS in this case.
6216
6217       --  There are also consequences for the case of delayed representation
6218       --  aspects for some cases. For example, a Size aspect is delayed and
6219       --  should not be evaluated to the freeze point. This early freezing
6220       --  means that the size attribute evaluation happens too early???
6221
6222       if Is_Fixed_Point_Type (Parent_Type) then
6223          Conditional_Delay (Implicit_Base, Parent_Type);
6224       else
6225          Freeze_Before (N, Implicit_Base);
6226       end if;
6227    end Build_Derived_Numeric_Type;
6228
6229    --------------------------------
6230    -- Build_Derived_Private_Type --
6231    --------------------------------
6232
6233    procedure Build_Derived_Private_Type
6234      (N             : Node_Id;
6235       Parent_Type   : Entity_Id;
6236       Derived_Type  : Entity_Id;
6237       Is_Completion : Boolean;
6238       Derive_Subps  : Boolean := True)
6239    is
6240       Loc         : constant Source_Ptr := Sloc (N);
6241       Der_Base    : Entity_Id;
6242       Discr       : Entity_Id;
6243       Full_Decl   : Node_Id := Empty;
6244       Full_Der    : Entity_Id;
6245       Full_P      : Entity_Id;
6246       Last_Discr  : Entity_Id;
6247       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
6248       Swapped     : Boolean := False;
6249
6250       procedure Copy_And_Build;
6251       --  Copy derived type declaration, replace parent with its full view,
6252       --  and analyze new declaration.
6253
6254       --------------------
6255       -- Copy_And_Build --
6256       --------------------
6257
6258       procedure Copy_And_Build is
6259          Full_N : Node_Id;
6260
6261       begin
6262          if Ekind (Parent_Type) in Record_Kind
6263            or else
6264              (Ekind (Parent_Type) in Enumeration_Kind
6265                and then not Is_Standard_Character_Type (Parent_Type)
6266                and then not Is_Generic_Type (Root_Type (Parent_Type)))
6267          then
6268             Full_N := New_Copy_Tree (N);
6269             Insert_After (N, Full_N);
6270             Build_Derived_Type (
6271               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
6272
6273          else
6274             Build_Derived_Type (
6275               N, Parent_Type, Full_Der, True, Derive_Subps => False);
6276          end if;
6277       end Copy_And_Build;
6278
6279    --  Start of processing for Build_Derived_Private_Type
6280
6281    begin
6282       if Is_Tagged_Type (Parent_Type) then
6283          Full_P := Full_View (Parent_Type);
6284
6285          --  A type extension of a type with unknown discriminants is an
6286          --  indefinite type that the back-end cannot handle directly.
6287          --  We treat it as a private type, and build a completion that is
6288          --  derived from the full view of the parent, and hopefully has
6289          --  known discriminants.
6290
6291          --  If the full view of the parent type has an underlying record view,
6292          --  use it to generate the underlying record view of this derived type
6293          --  (required for chains of derivations with unknown discriminants).
6294
6295          --  Minor optimization: we avoid the generation of useless underlying
6296          --  record view entities if the private type declaration has unknown
6297          --  discriminants but its corresponding full view has no
6298          --  discriminants.
6299
6300          if Has_Unknown_Discriminants (Parent_Type)
6301            and then Present (Full_P)
6302            and then (Has_Discriminants (Full_P)
6303                       or else Present (Underlying_Record_View (Full_P)))
6304            and then not In_Open_Scopes (Par_Scope)
6305            and then Expander_Active
6306          then
6307             declare
6308                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
6309                New_Ext  : constant Node_Id :=
6310                             Copy_Separate_Tree
6311                               (Record_Extension_Part (Type_Definition (N)));
6312                Decl     : Node_Id;
6313
6314             begin
6315                Build_Derived_Record_Type
6316                  (N, Parent_Type, Derived_Type, Derive_Subps);
6317
6318                --  Build anonymous completion, as a derivation from the full
6319                --  view of the parent. This is not a completion in the usual
6320                --  sense, because the current type is not private.
6321
6322                Decl :=
6323                  Make_Full_Type_Declaration (Loc,
6324                    Defining_Identifier => Full_Der,
6325                    Type_Definition     =>
6326                      Make_Derived_Type_Definition (Loc,
6327                        Subtype_Indication =>
6328                          New_Copy_Tree
6329                            (Subtype_Indication (Type_Definition (N))),
6330                        Record_Extension_Part => New_Ext));
6331
6332                --  If the parent type has an underlying record view, use it
6333                --  here to build the new underlying record view.
6334
6335                if Present (Underlying_Record_View (Full_P)) then
6336                   pragma Assert
6337                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
6338                        = N_Identifier);
6339                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
6340                     Underlying_Record_View (Full_P));
6341                end if;
6342
6343                Install_Private_Declarations (Par_Scope);
6344                Install_Visible_Declarations (Par_Scope);
6345                Insert_Before (N, Decl);
6346
6347                --  Mark entity as an underlying record view before analysis,
6348                --  to avoid generating the list of its primitive operations
6349                --  (which is not really required for this entity) and thus
6350                --  prevent spurious errors associated with missing overriding
6351                --  of abstract primitives (overridden only for Derived_Type).
6352
6353                Set_Ekind (Full_Der, E_Record_Type);
6354                Set_Is_Underlying_Record_View (Full_Der);
6355
6356                Analyze (Decl);
6357
6358                pragma Assert (Has_Discriminants (Full_Der)
6359                  and then not Has_Unknown_Discriminants (Full_Der));
6360
6361                Uninstall_Declarations (Par_Scope);
6362
6363                --  Freeze the underlying record view, to prevent generation of
6364                --  useless dispatching information, which is simply shared with
6365                --  the real derived type.
6366
6367                Set_Is_Frozen (Full_Der);
6368
6369                --  Set up links between real entity and underlying record view
6370
6371                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
6372                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
6373             end;
6374
6375          --  If discriminants are known, build derived record
6376
6377          else
6378             Build_Derived_Record_Type
6379               (N, Parent_Type, Derived_Type, Derive_Subps);
6380          end if;
6381
6382          return;
6383
6384       elsif Has_Discriminants (Parent_Type) then
6385          if Present (Full_View (Parent_Type)) then
6386             if not Is_Completion then
6387
6388                --  Copy declaration for subsequent analysis, to provide a
6389                --  completion for what is a private declaration. Indicate that
6390                --  the full type is internally generated.
6391
6392                Full_Decl := New_Copy_Tree (N);
6393                Full_Der  := New_Copy (Derived_Type);
6394                Set_Comes_From_Source (Full_Decl, False);
6395                Set_Comes_From_Source (Full_Der, False);
6396                Set_Parent (Full_Der, Full_Decl);
6397
6398                Insert_After (N, Full_Decl);
6399
6400             else
6401                --  If this is a completion, the full view being built is itself
6402                --  private. We build a subtype of the parent with the same
6403                --  constraints as this full view, to convey to the back end the
6404                --  constrained components and the size of this subtype. If the
6405                --  parent is constrained, its full view can serve as the
6406                --  underlying full view of the derived type.
6407
6408                if No (Discriminant_Specifications (N)) then
6409                   if Nkind (Subtype_Indication (Type_Definition (N))) =
6410                                                         N_Subtype_Indication
6411                   then
6412                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
6413
6414                   elsif Is_Constrained (Full_View (Parent_Type)) then
6415                      Set_Underlying_Full_View
6416                        (Derived_Type, Full_View (Parent_Type));
6417                   end if;
6418
6419                else
6420                   --  If there are new discriminants, the parent subtype is
6421                   --  constrained by them, but it is not clear how to build
6422                   --  the Underlying_Full_View in this case???
6423
6424                   null;
6425                end if;
6426             end if;
6427          end if;
6428
6429          --  Build partial view of derived type from partial view of parent
6430
6431          Build_Derived_Record_Type
6432            (N, Parent_Type, Derived_Type, Derive_Subps);
6433
6434          if Present (Full_View (Parent_Type)) and then not Is_Completion then
6435             if not In_Open_Scopes (Par_Scope)
6436               or else not In_Same_Source_Unit (N, Parent_Type)
6437             then
6438                --  Swap partial and full views temporarily
6439
6440                Install_Private_Declarations (Par_Scope);
6441                Install_Visible_Declarations (Par_Scope);
6442                Swapped := True;
6443             end if;
6444
6445             --  Build full view of derived type from full view of parent which
6446             --  is now installed. Subprograms have been derived on the partial
6447             --  view, the completion does not derive them anew.
6448
6449             if not Is_Tagged_Type (Parent_Type) then
6450
6451                --  If the parent is itself derived from another private type,
6452                --  installing the private declarations has not affected its
6453                --  privacy status, so use its own full view explicitly.
6454
6455                if Is_Private_Type (Parent_Type) then
6456                   Build_Derived_Record_Type
6457                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
6458                else
6459                   Build_Derived_Record_Type
6460                     (Full_Decl, Parent_Type, Full_Der, False);
6461                end if;
6462
6463             else
6464                --  If full view of parent is tagged, the completion inherits
6465                --  the proper primitive operations.
6466
6467                Set_Defining_Identifier (Full_Decl, Full_Der);
6468                Build_Derived_Record_Type
6469                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
6470             end if;
6471
6472             --  The full declaration has been introduced into the tree and
6473             --  processed in the step above. It should not be analyzed again
6474             --  (when encountered later in the current list of declarations)
6475             --  to prevent spurious name conflicts. The full entity remains
6476             --  invisible.
6477
6478             Set_Analyzed (Full_Decl);
6479
6480             if Swapped then
6481                Uninstall_Declarations (Par_Scope);
6482
6483                if In_Open_Scopes (Par_Scope) then
6484                   Install_Visible_Declarations (Par_Scope);
6485                end if;
6486             end if;
6487
6488             Der_Base := Base_Type (Derived_Type);
6489             Set_Full_View (Derived_Type, Full_Der);
6490             Set_Full_View (Der_Base, Base_Type (Full_Der));
6491
6492             --  Copy the discriminant list from full view to the partial views
6493             --  (base type and its subtype). Gigi requires that the partial and
6494             --  full views have the same discriminants.
6495
6496             --  Note that since the partial view is pointing to discriminants
6497             --  in the full view, their scope will be that of the full view.
6498             --  This might cause some front end problems and need adjustment???
6499
6500             Discr := First_Discriminant (Base_Type (Full_Der));
6501             Set_First_Entity (Der_Base, Discr);
6502
6503             loop
6504                Last_Discr := Discr;
6505                Next_Discriminant (Discr);
6506                exit when No (Discr);
6507             end loop;
6508
6509             Set_Last_Entity (Der_Base, Last_Discr);
6510
6511             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
6512             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
6513             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
6514
6515          else
6516             --  If this is a completion, the derived type stays private and
6517             --  there is no need to create a further full view, except in the
6518             --  unusual case when the derivation is nested within a child unit,
6519             --  see below.
6520
6521             null;
6522          end if;
6523
6524       elsif Present (Full_View (Parent_Type))
6525         and then  Has_Discriminants (Full_View (Parent_Type))
6526       then
6527          if Has_Unknown_Discriminants (Parent_Type)
6528            and then Nkind (Subtype_Indication (Type_Definition (N))) =
6529                                                          N_Subtype_Indication
6530          then
6531             Error_Msg_N
6532               ("cannot constrain type with unknown discriminants",
6533                Subtype_Indication (Type_Definition (N)));
6534             return;
6535          end if;
6536
6537          --  If full view of parent is a record type, build full view as a
6538          --  derivation from the parent's full view. Partial view remains
6539          --  private. For code generation and linking, the full view must have
6540          --  the same public status as the partial one. This full view is only
6541          --  needed if the parent type is in an enclosing scope, so that the
6542          --  full view may actually become visible, e.g. in a child unit. This
6543          --  is both more efficient, and avoids order of freezing problems with
6544          --  the added entities.
6545
6546          if not Is_Private_Type (Full_View (Parent_Type))
6547            and then (In_Open_Scopes (Scope (Parent_Type)))
6548          then
6549             Full_Der :=
6550               Make_Defining_Identifier (Sloc (Derived_Type),
6551                 Chars => Chars (Derived_Type));
6552
6553             Set_Is_Itype (Full_Der);
6554             Set_Has_Private_Declaration (Full_Der);
6555             Set_Has_Private_Declaration (Derived_Type);
6556             Set_Associated_Node_For_Itype (Full_Der, N);
6557             Set_Parent (Full_Der, Parent (Derived_Type));
6558             Set_Full_View (Derived_Type, Full_Der);
6559             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6560             Full_P := Full_View (Parent_Type);
6561             Exchange_Declarations (Parent_Type);
6562             Copy_And_Build;
6563             Exchange_Declarations (Full_P);
6564
6565          else
6566             Build_Derived_Record_Type
6567               (N, Full_View (Parent_Type), Derived_Type,
6568                Derive_Subps => False);
6569
6570             --  Except in the context of the full view of the parent, there
6571             --  are no non-extension aggregates for the derived type.
6572
6573             Set_Has_Private_Ancestor (Derived_Type);
6574          end if;
6575
6576          --  In any case, the primitive operations are inherited from the
6577          --  parent type, not from the internal full view.
6578
6579          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6580
6581          if Derive_Subps then
6582             Derive_Subprograms (Parent_Type, Derived_Type);
6583          end if;
6584
6585       else
6586          --  Untagged type, No discriminants on either view
6587
6588          if Nkind (Subtype_Indication (Type_Definition (N))) =
6589                                                    N_Subtype_Indication
6590          then
6591             Error_Msg_N
6592               ("illegal constraint on type without discriminants", N);
6593          end if;
6594
6595          if Present (Discriminant_Specifications (N))
6596            and then Present (Full_View (Parent_Type))
6597            and then not Is_Tagged_Type (Full_View (Parent_Type))
6598          then
6599             Error_Msg_N ("cannot add discriminants to untagged type", N);
6600          end if;
6601
6602          Set_Stored_Constraint (Derived_Type, No_Elist);
6603          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6604          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6605          Set_Has_Controlled_Component
6606                                (Derived_Type, Has_Controlled_Component
6607                                                              (Parent_Type));
6608
6609          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6610
6611          if not Is_Controlled  (Parent_Type) then
6612             Set_Finalize_Storage_Only
6613               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6614          end if;
6615
6616          --  Construct the implicit full view by deriving from full view of the
6617          --  parent type. In order to get proper visibility, we install the
6618          --  parent scope and its declarations.
6619
6620          --  ??? If the parent is untagged private and its completion is
6621          --  tagged, this mechanism will not work because we cannot derive from
6622          --  the tagged full view unless we have an extension.
6623
6624          if Present (Full_View (Parent_Type))
6625            and then not Is_Tagged_Type (Full_View (Parent_Type))
6626            and then not Is_Completion
6627          then
6628             Full_Der :=
6629               Make_Defining_Identifier
6630                 (Sloc (Derived_Type), Chars (Derived_Type));
6631             Set_Is_Itype (Full_Der);
6632             Set_Has_Private_Declaration (Full_Der);
6633             Set_Has_Private_Declaration (Derived_Type);
6634             Set_Associated_Node_For_Itype (Full_Der, N);
6635             Set_Parent (Full_Der, Parent (Derived_Type));
6636             Set_Full_View (Derived_Type, Full_Der);
6637
6638             if not In_Open_Scopes (Par_Scope) then
6639                Install_Private_Declarations (Par_Scope);
6640                Install_Visible_Declarations (Par_Scope);
6641                Copy_And_Build;
6642                Uninstall_Declarations (Par_Scope);
6643
6644             --  If parent scope is open and in another unit, and parent has a
6645             --  completion, then the derivation is taking place in the visible
6646             --  part of a child unit. In that case retrieve the full view of
6647             --  the parent momentarily.
6648
6649             elsif not In_Same_Source_Unit (N, Parent_Type) then
6650                Full_P := Full_View (Parent_Type);
6651                Exchange_Declarations (Parent_Type);
6652                Copy_And_Build;
6653                Exchange_Declarations (Full_P);
6654
6655             --  Otherwise it is a local derivation
6656
6657             else
6658                Copy_And_Build;
6659             end if;
6660
6661             Set_Scope                (Full_Der, Current_Scope);
6662             Set_Is_First_Subtype     (Full_Der,
6663                                        Is_First_Subtype (Derived_Type));
6664             Set_Has_Size_Clause      (Full_Der, False);
6665             Set_Has_Alignment_Clause (Full_Der, False);
6666             Set_Next_Entity          (Full_Der, Empty);
6667             Set_Has_Delayed_Freeze   (Full_Der);
6668             Set_Is_Frozen            (Full_Der, False);
6669             Set_Freeze_Node          (Full_Der, Empty);
6670             Set_Depends_On_Private   (Full_Der,
6671                                        Has_Private_Component (Full_Der));
6672             Set_Public_Status        (Full_Der);
6673          end if;
6674       end if;
6675
6676       Set_Has_Unknown_Discriminants (Derived_Type,
6677         Has_Unknown_Discriminants (Parent_Type));
6678
6679       if Is_Private_Type (Derived_Type) then
6680          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6681       end if;
6682
6683       if Is_Private_Type (Parent_Type)
6684         and then Base_Type (Parent_Type) = Parent_Type
6685         and then In_Open_Scopes (Scope (Parent_Type))
6686       then
6687          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6688
6689          --  Check for unusual case where a type completed by a private
6690          --  derivation occurs within a package nested in a child unit, and
6691          --  the parent is declared in an ancestor.
6692
6693          if Is_Child_Unit (Scope (Current_Scope))
6694            and then Is_Completion
6695            and then In_Private_Part (Current_Scope)
6696            and then Scope (Parent_Type) /= Current_Scope
6697
6698            --  Note that if the parent has a completion in the private part,
6699            --  (which is itself a derivation from some other private type)
6700            --  it is that completion that is visible, there is no full view
6701            --  available, and no special processing is needed.
6702
6703            and then Present (Full_View (Parent_Type))
6704          then
6705             --  In this case, the full view of the parent type will become
6706             --  visible in the body of the enclosing child, and only then will
6707             --  the current type be possibly non-private. We build an
6708             --  underlying full view that will be installed when the enclosing
6709             --  child body is compiled.
6710
6711             Full_Der :=
6712               Make_Defining_Identifier
6713                 (Sloc (Derived_Type), Chars (Derived_Type));
6714             Set_Is_Itype (Full_Der);
6715             Build_Itype_Reference (Full_Der, N);
6716
6717             --  The full view will be used to swap entities on entry/exit to
6718             --  the body, and must appear in the entity list for the package.
6719
6720             Append_Entity (Full_Der, Scope (Derived_Type));
6721             Set_Has_Private_Declaration (Full_Der);
6722             Set_Has_Private_Declaration (Derived_Type);
6723             Set_Associated_Node_For_Itype (Full_Der, N);
6724             Set_Parent (Full_Der, Parent (Derived_Type));
6725             Full_P := Full_View (Parent_Type);
6726             Exchange_Declarations (Parent_Type);
6727             Copy_And_Build;
6728             Exchange_Declarations (Full_P);
6729             Set_Underlying_Full_View (Derived_Type, Full_Der);
6730          end if;
6731       end if;
6732    end Build_Derived_Private_Type;
6733
6734    -------------------------------
6735    -- Build_Derived_Record_Type --
6736    -------------------------------
6737
6738    --  1. INTRODUCTION
6739
6740    --  Ideally we would like to use the same model of type derivation for
6741    --  tagged and untagged record types. Unfortunately this is not quite
6742    --  possible because the semantics of representation clauses is different
6743    --  for tagged and untagged records under inheritance. Consider the
6744    --  following:
6745
6746    --     type R (...) is [tagged] record ... end record;
6747    --     type T (...) is new R (...) [with ...];
6748
6749    --  The representation clauses for T can specify a completely different
6750    --  record layout from R's. Hence the same component can be placed in two
6751    --  very different positions in objects of type T and R. If R and T are
6752    --  tagged types, representation clauses for T can only specify the layout
6753    --  of non inherited components, thus components that are common in R and T
6754    --  have the same position in objects of type R and T.
6755
6756    --  This has two implications. The first is that the entire tree for R's
6757    --  declaration needs to be copied for T in the untagged case, so that T
6758    --  can be viewed as a record type of its own with its own representation
6759    --  clauses. The second implication is the way we handle discriminants.
6760    --  Specifically, in the untagged case we need a way to communicate to Gigi
6761    --  what are the real discriminants in the record, while for the semantics
6762    --  we need to consider those introduced by the user to rename the
6763    --  discriminants in the parent type. This is handled by introducing the
6764    --  notion of stored discriminants. See below for more.
6765
6766    --  Fortunately the way regular components are inherited can be handled in
6767    --  the same way in tagged and untagged types.
6768
6769    --  To complicate things a bit more the private view of a private extension
6770    --  cannot be handled in the same way as the full view (for one thing the
6771    --  semantic rules are somewhat different). We will explain what differs
6772    --  below.
6773
6774    --  2. DISCRIMINANTS UNDER INHERITANCE
6775
6776    --  The semantic rules governing the discriminants of derived types are
6777    --  quite subtle.
6778
6779    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6780    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6781
6782    --  If parent type has discriminants, then the discriminants that are
6783    --  declared in the derived type are [3.4 (11)]:
6784
6785    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6786    --    there is one;
6787
6788    --  o Otherwise, each discriminant of the parent type (implicitly declared
6789    --    in the same order with the same specifications). In this case, the
6790    --    discriminants are said to be "inherited", or if unknown in the parent
6791    --    are also unknown in the derived type.
6792
6793    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6794
6795    --  o The parent subtype shall be constrained;
6796
6797    --  o If the parent type is not a tagged type, then each discriminant of
6798    --    the derived type shall be used in the constraint defining a parent
6799    --    subtype. [Implementation note: This ensures that the new discriminant
6800    --    can share storage with an existing discriminant.]
6801
6802    --  For the derived type each discriminant of the parent type is either
6803    --  inherited, constrained to equal some new discriminant of the derived
6804    --  type, or constrained to the value of an expression.
6805
6806    --  When inherited or constrained to equal some new discriminant, the
6807    --  parent discriminant and the discriminant of the derived type are said
6808    --  to "correspond".
6809
6810    --  If a discriminant of the parent type is constrained to a specific value
6811    --  in the derived type definition, then the discriminant is said to be
6812    --  "specified" by that derived type definition.
6813
6814    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6815
6816    --  We have spoken about stored discriminants in point 1 (introduction)
6817    --  above. There are two sort of stored discriminants: implicit and
6818    --  explicit. As long as the derived type inherits the same discriminants as
6819    --  the root record type, stored discriminants are the same as regular
6820    --  discriminants, and are said to be implicit. However, if any discriminant
6821    --  in the root type was renamed in the derived type, then the derived
6822    --  type will contain explicit stored discriminants. Explicit stored
6823    --  discriminants are discriminants in addition to the semantically visible
6824    --  discriminants defined for the derived type. Stored discriminants are
6825    --  used by Gigi to figure out what are the physical discriminants in
6826    --  objects of the derived type (see precise definition in einfo.ads).
6827    --  As an example, consider the following:
6828
6829    --           type R  (D1, D2, D3 : Int) is record ... end record;
6830    --           type T1 is new R;
6831    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6832    --           type T3 is new T2;
6833    --           type T4 (Y : Int) is new T3 (Y, 99);
6834
6835    --  The following table summarizes the discriminants and stored
6836    --  discriminants in R and T1 through T4.
6837
6838    --   Type      Discrim     Stored Discrim  Comment
6839    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6840    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6841    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6842    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6843    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6844
6845    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6846    --  find the corresponding discriminant in the parent type, while
6847    --  Original_Record_Component (abbreviated ORC below), the actual physical
6848    --  component that is renamed. Finally the field Is_Completely_Hidden
6849    --  (abbreviated ICH below) is set for all explicit stored discriminants
6850    --  (see einfo.ads for more info). For the above example this gives:
6851
6852    --                 Discrim     CD        ORC     ICH
6853    --                 ^^^^^^^     ^^        ^^^     ^^^
6854    --                 D1 in R    empty     itself    no
6855    --                 D2 in R    empty     itself    no
6856    --                 D3 in R    empty     itself    no
6857
6858    --                 D1 in T1  D1 in R    itself    no
6859    --                 D2 in T1  D2 in R    itself    no
6860    --                 D3 in T1  D3 in R    itself    no
6861
6862    --                 X1 in T2  D3 in T1  D3 in T2   no
6863    --                 X2 in T2  D1 in T1  D1 in T2   no
6864    --                 D1 in T2   empty    itself    yes
6865    --                 D2 in T2   empty    itself    yes
6866    --                 D3 in T2   empty    itself    yes
6867
6868    --                 X1 in T3  X1 in T2  D3 in T3   no
6869    --                 X2 in T3  X2 in T2  D1 in T3   no
6870    --                 D1 in T3   empty    itself    yes
6871    --                 D2 in T3   empty    itself    yes
6872    --                 D3 in T3   empty    itself    yes
6873
6874    --                 Y  in T4  X1 in T3  D3 in T3   no
6875    --                 D1 in T3   empty    itself    yes
6876    --                 D2 in T3   empty    itself    yes
6877    --                 D3 in T3   empty    itself    yes
6878
6879    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6880
6881    --  Type derivation for tagged types is fairly straightforward. If no
6882    --  discriminants are specified by the derived type, these are inherited
6883    --  from the parent. No explicit stored discriminants are ever necessary.
6884    --  The only manipulation that is done to the tree is that of adding a
6885    --  _parent field with parent type and constrained to the same constraint
6886    --  specified for the parent in the derived type definition. For instance:
6887
6888    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6889    --           type T1 is new R with null record;
6890    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6891
6892    --  are changed into:
6893
6894    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6895    --              _parent : R (D1, D2, D3);
6896    --           end record;
6897
6898    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6899    --              _parent : T1 (X2, 88, X1);
6900    --           end record;
6901
6902    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6903    --  ORC and ICH fields are:
6904
6905    --                 Discrim     CD        ORC     ICH
6906    --                 ^^^^^^^     ^^        ^^^     ^^^
6907    --                 D1 in R    empty     itself    no
6908    --                 D2 in R    empty     itself    no
6909    --                 D3 in R    empty     itself    no
6910
6911    --                 D1 in T1  D1 in R    D1 in R   no
6912    --                 D2 in T1  D2 in R    D2 in R   no
6913    --                 D3 in T1  D3 in R    D3 in R   no
6914
6915    --                 X1 in T2  D3 in T1   D3 in R   no
6916    --                 X2 in T2  D1 in T1   D1 in R   no
6917
6918    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6919    --
6920    --  Regardless of whether we dealing with a tagged or untagged type
6921    --  we will transform all derived type declarations of the form
6922    --
6923    --               type T is new R (...) [with ...];
6924    --  or
6925    --               subtype S is R (...);
6926    --               type T is new S [with ...];
6927    --  into
6928    --               type BT is new R [with ...];
6929    --               subtype T is BT (...);
6930    --
6931    --  That is, the base derived type is constrained only if it has no
6932    --  discriminants. The reason for doing this is that GNAT's semantic model
6933    --  assumes that a base type with discriminants is unconstrained.
6934    --
6935    --  Note that, strictly speaking, the above transformation is not always
6936    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6937    --
6938    --       procedure B34011A is
6939    --          type REC (D : integer := 0) is record
6940    --             I : Integer;
6941    --          end record;
6942
6943    --          package P is
6944    --             type T6 is new Rec;
6945    --             function F return T6;
6946    --          end P;
6947
6948    --          use P;
6949    --          package Q6 is
6950    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6951    --          end Q6;
6952    --
6953    --  The definition of Q6.U is illegal. However transforming Q6.U into
6954
6955    --             type BaseU is new T6;
6956    --             subtype U is BaseU (Q6.F.I)
6957
6958    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6959    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6960    --  the transformation described above.
6961
6962    --  There is another instance where the above transformation is incorrect.
6963    --  Consider:
6964
6965    --          package Pack is
6966    --             type Base (D : Integer) is tagged null record;
6967    --             procedure P (X : Base);
6968
6969    --             type Der is new Base (2) with null record;
6970    --             procedure P (X : Der);
6971    --          end Pack;
6972
6973    --  Then the above transformation turns this into
6974
6975    --             type Der_Base is new Base with null record;
6976    --             --  procedure P (X : Base) is implicitly inherited here
6977    --             --  as procedure P (X : Der_Base).
6978
6979    --             subtype Der is Der_Base (2);
6980    --             procedure P (X : Der);
6981    --             --  The overriding of P (X : Der_Base) is illegal since we
6982    --             --  have a parameter conformance problem.
6983
6984    --  To get around this problem, after having semantically processed Der_Base
6985    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6986    --  Discriminant_Constraint from Der so that when parameter conformance is
6987    --  checked when P is overridden, no semantic errors are flagged.
6988
6989    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6990
6991    --  Regardless of whether we are dealing with a tagged or untagged type
6992    --  we will transform all derived type declarations of the form
6993
6994    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6995    --               type T is new R [with ...];
6996    --  into
6997    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6998
6999    --  The reason for such transformation is that it allows us to implement a
7000    --  very clean form of component inheritance as explained below.
7001
7002    --  Note that this transformation is not achieved by direct tree rewriting
7003    --  and manipulation, but rather by redoing the semantic actions that the
7004    --  above transformation will entail. This is done directly in routine
7005    --  Inherit_Components.
7006
7007    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
7008
7009    --  In both tagged and untagged derived types, regular non discriminant
7010    --  components are inherited in the derived type from the parent type. In
7011    --  the absence of discriminants component, inheritance is straightforward
7012    --  as components can simply be copied from the parent.
7013
7014    --  If the parent has discriminants, inheriting components constrained with
7015    --  these discriminants requires caution. Consider the following example:
7016
7017    --      type R  (D1, D2 : Positive) is [tagged] record
7018    --         S : String (D1 .. D2);
7019    --      end record;
7020
7021    --      type T1                is new R        [with null record];
7022    --      type T2 (X : positive) is new R (1, X) [with null record];
7023
7024    --  As explained in 6. above, T1 is rewritten as
7025    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
7026    --  which makes the treatment for T1 and T2 identical.
7027
7028    --  What we want when inheriting S, is that references to D1 and D2 in R are
7029    --  replaced with references to their correct constraints, i.e. D1 and D2 in
7030    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
7031    --  with either discriminant references in the derived type or expressions.
7032    --  This replacement is achieved as follows: before inheriting R's
7033    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
7034    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
7035    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
7036    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
7037    --  by String (1 .. X).
7038
7039    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
7040
7041    --  We explain here the rules governing private type extensions relevant to
7042    --  type derivation. These rules are explained on the following example:
7043
7044    --      type D [(...)] is new A [(...)] with private;      <-- partial view
7045    --      type D [(...)] is new P [(...)] with null record;  <-- full view
7046
7047    --  Type A is called the ancestor subtype of the private extension.
7048    --  Type P is the parent type of the full view of the private extension. It
7049    --  must be A or a type derived from A.
7050
7051    --  The rules concerning the discriminants of private type extensions are
7052    --  [7.3(10-13)]:
7053
7054    --  o If a private extension inherits known discriminants from the ancestor
7055    --    subtype, then the full view shall also inherit its discriminants from
7056    --    the ancestor subtype and the parent subtype of the full view shall be
7057    --    constrained if and only if the ancestor subtype is constrained.
7058
7059    --  o If a partial view has unknown discriminants, then the full view may
7060    --    define a definite or an indefinite subtype, with or without
7061    --    discriminants.
7062
7063    --  o If a partial view has neither known nor unknown discriminants, then
7064    --    the full view shall define a definite subtype.
7065
7066    --  o If the ancestor subtype of a private extension has constrained
7067    --    discriminants, then the parent subtype of the full view shall impose a
7068    --    statically matching constraint on those discriminants.
7069
7070    --  This means that only the following forms of private extensions are
7071    --  allowed:
7072
7073    --      type D is new A with private;      <-- partial view
7074    --      type D is new P with null record;  <-- full view
7075
7076    --  If A has no discriminants than P has no discriminants, otherwise P must
7077    --  inherit A's discriminants.
7078
7079    --      type D is new A (...) with private;      <-- partial view
7080    --      type D is new P (:::) with null record;  <-- full view
7081
7082    --  P must inherit A's discriminants and (...) and (:::) must statically
7083    --  match.
7084
7085    --      subtype A is R (...);
7086    --      type D is new A with private;      <-- partial view
7087    --      type D is new P with null record;  <-- full view
7088
7089    --  P must have inherited R's discriminants and must be derived from A or
7090    --  any of its subtypes.
7091
7092    --      type D (..) is new A with private;              <-- partial view
7093    --      type D (..) is new P [(:::)] with null record;  <-- full view
7094
7095    --  No specific constraints on P's discriminants or constraint (:::).
7096    --  Note that A can be unconstrained, but the parent subtype P must either
7097    --  be constrained or (:::) must be present.
7098
7099    --      type D (..) is new A [(...)] with private;      <-- partial view
7100    --      type D (..) is new P [(:::)] with null record;  <-- full view
7101
7102    --  P's constraints on A's discriminants must statically match those
7103    --  imposed by (...).
7104
7105    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
7106
7107    --  The full view of a private extension is handled exactly as described
7108    --  above. The model chose for the private view of a private extension is
7109    --  the same for what concerns discriminants (i.e. they receive the same
7110    --  treatment as in the tagged case). However, the private view of the
7111    --  private extension always inherits the components of the parent base,
7112    --  without replacing any discriminant reference. Strictly speaking this is
7113    --  incorrect. However, Gigi never uses this view to generate code so this
7114    --  is a purely semantic issue. In theory, a set of transformations similar
7115    --  to those given in 5. and 6. above could be applied to private views of
7116    --  private extensions to have the same model of component inheritance as
7117    --  for non private extensions. However, this is not done because it would
7118    --  further complicate private type processing. Semantically speaking, this
7119    --  leaves us in an uncomfortable situation. As an example consider:
7120
7121    --          package Pack is
7122    --             type R (D : integer) is tagged record
7123    --                S : String (1 .. D);
7124    --             end record;
7125    --             procedure P (X : R);
7126    --             type T is new R (1) with private;
7127    --          private
7128    --             type T is new R (1) with null record;
7129    --          end;
7130
7131    --  This is transformed into:
7132
7133    --          package Pack is
7134    --             type R (D : integer) is tagged record
7135    --                S : String (1 .. D);
7136    --             end record;
7137    --             procedure P (X : R);
7138    --             type T is new R (1) with private;
7139    --          private
7140    --             type BaseT is new R with null record;
7141    --             subtype  T is BaseT (1);
7142    --          end;
7143
7144    --  (strictly speaking the above is incorrect Ada)
7145
7146    --  From the semantic standpoint the private view of private extension T
7147    --  should be flagged as constrained since one can clearly have
7148    --
7149    --             Obj : T;
7150    --
7151    --  in a unit withing Pack. However, when deriving subprograms for the
7152    --  private view of private extension T, T must be seen as unconstrained
7153    --  since T has discriminants (this is a constraint of the current
7154    --  subprogram derivation model). Thus, when processing the private view of
7155    --  a private extension such as T, we first mark T as unconstrained, we
7156    --  process it, we perform program derivation and just before returning from
7157    --  Build_Derived_Record_Type we mark T as constrained.
7158
7159    --  ??? Are there are other uncomfortable cases that we will have to
7160    --      deal with.
7161
7162    --  10. RECORD_TYPE_WITH_PRIVATE complications
7163
7164    --  Types that are derived from a visible record type and have a private
7165    --  extension present other peculiarities. They behave mostly like private
7166    --  types, but if they have primitive operations defined, these will not
7167    --  have the proper signatures for further inheritance, because other
7168    --  primitive operations will use the implicit base that we define for
7169    --  private derivations below. This affect subprogram inheritance (see
7170    --  Derive_Subprograms for details). We also derive the implicit base from
7171    --  the base type of the full view, so that the implicit base is a record
7172    --  type and not another private type, This avoids infinite loops.
7173
7174    procedure Build_Derived_Record_Type
7175      (N            : Node_Id;
7176       Parent_Type  : Entity_Id;
7177       Derived_Type : Entity_Id;
7178       Derive_Subps : Boolean := True)
7179    is
7180       Discriminant_Specs : constant Boolean :=
7181                              Present (Discriminant_Specifications (N));
7182       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
7183       Loc                : constant Source_Ptr := Sloc (N);
7184       Private_Extension  : constant Boolean :=
7185                              Nkind (N) = N_Private_Extension_Declaration;
7186       Assoc_List         : Elist_Id;
7187       Constraint_Present : Boolean;
7188       Constrs            : Elist_Id;
7189       Discrim            : Entity_Id;
7190       Indic              : Node_Id;
7191       Inherit_Discrims   : Boolean := False;
7192       Last_Discrim       : Entity_Id;
7193       New_Base           : Entity_Id;
7194       New_Decl           : Node_Id;
7195       New_Discrs         : Elist_Id;
7196       New_Indic          : Node_Id;
7197       Parent_Base        : Entity_Id;
7198       Save_Etype         : Entity_Id;
7199       Save_Discr_Constr  : Elist_Id;
7200       Save_Next_Entity   : Entity_Id;
7201       Type_Def           : Node_Id;
7202
7203       Discs : Elist_Id := New_Elmt_List;
7204       --  An empty Discs list means that there were no constraints in the
7205       --  subtype indication or that there was an error processing it.
7206
7207    begin
7208       if Ekind (Parent_Type) = E_Record_Type_With_Private
7209         and then Present (Full_View (Parent_Type))
7210         and then Has_Discriminants (Parent_Type)
7211       then
7212          Parent_Base := Base_Type (Full_View (Parent_Type));
7213       else
7214          Parent_Base := Base_Type (Parent_Type);
7215       end if;
7216
7217       --  AI05-0115 : if this is a derivation from a private type in some
7218       --  other scope that may lead to invisible components for the derived
7219       --  type, mark it accordingly.
7220
7221       if Is_Private_Type (Parent_Type) then
7222          if Scope (Parent_Type) = Scope (Derived_Type) then
7223             null;
7224
7225          elsif In_Open_Scopes (Scope (Parent_Type))
7226            and then In_Private_Part (Scope (Parent_Type))
7227          then
7228             null;
7229
7230          else
7231             Set_Has_Private_Ancestor (Derived_Type);
7232          end if;
7233
7234       else
7235          Set_Has_Private_Ancestor
7236            (Derived_Type, Has_Private_Ancestor (Parent_Type));
7237       end if;
7238
7239       --  Before we start the previously documented transformations, here is
7240       --  little fix for size and alignment of tagged types. Normally when we
7241       --  derive type D from type P, we copy the size and alignment of P as the
7242       --  default for D, and in the absence of explicit representation clauses
7243       --  for D, the size and alignment are indeed the same as the parent.
7244
7245       --  But this is wrong for tagged types, since fields may be added, and
7246       --  the default size may need to be larger, and the default alignment may
7247       --  need to be larger.
7248
7249       --  We therefore reset the size and alignment fields in the tagged case.
7250       --  Note that the size and alignment will in any case be at least as
7251       --  large as the parent type (since the derived type has a copy of the
7252       --  parent type in the _parent field)
7253
7254       --  The type is also marked as being tagged here, which is needed when
7255       --  processing components with a self-referential anonymous access type
7256       --  in the call to Check_Anonymous_Access_Components below. Note that
7257       --  this flag is also set later on for completeness.
7258
7259       if Is_Tagged then
7260          Set_Is_Tagged_Type (Derived_Type);
7261          Init_Size_Align    (Derived_Type);
7262       end if;
7263
7264       --  STEP 0a: figure out what kind of derived type declaration we have
7265
7266       if Private_Extension then
7267          Type_Def := N;
7268          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
7269
7270       else
7271          Type_Def := Type_Definition (N);
7272
7273          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7274          --  Parent_Base can be a private type or private extension. However,
7275          --  for tagged types with an extension the newly added fields are
7276          --  visible and hence the Derived_Type is always an E_Record_Type.
7277          --  (except that the parent may have its own private fields).
7278          --  For untagged types we preserve the Ekind of the Parent_Base.
7279
7280          if Present (Record_Extension_Part (Type_Def)) then
7281             Set_Ekind (Derived_Type, E_Record_Type);
7282
7283             --  Create internal access types for components with anonymous
7284             --  access types.
7285
7286             if Ada_Version >= Ada_2005 then
7287                Check_Anonymous_Access_Components
7288                  (N, Derived_Type, Derived_Type,
7289                    Component_List (Record_Extension_Part (Type_Def)));
7290             end if;
7291
7292          else
7293             Set_Ekind (Derived_Type, Ekind (Parent_Base));
7294          end if;
7295       end if;
7296
7297       --  Indic can either be an N_Identifier if the subtype indication
7298       --  contains no constraint or an N_Subtype_Indication if the subtype
7299       --  indication has a constraint.
7300
7301       Indic := Subtype_Indication (Type_Def);
7302       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
7303
7304       --  Check that the type has visible discriminants. The type may be
7305       --  a private type with unknown discriminants whose full view has
7306       --  discriminants which are invisible.
7307
7308       if Constraint_Present then
7309          if not Has_Discriminants (Parent_Base)
7310            or else
7311              (Has_Unknown_Discriminants (Parent_Base)
7312                 and then Is_Private_Type (Parent_Base))
7313          then
7314             Error_Msg_N
7315               ("invalid constraint: type has no discriminant",
7316                  Constraint (Indic));
7317
7318             Constraint_Present := False;
7319             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7320
7321          elsif Is_Constrained (Parent_Type) then
7322             Error_Msg_N
7323                ("invalid constraint: parent type is already constrained",
7324                   Constraint (Indic));
7325
7326             Constraint_Present := False;
7327             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7328          end if;
7329       end if;
7330
7331       --  STEP 0b: If needed, apply transformation given in point 5. above
7332
7333       if not Private_Extension
7334         and then Has_Discriminants (Parent_Type)
7335         and then not Discriminant_Specs
7336         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
7337       then
7338          --  First, we must analyze the constraint (see comment in point 5.)
7339          --  The constraint may come from the subtype indication of the full
7340          --  declaration.
7341
7342          if Constraint_Present then
7343             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
7344
7345          --  If there is no explicit constraint, there might be one that is
7346          --  inherited from a constrained parent type. In that case verify that
7347          --  it conforms to the constraint in the partial view. In perverse
7348          --  cases the parent subtypes of the partial and full view can have
7349          --  different constraints.
7350
7351          elsif Present (Stored_Constraint (Parent_Type)) then
7352             New_Discrs := Stored_Constraint (Parent_Type);
7353
7354          else
7355             New_Discrs := No_Elist;
7356          end if;
7357
7358          if Has_Discriminants (Derived_Type)
7359            and then Has_Private_Declaration (Derived_Type)
7360            and then Present (Discriminant_Constraint (Derived_Type))
7361            and then Present (New_Discrs)
7362          then
7363             --  Verify that constraints of the full view statically match
7364             --  those given in the partial view.
7365
7366             declare
7367                C1, C2 : Elmt_Id;
7368
7369             begin
7370                C1 := First_Elmt (New_Discrs);
7371                C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
7372                while Present (C1) and then Present (C2) loop
7373                   if Fully_Conformant_Expressions (Node (C1), Node (C2))
7374                     or else
7375                       (Is_OK_Static_Expression (Node (C1))
7376                         and then Is_OK_Static_Expression (Node (C2))
7377                         and then
7378                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
7379                   then
7380                      null;
7381
7382                   else
7383                      if Constraint_Present then
7384                         Error_Msg_N
7385                           ("constraint not conformant to previous declaration",
7386                            Node (C1));
7387                      else
7388                         Error_Msg_N
7389                           ("constraint of full view is incompatible "
7390                            & "with partial view", N);
7391                      end if;
7392                   end if;
7393
7394                   Next_Elmt (C1);
7395                   Next_Elmt (C2);
7396                end loop;
7397             end;
7398          end if;
7399
7400          --  Insert and analyze the declaration for the unconstrained base type
7401
7402          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
7403
7404          New_Decl :=
7405            Make_Full_Type_Declaration (Loc,
7406               Defining_Identifier => New_Base,
7407               Type_Definition     =>
7408                 Make_Derived_Type_Definition (Loc,
7409                   Abstract_Present      => Abstract_Present (Type_Def),
7410                   Limited_Present       => Limited_Present (Type_Def),
7411                   Subtype_Indication    =>
7412                     New_Occurrence_Of (Parent_Base, Loc),
7413                   Record_Extension_Part =>
7414                     Relocate_Node (Record_Extension_Part (Type_Def)),
7415                   Interface_List        => Interface_List (Type_Def)));
7416
7417          Set_Parent (New_Decl, Parent (N));
7418          Mark_Rewrite_Insertion (New_Decl);
7419          Insert_Before (N, New_Decl);
7420
7421          --  In the extension case, make sure ancestor is frozen appropriately
7422          --  (see also non-discriminated case below).
7423
7424          if Present (Record_Extension_Part (Type_Def))
7425            or else Is_Interface (Parent_Base)
7426          then
7427             Freeze_Before (New_Decl, Parent_Type);
7428          end if;
7429
7430          --  Note that this call passes False for the Derive_Subps parameter
7431          --  because subprogram derivation is deferred until after creating
7432          --  the subtype (see below).
7433
7434          Build_Derived_Type
7435            (New_Decl, Parent_Base, New_Base,
7436             Is_Completion => True, Derive_Subps => False);
7437
7438          --  ??? This needs re-examination to determine whether the
7439          --  above call can simply be replaced by a call to Analyze.
7440
7441          Set_Analyzed (New_Decl);
7442
7443          --  Insert and analyze the declaration for the constrained subtype
7444
7445          if Constraint_Present then
7446             New_Indic :=
7447               Make_Subtype_Indication (Loc,
7448                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7449                 Constraint   => Relocate_Node (Constraint (Indic)));
7450
7451          else
7452             declare
7453                Constr_List : constant List_Id := New_List;
7454                C           : Elmt_Id;
7455                Expr        : Node_Id;
7456
7457             begin
7458                C := First_Elmt (Discriminant_Constraint (Parent_Type));
7459                while Present (C) loop
7460                   Expr := Node (C);
7461
7462                   --  It is safe here to call New_Copy_Tree since
7463                   --  Force_Evaluation was called on each constraint in
7464                   --  Build_Discriminant_Constraints.
7465
7466                   Append (New_Copy_Tree (Expr), To => Constr_List);
7467
7468                   Next_Elmt (C);
7469                end loop;
7470
7471                New_Indic :=
7472                  Make_Subtype_Indication (Loc,
7473                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7474                    Constraint   =>
7475                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
7476             end;
7477          end if;
7478
7479          Rewrite (N,
7480            Make_Subtype_Declaration (Loc,
7481              Defining_Identifier => Derived_Type,
7482              Subtype_Indication  => New_Indic));
7483
7484          Analyze (N);
7485
7486          --  Derivation of subprograms must be delayed until the full subtype
7487          --  has been established, to ensure proper overriding of subprograms
7488          --  inherited by full types. If the derivations occurred as part of
7489          --  the call to Build_Derived_Type above, then the check for type
7490          --  conformance would fail because earlier primitive subprograms
7491          --  could still refer to the full type prior the change to the new
7492          --  subtype and hence would not match the new base type created here.
7493          --  Subprograms are not derived, however, when Derive_Subps is False
7494          --  (since otherwise there could be redundant derivations).
7495
7496          if Derive_Subps then
7497             Derive_Subprograms (Parent_Type, Derived_Type);
7498          end if;
7499
7500          --  For tagged types the Discriminant_Constraint of the new base itype
7501          --  is inherited from the first subtype so that no subtype conformance
7502          --  problem arise when the first subtype overrides primitive
7503          --  operations inherited by the implicit base type.
7504
7505          if Is_Tagged then
7506             Set_Discriminant_Constraint
7507               (New_Base, Discriminant_Constraint (Derived_Type));
7508          end if;
7509
7510          return;
7511       end if;
7512
7513       --  If we get here Derived_Type will have no discriminants or it will be
7514       --  a discriminated unconstrained base type.
7515
7516       --  STEP 1a: perform preliminary actions/checks for derived tagged types
7517
7518       if Is_Tagged then
7519
7520          --  The parent type is frozen for non-private extensions (RM 13.14(7))
7521          --  The declaration of a specific descendant of an interface type
7522          --  freezes the interface type (RM 13.14).
7523
7524          if not Private_Extension or else Is_Interface (Parent_Base) then
7525             Freeze_Before (N, Parent_Type);
7526          end if;
7527
7528          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
7529          --  cannot be declared at a deeper level than its parent type is
7530          --  removed. The check on derivation within a generic body is also
7531          --  relaxed, but there's a restriction that a derived tagged type
7532          --  cannot be declared in a generic body if it's derived directly
7533          --  or indirectly from a formal type of that generic.
7534
7535          if Ada_Version >= Ada_2005 then
7536             if Present (Enclosing_Generic_Body (Derived_Type)) then
7537                declare
7538                   Ancestor_Type : Entity_Id;
7539
7540                begin
7541                   --  Check to see if any ancestor of the derived type is a
7542                   --  formal type.
7543
7544                   Ancestor_Type := Parent_Type;
7545                   while not Is_Generic_Type (Ancestor_Type)
7546                     and then Etype (Ancestor_Type) /= Ancestor_Type
7547                   loop
7548                      Ancestor_Type := Etype (Ancestor_Type);
7549                   end loop;
7550
7551                   --  If the derived type does have a formal type as an
7552                   --  ancestor, then it's an error if the derived type is
7553                   --  declared within the body of the generic unit that
7554                   --  declares the formal type in its generic formal part. It's
7555                   --  sufficient to check whether the ancestor type is declared
7556                   --  inside the same generic body as the derived type (such as
7557                   --  within a nested generic spec), in which case the
7558                   --  derivation is legal. If the formal type is declared
7559                   --  outside of that generic body, then it's guaranteed that
7560                   --  the derived type is declared within the generic body of
7561                   --  the generic unit declaring the formal type.
7562
7563                   if Is_Generic_Type (Ancestor_Type)
7564                     and then Enclosing_Generic_Body (Ancestor_Type) /=
7565                                Enclosing_Generic_Body (Derived_Type)
7566                   then
7567                      Error_Msg_NE
7568                        ("parent type of& must not be descendant of formal type"
7569                           & " of an enclosing generic body",
7570                             Indic, Derived_Type);
7571                   end if;
7572                end;
7573             end if;
7574
7575          elsif Type_Access_Level (Derived_Type) /=
7576                  Type_Access_Level (Parent_Type)
7577            and then not Is_Generic_Type (Derived_Type)
7578          then
7579             if Is_Controlled (Parent_Type) then
7580                Error_Msg_N
7581                  ("controlled type must be declared at the library level",
7582                   Indic);
7583             else
7584                Error_Msg_N
7585                  ("type extension at deeper accessibility level than parent",
7586                   Indic);
7587             end if;
7588
7589          else
7590             declare
7591                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
7592
7593             begin
7594                if Present (GB)
7595                  and then GB /= Enclosing_Generic_Body (Parent_Base)
7596                then
7597                   Error_Msg_NE
7598                     ("parent type of& must not be outside generic body"
7599                        & " (RM 3.9.1(4))",
7600                          Indic, Derived_Type);
7601                end if;
7602             end;
7603          end if;
7604       end if;
7605
7606       --  Ada 2005 (AI-251)
7607
7608       if Ada_Version >= Ada_2005 and then Is_Tagged then
7609
7610          --  "The declaration of a specific descendant of an interface type
7611          --  freezes the interface type" (RM 13.14).
7612
7613          declare
7614             Iface : Node_Id;
7615          begin
7616             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7617                Iface := First (Interface_List (Type_Def));
7618                while Present (Iface) loop
7619                   Freeze_Before (N, Etype (Iface));
7620                   Next (Iface);
7621                end loop;
7622             end if;
7623          end;
7624       end if;
7625
7626       --  STEP 1b : preliminary cleanup of the full view of private types
7627
7628       --  If the type is already marked as having discriminants, then it's the
7629       --  completion of a private type or private extension and we need to
7630       --  retain the discriminants from the partial view if the current
7631       --  declaration has Discriminant_Specifications so that we can verify
7632       --  conformance. However, we must remove any existing components that
7633       --  were inherited from the parent (and attached in Copy_And_Swap)
7634       --  because the full type inherits all appropriate components anyway, and
7635       --  we do not want the partial view's components interfering.
7636
7637       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7638          Discrim := First_Discriminant (Derived_Type);
7639          loop
7640             Last_Discrim := Discrim;
7641             Next_Discriminant (Discrim);
7642             exit when No (Discrim);
7643          end loop;
7644
7645          Set_Last_Entity (Derived_Type, Last_Discrim);
7646
7647       --  In all other cases wipe out the list of inherited components (even
7648       --  inherited discriminants), it will be properly rebuilt here.
7649
7650       else
7651          Set_First_Entity (Derived_Type, Empty);
7652          Set_Last_Entity  (Derived_Type, Empty);
7653       end if;
7654
7655       --  STEP 1c: Initialize some flags for the Derived_Type
7656
7657       --  The following flags must be initialized here so that
7658       --  Process_Discriminants can check that discriminants of tagged types do
7659       --  not have a default initial value and that access discriminants are
7660       --  only specified for limited records. For completeness, these flags are
7661       --  also initialized along with all the other flags below.
7662
7663       --  AI-419: Limitedness is not inherited from an interface parent, so to
7664       --  be limited in that case the type must be explicitly declared as
7665       --  limited. However, task and protected interfaces are always limited.
7666
7667       if Limited_Present (Type_Def) then
7668          Set_Is_Limited_Record (Derived_Type);
7669
7670       elsif Is_Limited_Record (Parent_Type)
7671         or else (Present (Full_View (Parent_Type))
7672                    and then Is_Limited_Record (Full_View (Parent_Type)))
7673       then
7674          if not Is_Interface (Parent_Type)
7675            or else Is_Synchronized_Interface (Parent_Type)
7676            or else Is_Protected_Interface (Parent_Type)
7677            or else Is_Task_Interface (Parent_Type)
7678          then
7679             Set_Is_Limited_Record (Derived_Type);
7680          end if;
7681       end if;
7682
7683       --  STEP 2a: process discriminants of derived type if any
7684
7685       Push_Scope (Derived_Type);
7686
7687       if Discriminant_Specs then
7688          Set_Has_Unknown_Discriminants (Derived_Type, False);
7689
7690          --  The following call initializes fields Has_Discriminants and
7691          --  Discriminant_Constraint, unless we are processing the completion
7692          --  of a private type declaration.
7693
7694          Check_Or_Process_Discriminants (N, Derived_Type);
7695
7696          --  For untagged types, the constraint on the Parent_Type must be
7697          --  present and is used to rename the discriminants.
7698
7699          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7700             Error_Msg_N ("untagged parent must have discriminants", Indic);
7701
7702          elsif not Is_Tagged and then not Constraint_Present then
7703             Error_Msg_N
7704               ("discriminant constraint needed for derived untagged records",
7705                Indic);
7706
7707          --  Otherwise the parent subtype must be constrained unless we have a
7708          --  private extension.
7709
7710          elsif not Constraint_Present
7711            and then not Private_Extension
7712            and then not Is_Constrained (Parent_Type)
7713          then
7714             Error_Msg_N
7715               ("unconstrained type not allowed in this context", Indic);
7716
7717          elsif Constraint_Present then
7718             --  The following call sets the field Corresponding_Discriminant
7719             --  for the discriminants in the Derived_Type.
7720
7721             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7722
7723             --  For untagged types all new discriminants must rename
7724             --  discriminants in the parent. For private extensions new
7725             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7726
7727             Discrim := First_Discriminant (Derived_Type);
7728             while Present (Discrim) loop
7729                if not Is_Tagged
7730                  and then No (Corresponding_Discriminant (Discrim))
7731                then
7732                   Error_Msg_N
7733                     ("new discriminants must constrain old ones", Discrim);
7734
7735                elsif Private_Extension
7736                  and then Present (Corresponding_Discriminant (Discrim))
7737                then
7738                   Error_Msg_N
7739                     ("only static constraints allowed for parent"
7740                      & " discriminants in the partial view", Indic);
7741                   exit;
7742                end if;
7743
7744                --  If a new discriminant is used in the constraint, then its
7745                --  subtype must be statically compatible with the parent
7746                --  discriminant's subtype (3.7(15)).
7747
7748                --  However, if the record contains an array constrained by
7749                --  the discriminant but with some different bound, the compiler
7750                --  attemps to create a smaller range for the discriminant type.
7751                --  (See exp_ch3.Adjust_Discriminants). In this case, where
7752                --  the discriminant type is a scalar type, the check must use
7753                --  the original discriminant type in the parent declaration.
7754
7755                declare
7756                   Corr_Disc : constant Entity_Id :=
7757                       Corresponding_Discriminant (Discrim);
7758                   Disc_Type : constant Entity_Id := Etype (Discrim);
7759                   Corr_Type : Entity_Id;
7760
7761                begin
7762                   if Present (Corr_Disc) then
7763                      if Is_Scalar_Type (Disc_Type) then
7764                         Corr_Type :=
7765                            Entity (Discriminant_Type (Parent (Corr_Disc)));
7766                      else
7767                         Corr_Type := Etype (Corr_Disc);
7768                      end if;
7769
7770                      if not
7771                         Subtypes_Statically_Compatible (Disc_Type, Corr_Type)
7772                      then
7773                         Error_Msg_N
7774                           ("subtype must be compatible "
7775                            & "with parent discriminant",
7776                            Discrim);
7777                      end if;
7778                   end if;
7779                end;
7780
7781                Next_Discriminant (Discrim);
7782             end loop;
7783
7784             --  Check whether the constraints of the full view statically
7785             --  match those imposed by the parent subtype [7.3(13)].
7786
7787             if Present (Stored_Constraint (Derived_Type)) then
7788                declare
7789                   C1, C2 : Elmt_Id;
7790
7791                begin
7792                   C1 := First_Elmt (Discs);
7793                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7794                   while Present (C1) and then Present (C2) loop
7795                      if not
7796                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7797                      then
7798                         Error_Msg_N
7799                           ("not conformant with previous declaration",
7800                            Node (C1));
7801                      end if;
7802
7803                      Next_Elmt (C1);
7804                      Next_Elmt (C2);
7805                   end loop;
7806                end;
7807             end if;
7808          end if;
7809
7810       --  STEP 2b: No new discriminants, inherit discriminants if any
7811
7812       else
7813          if Private_Extension then
7814             Set_Has_Unknown_Discriminants
7815               (Derived_Type,
7816                Has_Unknown_Discriminants (Parent_Type)
7817                  or else Unknown_Discriminants_Present (N));
7818
7819          --  The partial view of the parent may have unknown discriminants,
7820          --  but if the full view has discriminants and the parent type is
7821          --  in scope they must be inherited.
7822
7823          elsif Has_Unknown_Discriminants (Parent_Type)
7824            and then
7825             (not Has_Discriminants (Parent_Type)
7826               or else not In_Open_Scopes (Scope (Parent_Type)))
7827          then
7828             Set_Has_Unknown_Discriminants (Derived_Type);
7829          end if;
7830
7831          if not Has_Unknown_Discriminants (Derived_Type)
7832            and then not Has_Unknown_Discriminants (Parent_Base)
7833            and then Has_Discriminants (Parent_Type)
7834          then
7835             Inherit_Discrims := True;
7836             Set_Has_Discriminants
7837               (Derived_Type, True);
7838             Set_Discriminant_Constraint
7839               (Derived_Type, Discriminant_Constraint (Parent_Base));
7840          end if;
7841
7842          --  The following test is true for private types (remember
7843          --  transformation 5. is not applied to those) and in an error
7844          --  situation.
7845
7846          if Constraint_Present then
7847             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7848          end if;
7849
7850          --  For now mark a new derived type as constrained only if it has no
7851          --  discriminants. At the end of Build_Derived_Record_Type we properly
7852          --  set this flag in the case of private extensions. See comments in
7853          --  point 9. just before body of Build_Derived_Record_Type.
7854
7855          Set_Is_Constrained
7856            (Derived_Type,
7857             not (Inherit_Discrims
7858                    or else Has_Unknown_Discriminants (Derived_Type)));
7859       end if;
7860
7861       --  STEP 3: initialize fields of derived type
7862
7863       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7864       Set_Stored_Constraint (Derived_Type, No_Elist);
7865
7866       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7867       --  but cannot be interfaces
7868
7869       if not Private_Extension
7870          and then Ekind (Derived_Type) /= E_Private_Type
7871          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7872       then
7873          if Interface_Present (Type_Def) then
7874             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7875          end if;
7876
7877          Set_Interfaces (Derived_Type, No_Elist);
7878       end if;
7879
7880       --  Fields inherited from the Parent_Type
7881
7882       Set_Has_Specified_Layout
7883         (Derived_Type, Has_Specified_Layout (Parent_Type));
7884       Set_Is_Limited_Composite
7885         (Derived_Type, Is_Limited_Composite (Parent_Type));
7886       Set_Is_Private_Composite
7887         (Derived_Type, Is_Private_Composite (Parent_Type));
7888
7889       --  Fields inherited from the Parent_Base
7890
7891       Set_Has_Controlled_Component
7892         (Derived_Type, Has_Controlled_Component (Parent_Base));
7893       Set_Has_Non_Standard_Rep
7894         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7895       Set_Has_Primitive_Operations
7896         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7897
7898       --  Fields inherited from the Parent_Base in the non-private case
7899
7900       if Ekind (Derived_Type) = E_Record_Type then
7901          Set_Has_Complex_Representation
7902            (Derived_Type, Has_Complex_Representation (Parent_Base));
7903       end if;
7904
7905       --  Fields inherited from the Parent_Base for record types
7906
7907       if Is_Record_Type (Derived_Type) then
7908
7909          declare
7910             Parent_Full : Entity_Id;
7911
7912          begin
7913             --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7914             --  Parent_Base can be a private type or private extension. Go
7915             --  to the full view here to get the E_Record_Type specific flags.
7916
7917             if Present (Full_View (Parent_Base)) then
7918                Parent_Full := Full_View (Parent_Base);
7919             else
7920                Parent_Full := Parent_Base;
7921             end if;
7922
7923             Set_OK_To_Reorder_Components
7924               (Derived_Type, OK_To_Reorder_Components (Parent_Full));
7925          end;
7926       end if;
7927
7928       --  Set fields for private derived types
7929
7930       if Is_Private_Type (Derived_Type) then
7931          Set_Depends_On_Private (Derived_Type, True);
7932          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7933
7934       --  Inherit fields from non private record types. If this is the
7935       --  completion of a derivation from a private type, the parent itself
7936       --  is private, and the attributes come from its full view, which must
7937       --  be present.
7938
7939       else
7940          if Is_Private_Type (Parent_Base)
7941            and then not Is_Record_Type (Parent_Base)
7942          then
7943             Set_Component_Alignment
7944               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7945             Set_C_Pass_By_Copy
7946               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7947          else
7948             Set_Component_Alignment
7949               (Derived_Type, Component_Alignment (Parent_Base));
7950             Set_C_Pass_By_Copy
7951               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7952          end if;
7953       end if;
7954
7955       --  Set fields for tagged types
7956
7957       if Is_Tagged then
7958          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
7959
7960          --  All tagged types defined in Ada.Finalization are controlled
7961
7962          if Chars (Scope (Derived_Type)) = Name_Finalization
7963            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7964            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7965          then
7966             Set_Is_Controlled (Derived_Type);
7967          else
7968             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7969          end if;
7970
7971          --  Minor optimization: there is no need to generate the class-wide
7972          --  entity associated with an underlying record view.
7973
7974          if not Is_Underlying_Record_View (Derived_Type) then
7975             Make_Class_Wide_Type (Derived_Type);
7976          end if;
7977
7978          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7979
7980          if Has_Discriminants (Derived_Type)
7981            and then Constraint_Present
7982          then
7983             Set_Stored_Constraint
7984               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7985          end if;
7986
7987          if Ada_Version >= Ada_2005 then
7988             declare
7989                Ifaces_List : Elist_Id;
7990
7991             begin
7992                --  Checks rules 3.9.4 (13/2 and 14/2)
7993
7994                if Comes_From_Source (Derived_Type)
7995                  and then not Is_Private_Type (Derived_Type)
7996                  and then Is_Interface (Parent_Type)
7997                  and then not Is_Interface (Derived_Type)
7998                then
7999                   if Is_Task_Interface (Parent_Type) then
8000                      Error_Msg_N
8001                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
8002                         Derived_Type);
8003
8004                   elsif Is_Protected_Interface (Parent_Type) then
8005                      Error_Msg_N
8006                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
8007                         Derived_Type);
8008                   end if;
8009                end if;
8010
8011                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
8012
8013                Check_Interfaces (N, Type_Def);
8014
8015                --  Ada 2005 (AI-251): Collect the list of progenitors that are
8016                --  not already in the parents.
8017
8018                Collect_Interfaces
8019                  (T               => Derived_Type,
8020                   Ifaces_List     => Ifaces_List,
8021                   Exclude_Parents => True);
8022
8023                Set_Interfaces (Derived_Type, Ifaces_List);
8024
8025                --  If the derived type is the anonymous type created for
8026                --  a declaration whose parent has a constraint, propagate
8027                --  the interface list to the source type. This must be done
8028                --  prior to the completion of the analysis of the source type
8029                --  because the components in the extension may contain current
8030                --  instances whose legality depends on some ancestor.
8031
8032                if Is_Itype (Derived_Type) then
8033                   declare
8034                      Def : constant Node_Id :=
8035                        Associated_Node_For_Itype (Derived_Type);
8036                   begin
8037                      if Present (Def)
8038                        and then Nkind (Def) = N_Full_Type_Declaration
8039                      then
8040                         Set_Interfaces
8041                           (Defining_Identifier (Def), Ifaces_List);
8042                      end if;
8043                   end;
8044                end if;
8045             end;
8046          end if;
8047
8048       else
8049          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
8050          Set_Has_Non_Standard_Rep
8051                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
8052       end if;
8053
8054       --  STEP 4: Inherit components from the parent base and constrain them.
8055       --          Apply the second transformation described in point 6. above.
8056
8057       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
8058         or else not Has_Discriminants (Parent_Type)
8059         or else not Is_Constrained (Parent_Type)
8060       then
8061          Constrs := Discs;
8062       else
8063          Constrs := Discriminant_Constraint (Parent_Type);
8064       end if;
8065
8066       Assoc_List :=
8067         Inherit_Components
8068           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
8069
8070       --  STEP 5a: Copy the parent record declaration for untagged types
8071
8072       if not Is_Tagged then
8073
8074          --  Discriminant_Constraint (Derived_Type) has been properly
8075          --  constructed. Save it and temporarily set it to Empty because we
8076          --  do not want the call to New_Copy_Tree below to mess this list.
8077
8078          if Has_Discriminants (Derived_Type) then
8079             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
8080             Set_Discriminant_Constraint (Derived_Type, No_Elist);
8081          else
8082             Save_Discr_Constr := No_Elist;
8083          end if;
8084
8085          --  Save the Etype field of Derived_Type. It is correctly set now,
8086          --  but the call to New_Copy tree may remap it to point to itself,
8087          --  which is not what we want. Ditto for the Next_Entity field.
8088
8089          Save_Etype       := Etype (Derived_Type);
8090          Save_Next_Entity := Next_Entity (Derived_Type);
8091
8092          --  Assoc_List maps all stored discriminants in the Parent_Base to
8093          --  stored discriminants in the Derived_Type. It is fundamental that
8094          --  no types or itypes with discriminants other than the stored
8095          --  discriminants appear in the entities declared inside
8096          --  Derived_Type, since the back end cannot deal with it.
8097
8098          New_Decl :=
8099            New_Copy_Tree
8100              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
8101
8102          --  Restore the fields saved prior to the New_Copy_Tree call
8103          --  and compute the stored constraint.
8104
8105          Set_Etype       (Derived_Type, Save_Etype);
8106          Set_Next_Entity (Derived_Type, Save_Next_Entity);
8107
8108          if Has_Discriminants (Derived_Type) then
8109             Set_Discriminant_Constraint
8110               (Derived_Type, Save_Discr_Constr);
8111             Set_Stored_Constraint
8112               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
8113             Replace_Components (Derived_Type, New_Decl);
8114             Set_Has_Implicit_Dereference
8115               (Derived_Type, Has_Implicit_Dereference (Parent_Type));
8116          end if;
8117
8118          --  Insert the new derived type declaration
8119
8120          Rewrite (N, New_Decl);
8121
8122       --  STEP 5b: Complete the processing for record extensions in generics
8123
8124       --  There is no completion for record extensions declared in the
8125       --  parameter part of a generic, so we need to complete processing for
8126       --  these generic record extensions here. The Record_Type_Definition call
8127       --  will change the Ekind of the components from E_Void to E_Component.
8128
8129       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
8130          Record_Type_Definition (Empty, Derived_Type);
8131
8132       --  STEP 5c: Process the record extension for non private tagged types
8133
8134       elsif not Private_Extension then
8135
8136          --  Add the _parent field in the derived type
8137
8138          Expand_Record_Extension (Derived_Type, Type_Def);
8139
8140          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
8141          --  implemented interfaces if we are in expansion mode
8142
8143          if Expander_Active
8144            and then Has_Interfaces (Derived_Type)
8145          then
8146             Add_Interface_Tag_Components (N, Derived_Type);
8147          end if;
8148
8149          --  Analyze the record extension
8150
8151          Record_Type_Definition
8152            (Record_Extension_Part (Type_Def), Derived_Type);
8153       end if;
8154
8155       End_Scope;
8156
8157       --  Nothing else to do if there is an error in the derivation.
8158       --  An unusual case: the full view may be derived from a type in an
8159       --  instance, when the partial view was used illegally as an actual
8160       --  in that instance, leading to a circular definition.
8161
8162       if Etype (Derived_Type) = Any_Type
8163         or else Etype (Parent_Type) = Derived_Type
8164       then
8165          return;
8166       end if;
8167
8168       --  Set delayed freeze and then derive subprograms, we need to do
8169       --  this in this order so that derived subprograms inherit the
8170       --  derived freeze if necessary.
8171
8172       Set_Has_Delayed_Freeze (Derived_Type);
8173
8174       if Derive_Subps then
8175          Derive_Subprograms (Parent_Type, Derived_Type);
8176       end if;
8177
8178       --  If we have a private extension which defines a constrained derived
8179       --  type mark as constrained here after we have derived subprograms. See
8180       --  comment on point 9. just above the body of Build_Derived_Record_Type.
8181
8182       if Private_Extension and then Inherit_Discrims then
8183          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
8184             Set_Is_Constrained          (Derived_Type, True);
8185             Set_Discriminant_Constraint (Derived_Type, Discs);
8186
8187          elsif Is_Constrained (Parent_Type) then
8188             Set_Is_Constrained
8189               (Derived_Type, True);
8190             Set_Discriminant_Constraint
8191               (Derived_Type, Discriminant_Constraint (Parent_Type));
8192          end if;
8193       end if;
8194
8195       --  Update the class-wide type, which shares the now-completed entity
8196       --  list with its specific type. In case of underlying record views,
8197       --  we do not generate the corresponding class wide entity.
8198
8199       if Is_Tagged
8200         and then not Is_Underlying_Record_View (Derived_Type)
8201       then
8202          Set_First_Entity
8203            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
8204          Set_Last_Entity
8205            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
8206       end if;
8207
8208       Check_Function_Writable_Actuals (N);
8209    end Build_Derived_Record_Type;
8210
8211    ------------------------
8212    -- Build_Derived_Type --
8213    ------------------------
8214
8215    procedure Build_Derived_Type
8216      (N             : Node_Id;
8217       Parent_Type   : Entity_Id;
8218       Derived_Type  : Entity_Id;
8219       Is_Completion : Boolean;
8220       Derive_Subps  : Boolean := True)
8221    is
8222       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
8223
8224    begin
8225       --  Set common attributes
8226
8227       Set_Scope          (Derived_Type, Current_Scope);
8228
8229       Set_Ekind          (Derived_Type, Ekind    (Parent_Base));
8230       Set_Etype          (Derived_Type,           Parent_Base);
8231       Set_Has_Task       (Derived_Type, Has_Task (Parent_Base));
8232
8233       Set_Size_Info      (Derived_Type,                 Parent_Type);
8234       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
8235       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
8236       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
8237
8238       --  If the parent type is a private subtype, the convention on the base
8239       --  type may be set in the private part, and not propagated to the
8240       --  subtype until later, so we obtain the convention from the base type.
8241
8242       Set_Convention     (Derived_Type, Convention     (Parent_Base));
8243
8244       --  Propagate invariant information. The new type has invariants if
8245       --  they are inherited from the parent type, and these invariants can
8246       --  be further inherited, so both flags are set.
8247
8248       --  We similarly inherit predicates
8249
8250       if Has_Predicates (Parent_Type) then
8251          Set_Has_Predicates (Derived_Type);
8252       end if;
8253
8254       --  The derived type inherits the representation clauses of the parent.
8255       --  However, for a private type that is completed by a derivation, there
8256       --  may be operation attributes that have been specified already (stream
8257       --  attributes and External_Tag) and those must be provided. Finally,
8258       --  if the partial view is a private extension, the representation items
8259       --  of the parent have been inherited already, and should not be chained
8260       --  twice to the derived type.
8261
8262       if Is_Tagged_Type (Parent_Type)
8263         and then Present (First_Rep_Item (Derived_Type))
8264       then
8265          --  The existing items are either operational items or items inherited
8266          --  from a private extension declaration.
8267
8268          declare
8269             Rep : Node_Id;
8270             --  Used to iterate over representation items of the derived type
8271
8272             Last_Rep : Node_Id;
8273             --  Last representation item of the (non-empty) representation
8274             --  item list of the derived type.
8275
8276             Found : Boolean := False;
8277
8278          begin
8279             Rep      := First_Rep_Item (Derived_Type);
8280             Last_Rep := Rep;
8281             while Present (Rep) loop
8282                if Rep = First_Rep_Item (Parent_Type) then
8283                   Found := True;
8284                   exit;
8285
8286                else
8287                   Rep := Next_Rep_Item (Rep);
8288
8289                   if Present (Rep) then
8290                      Last_Rep := Rep;
8291                   end if;
8292                end if;
8293             end loop;
8294
8295             --  Here if we either encountered the parent type's first rep
8296             --  item on the derived type's rep item list (in which case
8297             --  Found is True, and we have nothing else to do), or if we
8298             --  reached the last rep item of the derived type, which is
8299             --  Last_Rep, in which case we further chain the parent type's
8300             --  rep items to those of the derived type.
8301
8302             if not Found then
8303                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
8304             end if;
8305          end;
8306
8307       else
8308          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
8309       end if;
8310
8311       --  If the parent type has delayed rep aspects, then mark the derived
8312       --  type as possibly inheriting a delayed rep aspect.
8313
8314       if Has_Delayed_Rep_Aspects (Parent_Type) then
8315          Set_May_Inherit_Delayed_Rep_Aspects (Derived_Type);
8316       end if;
8317
8318       --  Type dependent processing
8319
8320       case Ekind (Parent_Type) is
8321          when Numeric_Kind =>
8322             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
8323
8324          when Array_Kind =>
8325             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
8326
8327          when E_Record_Type
8328             | E_Record_Subtype
8329             | Class_Wide_Kind  =>
8330             Build_Derived_Record_Type
8331               (N, Parent_Type, Derived_Type, Derive_Subps);
8332             return;
8333
8334          when Enumeration_Kind =>
8335             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
8336
8337          when Access_Kind =>
8338             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
8339
8340          when Incomplete_Or_Private_Kind =>
8341             Build_Derived_Private_Type
8342               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
8343
8344             --  For discriminated types, the derivation includes deriving
8345             --  primitive operations. For others it is done below.
8346
8347             if Is_Tagged_Type (Parent_Type)
8348               or else Has_Discriminants (Parent_Type)
8349               or else (Present (Full_View (Parent_Type))
8350                         and then Has_Discriminants (Full_View (Parent_Type)))
8351             then
8352                return;
8353             end if;
8354
8355          when Concurrent_Kind =>
8356             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
8357
8358          when others =>
8359             raise Program_Error;
8360       end case;
8361
8362       --  Nothing more to do if some error occurred
8363
8364       if Etype (Derived_Type) = Any_Type then
8365          return;
8366       end if;
8367
8368       --  Set delayed freeze and then derive subprograms, we need to do this
8369       --  in this order so that derived subprograms inherit the derived freeze
8370       --  if necessary.
8371
8372       Set_Has_Delayed_Freeze (Derived_Type);
8373
8374       if Derive_Subps then
8375          Derive_Subprograms (Parent_Type, Derived_Type);
8376       end if;
8377
8378       Set_Has_Primitive_Operations
8379         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
8380    end Build_Derived_Type;
8381
8382    -----------------------
8383    -- Build_Discriminal --
8384    -----------------------
8385
8386    procedure Build_Discriminal (Discrim : Entity_Id) is
8387       D_Minal : Entity_Id;
8388       CR_Disc : Entity_Id;
8389
8390    begin
8391       --  A discriminal has the same name as the discriminant
8392
8393       D_Minal := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
8394
8395       Set_Ekind     (D_Minal, E_In_Parameter);
8396       Set_Mechanism (D_Minal, Default_Mechanism);
8397       Set_Etype     (D_Minal, Etype (Discrim));
8398       Set_Scope     (D_Minal, Current_Scope);
8399
8400       Set_Discriminal (Discrim, D_Minal);
8401       Set_Discriminal_Link (D_Minal, Discrim);
8402
8403       --  For task types, build at once the discriminants of the corresponding
8404       --  record, which are needed if discriminants are used in entry defaults
8405       --  and in family bounds.
8406
8407       if Is_Concurrent_Type (Current_Scope)
8408         or else Is_Limited_Type (Current_Scope)
8409       then
8410          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
8411
8412          Set_Ekind            (CR_Disc, E_In_Parameter);
8413          Set_Mechanism        (CR_Disc, Default_Mechanism);
8414          Set_Etype            (CR_Disc, Etype (Discrim));
8415          Set_Scope            (CR_Disc, Current_Scope);
8416          Set_Discriminal_Link (CR_Disc, Discrim);
8417          Set_CR_Discriminant  (Discrim, CR_Disc);
8418       end if;
8419    end Build_Discriminal;
8420
8421    ------------------------------------
8422    -- Build_Discriminant_Constraints --
8423    ------------------------------------
8424
8425    function Build_Discriminant_Constraints
8426      (T           : Entity_Id;
8427       Def         : Node_Id;
8428       Derived_Def : Boolean := False) return Elist_Id
8429    is
8430       C        : constant Node_Id := Constraint (Def);
8431       Nb_Discr : constant Nat     := Number_Discriminants (T);
8432
8433       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
8434       --  Saves the expression corresponding to a given discriminant in T
8435
8436       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
8437       --  Return the Position number within array Discr_Expr of a discriminant
8438       --  D within the discriminant list of the discriminated type T.
8439
8440       procedure Process_Discriminant_Expression
8441          (Expr : Node_Id;
8442           D    : Entity_Id);
8443       --  If this is a discriminant constraint on a partial view, do not
8444       --  generate an overflow check on the discriminant expression. The check
8445       --  will be generated when constraining the full view. Otherwise the
8446       --  backend creates duplicate symbols for the temporaries corresponding
8447       --  to the expressions to be checked, causing spurious assembler errors.
8448
8449       ------------------
8450       -- Pos_Of_Discr --
8451       ------------------
8452
8453       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
8454          Disc : Entity_Id;
8455
8456       begin
8457          Disc := First_Discriminant (T);
8458          for J in Discr_Expr'Range loop
8459             if Disc = D then
8460                return J;
8461             end if;
8462
8463             Next_Discriminant (Disc);
8464          end loop;
8465
8466          --  Note: Since this function is called on discriminants that are
8467          --  known to belong to the discriminated type, falling through the
8468          --  loop with no match signals an internal compiler error.
8469
8470          raise Program_Error;
8471       end Pos_Of_Discr;
8472
8473       -------------------------------------
8474       -- Process_Discriminant_Expression --
8475       -------------------------------------
8476
8477       procedure Process_Discriminant_Expression
8478          (Expr : Node_Id;
8479           D    : Entity_Id)
8480       is
8481          BDT : constant Entity_Id := Base_Type (Etype (D));
8482
8483       begin
8484          --  If this is a discriminant constraint on a partial view, do
8485          --  not generate an overflow on the discriminant expression. The
8486          --  check will be generated when constraining the full view.
8487
8488          if Is_Private_Type (T)
8489            and then Present (Full_View (T))
8490          then
8491             Analyze_And_Resolve (Expr, BDT, Suppress => Overflow_Check);
8492          else
8493             Analyze_And_Resolve (Expr, BDT);
8494          end if;
8495       end Process_Discriminant_Expression;
8496
8497       --  Declarations local to Build_Discriminant_Constraints
8498
8499       Discr : Entity_Id;
8500       E     : Entity_Id;
8501       Elist : constant Elist_Id := New_Elmt_List;
8502
8503       Constr   : Node_Id;
8504       Expr     : Node_Id;
8505       Id       : Node_Id;
8506       Position : Nat;
8507       Found    : Boolean;
8508
8509       Discrim_Present : Boolean := False;
8510
8511    --  Start of processing for Build_Discriminant_Constraints
8512
8513    begin
8514       --  The following loop will process positional associations only.
8515       --  For a positional association, the (single) discriminant is
8516       --  implicitly specified by position, in textual order (RM 3.7.2).
8517
8518       Discr  := First_Discriminant (T);
8519       Constr := First (Constraints (C));
8520       for D in Discr_Expr'Range loop
8521          exit when Nkind (Constr) = N_Discriminant_Association;
8522
8523          if No (Constr) then
8524             Error_Msg_N ("too few discriminants given in constraint", C);
8525             return New_Elmt_List;
8526
8527          elsif Nkind (Constr) = N_Range
8528            or else (Nkind (Constr) = N_Attribute_Reference
8529                      and then
8530                     Attribute_Name (Constr) = Name_Range)
8531          then
8532             Error_Msg_N
8533               ("a range is not a valid discriminant constraint", Constr);
8534             Discr_Expr (D) := Error;
8535
8536          else
8537             Process_Discriminant_Expression (Constr, Discr);
8538             Discr_Expr (D) := Constr;
8539          end if;
8540
8541          Next_Discriminant (Discr);
8542          Next (Constr);
8543       end loop;
8544
8545       if No (Discr) and then Present (Constr) then
8546          Error_Msg_N ("too many discriminants given in constraint", Constr);
8547          return New_Elmt_List;
8548       end if;
8549
8550       --  Named associations can be given in any order, but if both positional
8551       --  and named associations are used in the same discriminant constraint,
8552       --  then positional associations must occur first, at their normal
8553       --  position. Hence once a named association is used, the rest of the
8554       --  discriminant constraint must use only named associations.
8555
8556       while Present (Constr) loop
8557
8558          --  Positional association forbidden after a named association
8559
8560          if Nkind (Constr) /= N_Discriminant_Association then
8561             Error_Msg_N ("positional association follows named one", Constr);
8562             return New_Elmt_List;
8563
8564          --  Otherwise it is a named association
8565
8566          else
8567             --  E records the type of the discriminants in the named
8568             --  association. All the discriminants specified in the same name
8569             --  association must have the same type.
8570
8571             E := Empty;
8572
8573             --  Search the list of discriminants in T to see if the simple name
8574             --  given in the constraint matches any of them.
8575
8576             Id := First (Selector_Names (Constr));
8577             while Present (Id) loop
8578                Found := False;
8579
8580                --  If Original_Discriminant is present, we are processing a
8581                --  generic instantiation and this is an instance node. We need
8582                --  to find the name of the corresponding discriminant in the
8583                --  actual record type T and not the name of the discriminant in
8584                --  the generic formal. Example:
8585
8586                --    generic
8587                --       type G (D : int) is private;
8588                --    package P is
8589                --       subtype W is G (D => 1);
8590                --    end package;
8591                --    type Rec (X : int) is record ... end record;
8592                --    package Q is new P (G => Rec);
8593
8594                --  At the point of the instantiation, formal type G is Rec
8595                --  and therefore when reanalyzing "subtype W is G (D => 1);"
8596                --  which really looks like "subtype W is Rec (D => 1);" at
8597                --  the point of instantiation, we want to find the discriminant
8598                --  that corresponds to D in Rec, i.e. X.
8599
8600                if Present (Original_Discriminant (Id))
8601                  and then In_Instance
8602                then
8603                   Discr := Find_Corresponding_Discriminant (Id, T);
8604                   Found := True;
8605
8606                else
8607                   Discr := First_Discriminant (T);
8608                   while Present (Discr) loop
8609                      if Chars (Discr) = Chars (Id) then
8610                         Found := True;
8611                         exit;
8612                      end if;
8613
8614                      Next_Discriminant (Discr);
8615                   end loop;
8616
8617                   if not Found then
8618                      Error_Msg_N ("& does not match any discriminant", Id);
8619                      return New_Elmt_List;
8620
8621                   --  If the parent type is a generic formal, preserve the
8622                   --  name of the discriminant for subsequent instances.
8623                   --  see comment at the beginning of this if statement.
8624
8625                   elsif Is_Generic_Type (Root_Type (T)) then
8626                      Set_Original_Discriminant (Id, Discr);
8627                   end if;
8628                end if;
8629
8630                Position := Pos_Of_Discr (T, Discr);
8631
8632                if Present (Discr_Expr (Position)) then
8633                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
8634
8635                else
8636                   --  Each discriminant specified in the same named association
8637                   --  must be associated with a separate copy of the
8638                   --  corresponding expression.
8639
8640                   if Present (Next (Id)) then
8641                      Expr := New_Copy_Tree (Expression (Constr));
8642                      Set_Parent (Expr, Parent (Expression (Constr)));
8643                   else
8644                      Expr := Expression (Constr);
8645                   end if;
8646
8647                   Discr_Expr (Position) := Expr;
8648                   Process_Discriminant_Expression (Expr, Discr);
8649                end if;
8650
8651                --  A discriminant association with more than one discriminant
8652                --  name is only allowed if the named discriminants are all of
8653                --  the same type (RM 3.7.1(8)).
8654
8655                if E = Empty then
8656                   E := Base_Type (Etype (Discr));
8657
8658                elsif Base_Type (Etype (Discr)) /= E then
8659                   Error_Msg_N
8660                     ("all discriminants in an association " &
8661                      "must have the same type", Id);
8662                end if;
8663
8664                Next (Id);
8665             end loop;
8666          end if;
8667
8668          Next (Constr);
8669       end loop;
8670
8671       --  A discriminant constraint must provide exactly one value for each
8672       --  discriminant of the type (RM 3.7.1(8)).
8673
8674       for J in Discr_Expr'Range loop
8675          if No (Discr_Expr (J)) then
8676             Error_Msg_N ("too few discriminants given in constraint", C);
8677             return New_Elmt_List;
8678          end if;
8679       end loop;
8680
8681       --  Determine if there are discriminant expressions in the constraint
8682
8683       for J in Discr_Expr'Range loop
8684          if Denotes_Discriminant
8685               (Discr_Expr (J), Check_Concurrent => True)
8686          then
8687             Discrim_Present := True;
8688          end if;
8689       end loop;
8690
8691       --  Build an element list consisting of the expressions given in the
8692       --  discriminant constraint and apply the appropriate checks. The list
8693       --  is constructed after resolving any named discriminant associations
8694       --  and therefore the expressions appear in the textual order of the
8695       --  discriminants.
8696
8697       Discr := First_Discriminant (T);
8698       for J in Discr_Expr'Range loop
8699          if Discr_Expr (J) /= Error then
8700             Append_Elmt (Discr_Expr (J), Elist);
8701
8702             --  If any of the discriminant constraints is given by a
8703             --  discriminant and we are in a derived type declaration we
8704             --  have a discriminant renaming. Establish link between new
8705             --  and old discriminant.
8706
8707             if Denotes_Discriminant (Discr_Expr (J)) then
8708                if Derived_Def then
8709                   Set_Corresponding_Discriminant
8710                     (Entity (Discr_Expr (J)), Discr);
8711                end if;
8712
8713             --  Force the evaluation of non-discriminant expressions.
8714             --  If we have found a discriminant in the constraint 3.4(26)
8715             --  and 3.8(18) demand that no range checks are performed are
8716             --  after evaluation. If the constraint is for a component
8717             --  definition that has a per-object constraint, expressions are
8718             --  evaluated but not checked either. In all other cases perform
8719             --  a range check.
8720
8721             else
8722                if Discrim_Present then
8723                   null;
8724
8725                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8726                  and then
8727                    Has_Per_Object_Constraint
8728                      (Defining_Identifier (Parent (Parent (Def))))
8729                then
8730                   null;
8731
8732                elsif Is_Access_Type (Etype (Discr)) then
8733                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8734
8735                else
8736                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8737                end if;
8738
8739                Force_Evaluation (Discr_Expr (J));
8740             end if;
8741
8742             --  Check that the designated type of an access discriminant's
8743             --  expression is not a class-wide type unless the discriminant's
8744             --  designated type is also class-wide.
8745
8746             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8747               and then not Is_Class_Wide_Type
8748                          (Designated_Type (Etype (Discr)))
8749               and then Etype (Discr_Expr (J)) /= Any_Type
8750               and then Is_Class_Wide_Type
8751                          (Designated_Type (Etype (Discr_Expr (J))))
8752             then
8753                Wrong_Type (Discr_Expr (J), Etype (Discr));
8754
8755             elsif Is_Access_Type (Etype (Discr))
8756               and then not Is_Access_Constant (Etype (Discr))
8757               and then Is_Access_Type (Etype (Discr_Expr (J)))
8758               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8759             then
8760                Error_Msg_NE
8761                  ("constraint for discriminant& must be access to variable",
8762                     Def, Discr);
8763             end if;
8764          end if;
8765
8766          Next_Discriminant (Discr);
8767       end loop;
8768
8769       return Elist;
8770    end Build_Discriminant_Constraints;
8771
8772    ---------------------------------
8773    -- Build_Discriminated_Subtype --
8774    ---------------------------------
8775
8776    procedure Build_Discriminated_Subtype
8777      (T           : Entity_Id;
8778       Def_Id      : Entity_Id;
8779       Elist       : Elist_Id;
8780       Related_Nod : Node_Id;
8781       For_Access  : Boolean := False)
8782    is
8783       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8784       Constrained : constant Boolean :=
8785                       (Has_Discrs
8786                          and then not Is_Empty_Elmt_List (Elist)
8787                          and then not Is_Class_Wide_Type (T))
8788                         or else Is_Constrained (T);
8789
8790    begin
8791       if Ekind (T) = E_Record_Type then
8792          if For_Access then
8793             Set_Ekind (Def_Id, E_Private_Subtype);
8794             Set_Is_For_Access_Subtype (Def_Id, True);
8795          else
8796             Set_Ekind (Def_Id, E_Record_Subtype);
8797          end if;
8798
8799          --  Inherit preelaboration flag from base, for types for which it
8800          --  may have been set: records, private types, protected types.
8801
8802          Set_Known_To_Have_Preelab_Init
8803            (Def_Id, Known_To_Have_Preelab_Init (T));
8804
8805       elsif Ekind (T) = E_Task_Type then
8806          Set_Ekind (Def_Id, E_Task_Subtype);
8807
8808       elsif Ekind (T) = E_Protected_Type then
8809          Set_Ekind (Def_Id, E_Protected_Subtype);
8810          Set_Known_To_Have_Preelab_Init
8811            (Def_Id, Known_To_Have_Preelab_Init (T));
8812
8813       elsif Is_Private_Type (T) then
8814          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8815          Set_Known_To_Have_Preelab_Init
8816            (Def_Id, Known_To_Have_Preelab_Init (T));
8817
8818          --  Private subtypes may have private dependents
8819
8820          Set_Private_Dependents (Def_Id, New_Elmt_List);
8821
8822       elsif Is_Class_Wide_Type (T) then
8823          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8824
8825       else
8826          --  Incomplete type. Attach subtype to list of dependents, to be
8827          --  completed with full view of parent type,  unless is it the
8828          --  designated subtype of a record component within an init_proc.
8829          --  This last case arises for a component of an access type whose
8830          --  designated type is incomplete (e.g. a Taft Amendment type).
8831          --  The designated subtype is within an inner scope, and needs no
8832          --  elaboration, because only the access type is needed in the
8833          --  initialization procedure.
8834
8835          Set_Ekind (Def_Id, Ekind (T));
8836
8837          if For_Access and then Within_Init_Proc then
8838             null;
8839          else
8840             Append_Elmt (Def_Id, Private_Dependents (T));
8841          end if;
8842       end if;
8843
8844       Set_Etype             (Def_Id, T);
8845       Init_Size_Align       (Def_Id);
8846       Set_Has_Discriminants (Def_Id, Has_Discrs);
8847       Set_Is_Constrained    (Def_Id, Constrained);
8848
8849       Set_First_Entity      (Def_Id, First_Entity   (T));
8850       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8851       Set_Has_Implicit_Dereference
8852                             (Def_Id, Has_Implicit_Dereference (T));
8853
8854       --  If the subtype is the completion of a private declaration, there may
8855       --  have been representation clauses for the partial view, and they must
8856       --  be preserved. Build_Derived_Type chains the inherited clauses with
8857       --  the ones appearing on the extension. If this comes from a subtype
8858       --  declaration, all clauses are inherited.
8859
8860       if No (First_Rep_Item (Def_Id)) then
8861          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8862       end if;
8863
8864       if Is_Tagged_Type (T) then
8865          Set_Is_Tagged_Type (Def_Id);
8866          Make_Class_Wide_Type (Def_Id);
8867       end if;
8868
8869       Set_Stored_Constraint (Def_Id, No_Elist);
8870
8871       if Has_Discrs then
8872          Set_Discriminant_Constraint (Def_Id, Elist);
8873          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8874       end if;
8875
8876       if Is_Tagged_Type (T) then
8877
8878          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8879          --  concurrent record type (which has the list of primitive
8880          --  operations).
8881
8882          if Ada_Version >= Ada_2005
8883            and then Is_Concurrent_Type (T)
8884          then
8885             Set_Corresponding_Record_Type (Def_Id,
8886                Corresponding_Record_Type (T));
8887          else
8888             Set_Direct_Primitive_Operations (Def_Id,
8889               Direct_Primitive_Operations (T));
8890          end if;
8891
8892          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8893       end if;
8894
8895       --  Subtypes introduced by component declarations do not need to be
8896       --  marked as delayed, and do not get freeze nodes, because the semantics
8897       --  verifies that the parents of the subtypes are frozen before the
8898       --  enclosing record is frozen.
8899
8900       if not Is_Type (Scope (Def_Id)) then
8901          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8902
8903          if Is_Private_Type (T)
8904            and then Present (Full_View (T))
8905          then
8906             Conditional_Delay (Def_Id, Full_View (T));
8907          else
8908             Conditional_Delay (Def_Id, T);
8909          end if;
8910       end if;
8911
8912       if Is_Record_Type (T) then
8913          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8914
8915          if Has_Discrs
8916             and then not Is_Empty_Elmt_List (Elist)
8917             and then not For_Access
8918          then
8919             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8920          elsif not For_Access then
8921             Set_Cloned_Subtype (Def_Id, T);
8922          end if;
8923       end if;
8924    end Build_Discriminated_Subtype;
8925
8926    ---------------------------
8927    -- Build_Itype_Reference --
8928    ---------------------------
8929
8930    procedure Build_Itype_Reference
8931      (Ityp : Entity_Id;
8932       Nod  : Node_Id)
8933    is
8934       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8935    begin
8936
8937       --  Itype references are only created for use by the back-end
8938
8939       if Inside_A_Generic then
8940          return;
8941       else
8942          Set_Itype (IR, Ityp);
8943          Insert_After (Nod, IR);
8944       end if;
8945    end Build_Itype_Reference;
8946
8947    ------------------------
8948    -- Build_Scalar_Bound --
8949    ------------------------
8950
8951    function Build_Scalar_Bound
8952      (Bound : Node_Id;
8953       Par_T : Entity_Id;
8954       Der_T : Entity_Id) return Node_Id
8955    is
8956       New_Bound : Entity_Id;
8957
8958    begin
8959       --  Note: not clear why this is needed, how can the original bound
8960       --  be unanalyzed at this point? and if it is, what business do we
8961       --  have messing around with it? and why is the base type of the
8962       --  parent type the right type for the resolution. It probably is
8963       --  not! It is OK for the new bound we are creating, but not for
8964       --  the old one??? Still if it never happens, no problem!
8965
8966       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8967
8968       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8969          New_Bound := New_Copy (Bound);
8970          Set_Etype (New_Bound, Der_T);
8971          Set_Analyzed (New_Bound);
8972
8973       elsif Is_Entity_Name (Bound) then
8974          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8975
8976       --  The following is almost certainly wrong. What business do we have
8977       --  relocating a node (Bound) that is presumably still attached to
8978       --  the tree elsewhere???
8979
8980       else
8981          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8982       end if;
8983
8984       Set_Etype (New_Bound, Der_T);
8985       return New_Bound;
8986    end Build_Scalar_Bound;
8987
8988    --------------------------------
8989    -- Build_Underlying_Full_View --
8990    --------------------------------
8991
8992    procedure Build_Underlying_Full_View
8993      (N   : Node_Id;
8994       Typ : Entity_Id;
8995       Par : Entity_Id)
8996    is
8997       Loc  : constant Source_Ptr := Sloc (N);
8998       Subt : constant Entity_Id :=
8999                Make_Defining_Identifier
9000                  (Loc, New_External_Name (Chars (Typ), 'S'));
9001
9002       Constr : Node_Id;
9003       Indic  : Node_Id;
9004       C      : Node_Id;
9005       Id     : Node_Id;
9006
9007       procedure Set_Discriminant_Name (Id : Node_Id);
9008       --  If the derived type has discriminants, they may rename discriminants
9009       --  of the parent. When building the full view of the parent, we need to
9010       --  recover the names of the original discriminants if the constraint is
9011       --  given by named associations.
9012
9013       ---------------------------
9014       -- Set_Discriminant_Name --
9015       ---------------------------
9016
9017       procedure Set_Discriminant_Name (Id : Node_Id) is
9018          Disc : Entity_Id;
9019
9020       begin
9021          Set_Original_Discriminant (Id, Empty);
9022
9023          if Has_Discriminants (Typ) then
9024             Disc := First_Discriminant (Typ);
9025             while Present (Disc) loop
9026                if Chars (Disc) = Chars (Id)
9027                  and then Present (Corresponding_Discriminant (Disc))
9028                then
9029                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
9030                end if;
9031                Next_Discriminant (Disc);
9032             end loop;
9033          end if;
9034       end Set_Discriminant_Name;
9035
9036    --  Start of processing for Build_Underlying_Full_View
9037
9038    begin
9039       if Nkind (N) = N_Full_Type_Declaration then
9040          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
9041
9042       elsif Nkind (N) = N_Subtype_Declaration then
9043          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
9044
9045       elsif Nkind (N) = N_Component_Declaration then
9046          Constr :=
9047            New_Copy_Tree
9048              (Constraint (Subtype_Indication (Component_Definition (N))));
9049
9050       else
9051          raise Program_Error;
9052       end if;
9053
9054       C := First (Constraints (Constr));
9055       while Present (C) loop
9056          if Nkind (C) = N_Discriminant_Association then
9057             Id := First (Selector_Names (C));
9058             while Present (Id) loop
9059                Set_Discriminant_Name (Id);
9060                Next (Id);
9061             end loop;
9062          end if;
9063
9064          Next (C);
9065       end loop;
9066
9067       Indic :=
9068         Make_Subtype_Declaration (Loc,
9069           Defining_Identifier => Subt,
9070           Subtype_Indication  =>
9071             Make_Subtype_Indication (Loc,
9072               Subtype_Mark => New_Reference_To (Par, Loc),
9073               Constraint   => New_Copy_Tree (Constr)));
9074
9075       --  If this is a component subtype for an outer itype, it is not
9076       --  a list member, so simply set the parent link for analysis: if
9077       --  the enclosing type does not need to be in a declarative list,
9078       --  neither do the components.
9079
9080       if Is_List_Member (N)
9081         and then Nkind (N) /= N_Component_Declaration
9082       then
9083          Insert_Before (N, Indic);
9084       else
9085          Set_Parent (Indic, Parent (N));
9086       end if;
9087
9088       Analyze (Indic);
9089       Set_Underlying_Full_View (Typ, Full_View (Subt));
9090    end Build_Underlying_Full_View;
9091
9092    -------------------------------
9093    -- Check_Abstract_Overriding --
9094    -------------------------------
9095
9096    procedure Check_Abstract_Overriding (T : Entity_Id) is
9097       Alias_Subp : Entity_Id;
9098       Elmt       : Elmt_Id;
9099       Op_List    : Elist_Id;
9100       Subp       : Entity_Id;
9101       Type_Def   : Node_Id;
9102
9103       procedure Check_Pragma_Implemented (Subp : Entity_Id);
9104       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
9105       --  which has pragma Implemented already set. Check whether Subp's entity
9106       --  kind conforms to the implementation kind of the overridden routine.
9107
9108       procedure Check_Pragma_Implemented
9109         (Subp       : Entity_Id;
9110          Iface_Subp : Entity_Id);
9111       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
9112       --  Iface_Subp and both entities have pragma Implemented already set on
9113       --  them. Check whether the two implementation kinds are conforming.
9114
9115       procedure Inherit_Pragma_Implemented
9116         (Subp       : Entity_Id;
9117          Iface_Subp : Entity_Id);
9118       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
9119       --  subprogram Iface_Subp which has been marked by pragma Implemented.
9120       --  Propagate the implementation kind of Iface_Subp to Subp.
9121
9122       ------------------------------
9123       -- Check_Pragma_Implemented --
9124       ------------------------------
9125
9126       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
9127          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
9128          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
9129          Subp_Alias  : constant Entity_Id := Alias (Subp);
9130          Contr_Typ   : Entity_Id;
9131          Impl_Subp   : Entity_Id;
9132
9133       begin
9134          --  Subp must have an alias since it is a hidden entity used to link
9135          --  an interface subprogram to its overriding counterpart.
9136
9137          pragma Assert (Present (Subp_Alias));
9138
9139          --  Handle aliases to synchronized wrappers
9140
9141          Impl_Subp := Subp_Alias;
9142
9143          if Is_Primitive_Wrapper (Impl_Subp) then
9144             Impl_Subp := Wrapped_Entity (Impl_Subp);
9145          end if;
9146
9147          --  Extract the type of the controlling formal
9148
9149          Contr_Typ := Etype (First_Formal (Subp_Alias));
9150
9151          if Is_Concurrent_Record_Type (Contr_Typ) then
9152             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
9153          end if;
9154
9155          --  An interface subprogram whose implementation kind is By_Entry must
9156          --  be implemented by an entry.
9157
9158          if Impl_Kind = Name_By_Entry
9159            and then Ekind (Impl_Subp) /= E_Entry
9160          then
9161             Error_Msg_Node_2 := Iface_Alias;
9162             Error_Msg_NE
9163               ("type & must implement abstract subprogram & with an entry",
9164                Subp_Alias, Contr_Typ);
9165
9166          elsif Impl_Kind = Name_By_Protected_Procedure then
9167
9168             --  An interface subprogram whose implementation kind is By_
9169             --  Protected_Procedure cannot be implemented by a primitive
9170             --  procedure of a task type.
9171
9172             if Ekind (Contr_Typ) /= E_Protected_Type then
9173                Error_Msg_Node_2 := Contr_Typ;
9174                Error_Msg_NE
9175                  ("interface subprogram & cannot be implemented by a " &
9176                   "primitive procedure of task type &", Subp_Alias,
9177                   Iface_Alias);
9178
9179             --  An interface subprogram whose implementation kind is By_
9180             --  Protected_Procedure must be implemented by a procedure.
9181
9182             elsif Ekind (Impl_Subp) /= E_Procedure then
9183                Error_Msg_Node_2 := Iface_Alias;
9184                Error_Msg_NE
9185                  ("type & must implement abstract subprogram & with a " &
9186                   "procedure", Subp_Alias, Contr_Typ);
9187             end if;
9188          end if;
9189       end Check_Pragma_Implemented;
9190
9191       ------------------------------
9192       -- Check_Pragma_Implemented --
9193       ------------------------------
9194
9195       procedure Check_Pragma_Implemented
9196         (Subp       : Entity_Id;
9197          Iface_Subp : Entity_Id)
9198       is
9199          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
9200          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
9201
9202       begin
9203          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
9204          --  and overriding subprogram are different. In general this is an
9205          --  error except when the implementation kind of the overridden
9206          --  subprograms is By_Any or Optional.
9207
9208          if Iface_Kind /= Subp_Kind
9209            and then Iface_Kind /= Name_By_Any
9210            and then Iface_Kind /= Name_Optional
9211          then
9212             if Iface_Kind = Name_By_Entry then
9213                Error_Msg_N
9214                  ("incompatible implementation kind, overridden subprogram " &
9215                   "is marked By_Entry", Subp);
9216             else
9217                Error_Msg_N
9218                  ("incompatible implementation kind, overridden subprogram " &
9219                   "is marked By_Protected_Procedure", Subp);
9220             end if;
9221          end if;
9222       end Check_Pragma_Implemented;
9223
9224       --------------------------------
9225       -- Inherit_Pragma_Implemented --
9226       --------------------------------
9227
9228       procedure Inherit_Pragma_Implemented
9229         (Subp       : Entity_Id;
9230          Iface_Subp : Entity_Id)
9231       is
9232          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
9233          Loc        : constant Source_Ptr := Sloc (Subp);
9234          Impl_Prag  : Node_Id;
9235
9236       begin
9237          --  Since the implementation kind is stored as a representation item
9238          --  rather than a flag, create a pragma node.
9239
9240          Impl_Prag :=
9241            Make_Pragma (Loc,
9242              Chars                        => Name_Implemented,
9243              Pragma_Argument_Associations => New_List (
9244                Make_Pragma_Argument_Association (Loc,
9245                  Expression => New_Reference_To (Subp, Loc)),
9246
9247                Make_Pragma_Argument_Association (Loc,
9248                  Expression => Make_Identifier (Loc, Iface_Kind))));
9249
9250          --  The pragma doesn't need to be analyzed because it is internally
9251          --  built. It is safe to directly register it as a rep item since we
9252          --  are only interested in the characters of the implementation kind.
9253
9254          Record_Rep_Item (Subp, Impl_Prag);
9255       end Inherit_Pragma_Implemented;
9256
9257    --  Start of processing for Check_Abstract_Overriding
9258
9259    begin
9260       Op_List := Primitive_Operations (T);
9261
9262       --  Loop to check primitive operations
9263
9264       Elmt := First_Elmt (Op_List);
9265       while Present (Elmt) loop
9266          Subp := Node (Elmt);
9267          Alias_Subp := Alias (Subp);
9268
9269          --  Inherited subprograms are identified by the fact that they do not
9270          --  come from source, and the associated source location is the
9271          --  location of the first subtype of the derived type.
9272
9273          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
9274          --  subprograms that "require overriding".
9275
9276          --  Special exception, do not complain about failure to override the
9277          --  stream routines _Input and _Output, as well as the primitive
9278          --  operations used in dispatching selects since we always provide
9279          --  automatic overridings for these subprograms.
9280
9281          --  Also ignore this rule for convention CIL since .NET libraries
9282          --  do bizarre things with interfaces???
9283
9284          --  The partial view of T may have been a private extension, for
9285          --  which inherited functions dispatching on result are abstract.
9286          --  If the full view is a null extension, there is no need for
9287          --  overriding in Ada 2005, but wrappers need to be built for them
9288          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
9289
9290          if Is_Null_Extension (T)
9291            and then Has_Controlling_Result (Subp)
9292            and then Ada_Version >= Ada_2005
9293            and then Present (Alias_Subp)
9294            and then not Comes_From_Source (Subp)
9295            and then not Is_Abstract_Subprogram (Alias_Subp)
9296            and then not Is_Access_Type (Etype (Subp))
9297          then
9298             null;
9299
9300          --  Ada 2005 (AI-251): Internal entities of interfaces need no
9301          --  processing because this check is done with the aliased
9302          --  entity
9303
9304          elsif Present (Interface_Alias (Subp)) then
9305             null;
9306
9307          elsif (Is_Abstract_Subprogram (Subp)
9308                  or else Requires_Overriding (Subp)
9309                  or else
9310                    (Has_Controlling_Result (Subp)
9311                      and then Present (Alias_Subp)
9312                      and then not Comes_From_Source (Subp)
9313                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
9314            and then not Is_TSS (Subp, TSS_Stream_Input)
9315            and then not Is_TSS (Subp, TSS_Stream_Output)
9316            and then not Is_Abstract_Type (T)
9317            and then Convention (T) /= Convention_CIL
9318            and then not Is_Predefined_Interface_Primitive (Subp)
9319
9320             --  Ada 2005 (AI-251): Do not consider hidden entities associated
9321             --  with abstract interface types because the check will be done
9322             --  with the aliased entity (otherwise we generate a duplicated
9323             --  error message).
9324
9325            and then not Present (Interface_Alias (Subp))
9326          then
9327             if Present (Alias_Subp) then
9328
9329                --  Only perform the check for a derived subprogram when the
9330                --  type has an explicit record extension. This avoids incorrect
9331                --  flagging of abstract subprograms for the case of a type
9332                --  without an extension that is derived from a formal type
9333                --  with a tagged actual (can occur within a private part).
9334
9335                --  Ada 2005 (AI-391): In the case of an inherited function with
9336                --  a controlling result of the type, the rule does not apply if
9337                --  the type is a null extension (unless the parent function
9338                --  itself is abstract, in which case the function must still be
9339                --  be overridden). The expander will generate an overriding
9340                --  wrapper function calling the parent subprogram (see
9341                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
9342
9343                Type_Def := Type_Definition (Parent (T));
9344
9345                if Nkind (Type_Def) = N_Derived_Type_Definition
9346                  and then Present (Record_Extension_Part (Type_Def))
9347                  and then
9348                    (Ada_Version < Ada_2005
9349                       or else not Is_Null_Extension (T)
9350                       or else Ekind (Subp) = E_Procedure
9351                       or else not Has_Controlling_Result (Subp)
9352                       or else Is_Abstract_Subprogram (Alias_Subp)
9353                       or else Requires_Overriding (Subp)
9354                       or else Is_Access_Type (Etype (Subp)))
9355                then
9356                   --  Avoid reporting error in case of abstract predefined
9357                   --  primitive inherited from interface type because the
9358                   --  body of internally generated predefined primitives
9359                   --  of tagged types are generated later by Freeze_Type
9360
9361                   if Is_Interface (Root_Type (T))
9362                     and then Is_Abstract_Subprogram (Subp)
9363                     and then Is_Predefined_Dispatching_Operation (Subp)
9364                     and then not Comes_From_Source (Ultimate_Alias (Subp))
9365                   then
9366                      null;
9367
9368                   else
9369                      Error_Msg_NE
9370                        ("type must be declared abstract or & overridden",
9371                         T, Subp);
9372
9373                      --  Traverse the whole chain of aliased subprograms to
9374                      --  complete the error notification. This is especially
9375                      --  useful for traceability of the chain of entities when
9376                      --  the subprogram corresponds with an interface
9377                      --  subprogram (which may be defined in another package).
9378
9379                      if Present (Alias_Subp) then
9380                         declare
9381                            E : Entity_Id;
9382
9383                         begin
9384                            E := Subp;
9385                            while Present (Alias (E)) loop
9386
9387                               --  Avoid reporting redundant errors on entities
9388                               --  inherited from interfaces
9389
9390                               if Sloc (E) /= Sloc (T) then
9391                                  Error_Msg_Sloc := Sloc (E);
9392                                  Error_Msg_NE
9393                                    ("\& has been inherited #", T, Subp);
9394                               end if;
9395
9396                               E := Alias (E);
9397                            end loop;
9398
9399                            Error_Msg_Sloc := Sloc (E);
9400
9401                            --  AI05-0068: report if there is an overriding
9402                            --  non-abstract subprogram that is invisible.
9403
9404                            if Is_Hidden (E)
9405                              and then not Is_Abstract_Subprogram (E)
9406                            then
9407                               Error_Msg_NE
9408                                 ("\& subprogram# is not visible",
9409                                  T, Subp);
9410
9411                            else
9412                               Error_Msg_NE
9413                                 ("\& has been inherited from subprogram #",
9414                                  T, Subp);
9415                            end if;
9416                         end;
9417                      end if;
9418                   end if;
9419
9420                --  Ada 2005 (AI-345): Protected or task type implementing
9421                --  abstract interfaces.
9422
9423                elsif Is_Concurrent_Record_Type (T)
9424                  and then Present (Interfaces (T))
9425                then
9426                   --  The controlling formal of Subp must be of mode "out",
9427                   --  "in out" or an access-to-variable to be overridden.
9428
9429                   if Ekind (First_Formal (Subp)) = E_In_Parameter
9430                     and then Ekind (Subp) /= E_Function
9431                   then
9432                      if not Is_Predefined_Dispatching_Operation (Subp)
9433                        and then Is_Protected_Type
9434                                   (Corresponding_Concurrent_Type (T))
9435                      then
9436                         Error_Msg_PT (T, Subp);
9437                      end if;
9438
9439                   --  Some other kind of overriding failure
9440
9441                   else
9442                      Error_Msg_NE
9443                        ("interface subprogram & must be overridden",
9444                         T, Subp);
9445
9446                      --  Examine primitive operations of synchronized type,
9447                      --  to find homonyms that have the wrong profile.
9448
9449                      declare
9450                         Prim : Entity_Id;
9451
9452                      begin
9453                         Prim :=
9454                           First_Entity (Corresponding_Concurrent_Type (T));
9455                         while Present (Prim) loop
9456                            if Chars (Prim) = Chars (Subp) then
9457                               Error_Msg_NE
9458                                 ("profile is not type conformant with "
9459                                    & "prefixed view profile of "
9460                                    & "inherited operation&", Prim, Subp);
9461                            end if;
9462
9463                            Next_Entity (Prim);
9464                         end loop;
9465                      end;
9466                   end if;
9467                end if;
9468
9469             else
9470                Error_Msg_Node_2 := T;
9471                Error_Msg_N
9472                  ("abstract subprogram& not allowed for type&", Subp);
9473
9474                --  Also post unconditional warning on the type (unconditional
9475                --  so that if there are more than one of these cases, we get
9476                --  them all, and not just the first one).
9477
9478                Error_Msg_Node_2 := Subp;
9479                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
9480             end if;
9481          end if;
9482
9483          --  Ada 2012 (AI05-0030): Perform some checks related to pragma
9484          --  Implemented
9485
9486          --  Subp is an expander-generated procedure which maps an interface
9487          --  alias to a protected wrapper. The interface alias is flagged by
9488          --  pragma Implemented. Ensure that Subp is a procedure when the
9489          --  implementation kind is By_Protected_Procedure or an entry when
9490          --  By_Entry.
9491
9492          if Ada_Version >= Ada_2012
9493            and then Is_Hidden (Subp)
9494            and then Present (Interface_Alias (Subp))
9495            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
9496          then
9497             Check_Pragma_Implemented (Subp);
9498          end if;
9499
9500          --  Subp is an interface primitive which overrides another interface
9501          --  primitive marked with pragma Implemented.
9502
9503          if Ada_Version >= Ada_2012
9504            and then Present (Overridden_Operation (Subp))
9505            and then Has_Rep_Pragma
9506                       (Overridden_Operation (Subp), Name_Implemented)
9507          then
9508             --  If the overriding routine is also marked by Implemented, check
9509             --  that the two implementation kinds are conforming.
9510
9511             if Has_Rep_Pragma (Subp, Name_Implemented) then
9512                Check_Pragma_Implemented
9513                  (Subp       => Subp,
9514                   Iface_Subp => Overridden_Operation (Subp));
9515
9516             --  Otherwise the overriding routine inherits the implementation
9517             --  kind from the overridden subprogram.
9518
9519             else
9520                Inherit_Pragma_Implemented
9521                  (Subp       => Subp,
9522                   Iface_Subp => Overridden_Operation (Subp));
9523             end if;
9524          end if;
9525
9526          --  If the operation is a wrapper for a synchronized primitive, it
9527          --  may be called indirectly through a dispatching select. We assume
9528          --  that it will be referenced elsewhere indirectly, and suppress
9529          --  warnings about an unused entity.
9530
9531          if Is_Primitive_Wrapper (Subp)
9532            and then Present (Wrapped_Entity (Subp))
9533          then
9534             Set_Referenced (Wrapped_Entity (Subp));
9535          end if;
9536
9537          Next_Elmt (Elmt);
9538       end loop;
9539    end Check_Abstract_Overriding;
9540
9541    ------------------------------------------------
9542    -- Check_Access_Discriminant_Requires_Limited --
9543    ------------------------------------------------
9544
9545    procedure Check_Access_Discriminant_Requires_Limited
9546      (D   : Node_Id;
9547       Loc : Node_Id)
9548    is
9549    begin
9550       --  A discriminant_specification for an access discriminant shall appear
9551       --  only in the declaration for a task or protected type, or for a type
9552       --  with the reserved word 'limited' in its definition or in one of its
9553       --  ancestors (RM 3.7(10)).
9554
9555       --  AI-0063: The proper condition is that type must be immutably limited,
9556       --  or else be a partial view.
9557
9558       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
9559          if Is_Immutably_Limited_Type (Current_Scope)
9560            or else
9561              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
9562                and then Limited_Present (Parent (Current_Scope)))
9563          then
9564             null;
9565
9566          else
9567             Error_Msg_N
9568               ("access discriminants allowed only for limited types", Loc);
9569          end if;
9570       end if;
9571    end Check_Access_Discriminant_Requires_Limited;
9572
9573    -----------------------------------
9574    -- Check_Aliased_Component_Types --
9575    -----------------------------------
9576
9577    procedure Check_Aliased_Component_Types (T : Entity_Id) is
9578       C : Entity_Id;
9579
9580    begin
9581       --  ??? Also need to check components of record extensions, but not
9582       --  components of protected types (which are always limited).
9583
9584       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
9585       --  types to be unconstrained. This is safe because it is illegal to
9586       --  create access subtypes to such types with explicit discriminant
9587       --  constraints.
9588
9589       if not Is_Limited_Type (T) then
9590          if Ekind (T) = E_Record_Type then
9591             C := First_Component (T);
9592             while Present (C) loop
9593                if Is_Aliased (C)
9594                  and then Has_Discriminants (Etype (C))
9595                  and then not Is_Constrained (Etype (C))
9596                  and then not In_Instance_Body
9597                  and then Ada_Version < Ada_2005
9598                then
9599                   Error_Msg_N
9600                     ("aliased component must be constrained (RM 3.6(11))",
9601                       C);
9602                end if;
9603
9604                Next_Component (C);
9605             end loop;
9606
9607          elsif Ekind (T) = E_Array_Type then
9608             if Has_Aliased_Components (T)
9609               and then Has_Discriminants (Component_Type (T))
9610               and then not Is_Constrained (Component_Type (T))
9611               and then not In_Instance_Body
9612               and then Ada_Version < Ada_2005
9613             then
9614                Error_Msg_N
9615                  ("aliased component type must be constrained (RM 3.6(11))",
9616                     T);
9617             end if;
9618          end if;
9619       end if;
9620    end Check_Aliased_Component_Types;
9621
9622    ----------------------
9623    -- Check_Completion --
9624    ----------------------
9625
9626    procedure Check_Completion (Body_Id : Node_Id := Empty) is
9627       E : Entity_Id;
9628
9629       procedure Post_Error;
9630       --  Post error message for lack of completion for entity E
9631
9632       ----------------
9633       -- Post_Error --
9634       ----------------
9635
9636       procedure Post_Error is
9637
9638          procedure Missing_Body;
9639          --  Output missing body message
9640
9641          ------------------
9642          -- Missing_Body --
9643          ------------------
9644
9645          procedure Missing_Body is
9646          begin
9647             --  Spec is in same unit, so we can post on spec
9648
9649             if In_Same_Source_Unit (Body_Id, E) then
9650                Error_Msg_N ("missing body for &", E);
9651
9652             --  Spec is in a separate unit, so we have to post on the body
9653
9654             else
9655                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
9656             end if;
9657          end Missing_Body;
9658
9659       --  Start of processing for Post_Error
9660
9661       begin
9662          if not Comes_From_Source (E) then
9663
9664             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
9665                --  It may be an anonymous protected type created for a
9666                --  single variable. Post error on variable, if present.
9667
9668                declare
9669                   Var : Entity_Id;
9670
9671                begin
9672                   Var := First_Entity (Current_Scope);
9673                   while Present (Var) loop
9674                      exit when Etype (Var) = E
9675                        and then Comes_From_Source (Var);
9676
9677                      Next_Entity (Var);
9678                   end loop;
9679
9680                   if Present (Var) then
9681                      E := Var;
9682                   end if;
9683                end;
9684             end if;
9685          end if;
9686
9687          --  If a generated entity has no completion, then either previous
9688          --  semantic errors have disabled the expansion phase, or else we had
9689          --  missing subunits, or else we are compiling without expansion,
9690          --  or else something is very wrong.
9691
9692          if not Comes_From_Source (E) then
9693             pragma Assert
9694               (Serious_Errors_Detected > 0
9695                 or else Configurable_Run_Time_Violations > 0
9696                 or else Subunits_Missing
9697                 or else not Expander_Active);
9698             return;
9699
9700          --  Here for source entity
9701
9702          else
9703             --  Here if no body to post the error message, so we post the error
9704             --  on the declaration that has no completion. This is not really
9705             --  the right place to post it, think about this later ???
9706
9707             if No (Body_Id) then
9708                if Is_Type (E) then
9709                   Error_Msg_NE
9710                     ("missing full declaration for }", Parent (E), E);
9711                else
9712                   Error_Msg_NE ("missing body for &", Parent (E), E);
9713                end if;
9714
9715             --  Package body has no completion for a declaration that appears
9716             --  in the corresponding spec. Post error on the body, with a
9717             --  reference to the non-completed declaration.
9718
9719             else
9720                Error_Msg_Sloc := Sloc (E);
9721
9722                if Is_Type (E) then
9723                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
9724
9725                elsif Is_Overloadable (E)
9726                  and then Current_Entity_In_Scope (E) /= E
9727                then
9728                   --  It may be that the completion is mistyped and appears as
9729                   --  a distinct overloading of the entity.
9730
9731                   declare
9732                      Candidate : constant Entity_Id :=
9733                                    Current_Entity_In_Scope (E);
9734                      Decl      : constant Node_Id :=
9735                                    Unit_Declaration_Node (Candidate);
9736
9737                   begin
9738                      if Is_Overloadable (Candidate)
9739                        and then Ekind (Candidate) = Ekind (E)
9740                        and then Nkind (Decl) = N_Subprogram_Body
9741                        and then Acts_As_Spec (Decl)
9742                      then
9743                         Check_Type_Conformant (Candidate, E);
9744
9745                      else
9746                         Missing_Body;
9747                      end if;
9748                   end;
9749
9750                else
9751                   Missing_Body;
9752                end if;
9753             end if;
9754          end if;
9755       end Post_Error;
9756
9757    --  Start of processing for Check_Completion
9758
9759    begin
9760       E := First_Entity (Current_Scope);
9761       while Present (E) loop
9762          if Is_Intrinsic_Subprogram (E) then
9763             null;
9764
9765          --  The following situation requires special handling: a child unit
9766          --  that appears in the context clause of the body of its parent:
9767
9768          --    procedure Parent.Child (...);
9769
9770          --    with Parent.Child;
9771          --    package body Parent is
9772
9773          --  Here Parent.Child appears as a local entity, but should not be
9774          --  flagged as requiring completion, because it is a compilation
9775          --  unit.
9776
9777          --  Ignore missing completion for a subprogram that does not come from
9778          --  source (including the _Call primitive operation of RAS types,
9779          --  which has to have the flag Comes_From_Source for other purposes):
9780          --  we assume that the expander will provide the missing completion.
9781          --  In case of previous errors, other expansion actions that provide
9782          --  bodies for null procedures with not be invoked, so inhibit message
9783          --  in those cases.
9784
9785          --  Note that E_Operator is not in the list that follows, because
9786          --  this kind is reserved for predefined operators, that are
9787          --  intrinsic and do not need completion.
9788
9789          elsif     Ekind (E) = E_Function
9790            or else Ekind (E) = E_Procedure
9791            or else Ekind (E) = E_Generic_Function
9792            or else Ekind (E) = E_Generic_Procedure
9793          then
9794             if Has_Completion (E) then
9795                null;
9796
9797             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
9798                null;
9799
9800             elsif Is_Subprogram (E)
9801               and then (not Comes_From_Source (E)
9802                          or else Chars (E) = Name_uCall)
9803             then
9804                null;
9805
9806             elsif
9807                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
9808             then
9809                null;
9810
9811             elsif Nkind (Parent (E)) = N_Procedure_Specification
9812               and then Null_Present (Parent (E))
9813               and then Serious_Errors_Detected > 0
9814             then
9815                null;
9816
9817             else
9818                Post_Error;
9819             end if;
9820
9821          elsif Is_Entry (E) then
9822             if not Has_Completion (E) and then
9823               (Ekind (Scope (E)) = E_Protected_Object
9824                 or else Ekind (Scope (E)) = E_Protected_Type)
9825             then
9826                Post_Error;
9827             end if;
9828
9829          elsif Is_Package_Or_Generic_Package (E) then
9830             if Unit_Requires_Body (E) then
9831                if not Has_Completion (E)
9832                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
9833                                                        N_Compilation_Unit
9834                then
9835                   Post_Error;
9836                end if;
9837
9838             elsif not Is_Child_Unit (E) then
9839                May_Need_Implicit_Body (E);
9840             end if;
9841
9842          --  A formal incomplete type (Ada 2012) does not require a completion;
9843          --  other incomplete type declarations do.
9844
9845          elsif Ekind (E) = E_Incomplete_Type
9846            and then No (Underlying_Type (E))
9847            and then not Is_Generic_Type (E)
9848          then
9849             Post_Error;
9850
9851          elsif (Ekind (E) = E_Task_Type or else
9852                 Ekind (E) = E_Protected_Type)
9853            and then not Has_Completion (E)
9854          then
9855             Post_Error;
9856
9857          --  A single task declared in the current scope is a constant, verify
9858          --  that the body of its anonymous type is in the same scope. If the
9859          --  task is defined elsewhere, this may be a renaming declaration for
9860          --  which no completion is needed.
9861
9862          elsif Ekind (E) = E_Constant
9863            and then Ekind (Etype (E)) = E_Task_Type
9864            and then not Has_Completion (Etype (E))
9865            and then Scope (Etype (E)) = Current_Scope
9866          then
9867             Post_Error;
9868
9869          elsif Ekind (E) = E_Protected_Object
9870            and then not Has_Completion (Etype (E))
9871          then
9872             Post_Error;
9873
9874          elsif Ekind (E) = E_Record_Type then
9875             if Is_Tagged_Type (E) then
9876                Check_Abstract_Overriding (E);
9877                Check_Conventions (E);
9878             end if;
9879
9880             Check_Aliased_Component_Types (E);
9881
9882          elsif Ekind (E) = E_Array_Type then
9883             Check_Aliased_Component_Types (E);
9884
9885          end if;
9886
9887          Next_Entity (E);
9888       end loop;
9889    end Check_Completion;
9890
9891    ------------------------------------
9892    -- Check_CPP_Type_Has_No_Defaults --
9893    ------------------------------------
9894
9895    procedure Check_CPP_Type_Has_No_Defaults (T : Entity_Id) is
9896       Tdef  : constant Node_Id := Type_Definition (Declaration_Node (T));
9897       Clist : Node_Id;
9898       Comp  : Node_Id;
9899
9900    begin
9901       --  Obtain the component list
9902
9903       if Nkind (Tdef) = N_Record_Definition then
9904          Clist := Component_List (Tdef);
9905       else pragma Assert (Nkind (Tdef) = N_Derived_Type_Definition);
9906          Clist := Component_List (Record_Extension_Part (Tdef));
9907       end if;
9908
9909       --  Check all components to ensure no default expressions
9910
9911       if Present (Clist) then
9912          Comp := First (Component_Items (Clist));
9913          while Present (Comp) loop
9914             if Present (Expression (Comp)) then
9915                Error_Msg_N
9916                  ("component of imported 'C'P'P type cannot have "
9917                   & "default expression", Expression (Comp));
9918             end if;
9919
9920             Next (Comp);
9921          end loop;
9922       end if;
9923    end Check_CPP_Type_Has_No_Defaults;
9924
9925    ----------------------------
9926    -- Check_Delta_Expression --
9927    ----------------------------
9928
9929    procedure Check_Delta_Expression (E : Node_Id) is
9930    begin
9931       if not (Is_Real_Type (Etype (E))) then
9932          Wrong_Type (E, Any_Real);
9933
9934       elsif not Is_OK_Static_Expression (E) then
9935          Flag_Non_Static_Expr
9936            ("non-static expression used for delta value!", E);
9937
9938       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9939          Error_Msg_N ("delta expression must be positive", E);
9940
9941       else
9942          return;
9943       end if;
9944
9945       --  If any of above errors occurred, then replace the incorrect
9946       --  expression by the real 0.1, which should prevent further errors.
9947
9948       Rewrite (E,
9949         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9950       Analyze_And_Resolve (E, Standard_Float);
9951    end Check_Delta_Expression;
9952
9953    -----------------------------
9954    -- Check_Digits_Expression --
9955    -----------------------------
9956
9957    procedure Check_Digits_Expression (E : Node_Id) is
9958    begin
9959       if not (Is_Integer_Type (Etype (E))) then
9960          Wrong_Type (E, Any_Integer);
9961
9962       elsif not Is_OK_Static_Expression (E) then
9963          Flag_Non_Static_Expr
9964            ("non-static expression used for digits value!", E);
9965
9966       elsif Expr_Value (E) <= 0 then
9967          Error_Msg_N ("digits value must be greater than zero", E);
9968
9969       else
9970          return;
9971       end if;
9972
9973       --  If any of above errors occurred, then replace the incorrect
9974       --  expression by the integer 1, which should prevent further errors.
9975
9976       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9977       Analyze_And_Resolve (E, Standard_Integer);
9978
9979    end Check_Digits_Expression;
9980
9981    --------------------------
9982    -- Check_Initialization --
9983    --------------------------
9984
9985    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9986    begin
9987       if Is_Limited_Type (T)
9988         and then not In_Instance
9989         and then not In_Inlined_Body
9990       then
9991          if not OK_For_Limited_Init (T, Exp) then
9992
9993             --  In GNAT mode, this is just a warning, to allow it to be evilly
9994             --  turned off. Otherwise it is a real error.
9995
9996             if GNAT_Mode then
9997                Error_Msg_N
9998                  ("?cannot initialize entities of limited type!", Exp);
9999
10000             elsif Ada_Version < Ada_2005 then
10001
10002                --  The side effect removal machinery may generate illegal Ada
10003                --  code to avoid the usage of access types and 'reference in
10004                --  SPARK mode. Since this is legal code with respect to theorem
10005                --  proving, do not emit the error.
10006
10007                if SPARK_Mode
10008                  and then Nkind (Exp) = N_Function_Call
10009                  and then Nkind (Parent (Exp)) = N_Object_Declaration
10010                  and then not Comes_From_Source
10011                                 (Defining_Identifier (Parent (Exp)))
10012                then
10013                   null;
10014
10015                else
10016                   Error_Msg_N
10017                     ("cannot initialize entities of limited type", Exp);
10018                   Explain_Limited_Type (T, Exp);
10019                end if;
10020
10021             else
10022                --  Specialize error message according to kind of illegal
10023                --  initial expression.
10024
10025                if Nkind (Exp) = N_Type_Conversion
10026                  and then Nkind (Expression (Exp)) = N_Function_Call
10027                then
10028                   Error_Msg_N
10029                     ("illegal context for call"
10030                       & " to function with limited result", Exp);
10031
10032                else
10033                   Error_Msg_N
10034                     ("initialization of limited object requires aggregate "
10035                       & "or function call",  Exp);
10036                end if;
10037             end if;
10038          end if;
10039       end if;
10040    end Check_Initialization;
10041
10042    ----------------------
10043    -- Check_Interfaces --
10044    ----------------------
10045
10046    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
10047       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
10048
10049       Iface       : Node_Id;
10050       Iface_Def   : Node_Id;
10051       Iface_Typ   : Entity_Id;
10052       Parent_Node : Node_Id;
10053
10054       Is_Task : Boolean := False;
10055       --  Set True if parent type or any progenitor is a task interface
10056
10057       Is_Protected : Boolean := False;
10058       --  Set True if parent type or any progenitor is a protected interface
10059
10060       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
10061       --  Check that a progenitor is compatible with declaration.
10062       --  Error is posted on Error_Node.
10063
10064       ------------------
10065       -- Check_Ifaces --
10066       ------------------
10067
10068       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
10069          Iface_Id : constant Entity_Id :=
10070                       Defining_Identifier (Parent (Iface_Def));
10071          Type_Def : Node_Id;
10072
10073       begin
10074          if Nkind (N) = N_Private_Extension_Declaration then
10075             Type_Def := N;
10076          else
10077             Type_Def := Type_Definition (N);
10078          end if;
10079
10080          if Is_Task_Interface (Iface_Id) then
10081             Is_Task := True;
10082
10083          elsif Is_Protected_Interface (Iface_Id) then
10084             Is_Protected := True;
10085          end if;
10086
10087          if Is_Synchronized_Interface (Iface_Id) then
10088
10089             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
10090             --  extension derived from a synchronized interface must explicitly
10091             --  be declared synchronized, because the full view will be a
10092             --  synchronized type.
10093
10094             if Nkind (N) = N_Private_Extension_Declaration then
10095                if not Synchronized_Present (N) then
10096                   Error_Msg_NE
10097                     ("private extension of& must be explicitly synchronized",
10098                       N, Iface_Id);
10099                end if;
10100
10101             --  However, by 3.9.4(16/2), a full type that is a record extension
10102             --  is never allowed to derive from a synchronized interface (note
10103             --  that interfaces must be excluded from this check, because those
10104             --  are represented by derived type definitions in some cases).
10105
10106             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
10107               and then not Interface_Present (Type_Definition (N))
10108             then
10109                Error_Msg_N ("record extension cannot derive from synchronized"
10110                              & " interface", Error_Node);
10111             end if;
10112          end if;
10113
10114          --  Check that the characteristics of the progenitor are compatible
10115          --  with the explicit qualifier in the declaration.
10116          --  The check only applies to qualifiers that come from source.
10117          --  Limited_Present also appears in the declaration of corresponding
10118          --  records, and the check does not apply to them.
10119
10120          if Limited_Present (Type_Def)
10121            and then not
10122              Is_Concurrent_Record_Type (Defining_Identifier (N))
10123          then
10124             if Is_Limited_Interface (Parent_Type)
10125               and then not Is_Limited_Interface (Iface_Id)
10126             then
10127                Error_Msg_NE
10128                  ("progenitor& must be limited interface",
10129                    Error_Node, Iface_Id);
10130
10131             elsif
10132               (Task_Present (Iface_Def)
10133                 or else Protected_Present (Iface_Def)
10134                 or else Synchronized_Present (Iface_Def))
10135               and then Nkind (N) /= N_Private_Extension_Declaration
10136               and then not Error_Posted (N)
10137             then
10138                Error_Msg_NE
10139                  ("progenitor& must be limited interface",
10140                    Error_Node, Iface_Id);
10141             end if;
10142
10143          --  Protected interfaces can only inherit from limited, synchronized
10144          --  or protected interfaces.
10145
10146          elsif Nkind (N) = N_Full_Type_Declaration
10147            and then  Protected_Present (Type_Def)
10148          then
10149             if Limited_Present (Iface_Def)
10150               or else Synchronized_Present (Iface_Def)
10151               or else Protected_Present (Iface_Def)
10152             then
10153                null;
10154
10155             elsif Task_Present (Iface_Def) then
10156                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
10157                             & " from task interface", Error_Node);
10158
10159             else
10160                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
10161                             & " from non-limited interface", Error_Node);
10162             end if;
10163
10164          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
10165          --  limited and synchronized.
10166
10167          elsif Synchronized_Present (Type_Def) then
10168             if Limited_Present (Iface_Def)
10169               or else Synchronized_Present (Iface_Def)
10170             then
10171                null;
10172
10173             elsif Protected_Present (Iface_Def)
10174               and then Nkind (N) /= N_Private_Extension_Declaration
10175             then
10176                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
10177                             & " from protected interface", Error_Node);
10178
10179             elsif Task_Present (Iface_Def)
10180               and then Nkind (N) /= N_Private_Extension_Declaration
10181             then
10182                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
10183                             & " from task interface", Error_Node);
10184
10185             elsif not Is_Limited_Interface (Iface_Id) then
10186                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
10187                             & " from non-limited interface", Error_Node);
10188             end if;
10189
10190          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
10191          --  synchronized or task interfaces.
10192
10193          elsif Nkind (N) = N_Full_Type_Declaration
10194            and then Task_Present (Type_Def)
10195          then
10196             if Limited_Present (Iface_Def)
10197               or else Synchronized_Present (Iface_Def)
10198               or else Task_Present (Iface_Def)
10199             then
10200                null;
10201
10202             elsif Protected_Present (Iface_Def) then
10203                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
10204                             & " protected interface", Error_Node);
10205
10206             else
10207                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
10208                             & " non-limited interface", Error_Node);
10209             end if;
10210          end if;
10211       end Check_Ifaces;
10212
10213    --  Start of processing for Check_Interfaces
10214
10215    begin
10216       if Is_Interface (Parent_Type) then
10217          if Is_Task_Interface (Parent_Type) then
10218             Is_Task := True;
10219
10220          elsif Is_Protected_Interface (Parent_Type) then
10221             Is_Protected := True;
10222          end if;
10223       end if;
10224
10225       if Nkind (N) = N_Private_Extension_Declaration then
10226
10227          --  Check that progenitors are compatible with declaration
10228
10229          Iface := First (Interface_List (Def));
10230          while Present (Iface) loop
10231             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
10232
10233             Parent_Node := Parent (Base_Type (Iface_Typ));
10234             Iface_Def   := Type_Definition (Parent_Node);
10235
10236             if not Is_Interface (Iface_Typ) then
10237                Diagnose_Interface (Iface, Iface_Typ);
10238
10239             else
10240                Check_Ifaces (Iface_Def, Iface);
10241             end if;
10242
10243             Next (Iface);
10244          end loop;
10245
10246          if Is_Task and Is_Protected then
10247             Error_Msg_N
10248               ("type cannot derive from task and protected interface", N);
10249          end if;
10250
10251          return;
10252       end if;
10253
10254       --  Full type declaration of derived type.
10255       --  Check compatibility with parent if it is interface type
10256
10257       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
10258         and then Is_Interface (Parent_Type)
10259       then
10260          Parent_Node := Parent (Parent_Type);
10261
10262          --  More detailed checks for interface varieties
10263
10264          Check_Ifaces
10265            (Iface_Def  => Type_Definition (Parent_Node),
10266             Error_Node => Subtype_Indication (Type_Definition (N)));
10267       end if;
10268
10269       Iface := First (Interface_List (Def));
10270       while Present (Iface) loop
10271          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
10272
10273          Parent_Node := Parent (Base_Type (Iface_Typ));
10274          Iface_Def   := Type_Definition (Parent_Node);
10275
10276          if not Is_Interface (Iface_Typ) then
10277             Diagnose_Interface (Iface, Iface_Typ);
10278
10279          else
10280             --  "The declaration of a specific descendant of an interface
10281             --   type freezes the interface type" RM 13.14
10282
10283             Freeze_Before (N, Iface_Typ);
10284             Check_Ifaces (Iface_Def, Error_Node => Iface);
10285          end if;
10286
10287          Next (Iface);
10288       end loop;
10289
10290       if Is_Task and Is_Protected then
10291          Error_Msg_N
10292            ("type cannot derive from task and protected interface", N);
10293       end if;
10294    end Check_Interfaces;
10295
10296    ------------------------------------
10297    -- Check_Or_Process_Discriminants --
10298    ------------------------------------
10299
10300    --  If an incomplete or private type declaration was already given for the
10301    --  type, the discriminants may have already been processed if they were
10302    --  present on the incomplete declaration. In this case a full conformance
10303    --  check has been performed in Find_Type_Name, and we then recheck here
10304    --  some properties that can't be checked on the partial view alone.
10305    --  Otherwise we call Process_Discriminants.
10306
10307    procedure Check_Or_Process_Discriminants
10308      (N    : Node_Id;
10309       T    : Entity_Id;
10310       Prev : Entity_Id := Empty)
10311    is
10312    begin
10313       if Has_Discriminants (T) then
10314
10315          --  Discriminants are already set on T if they were already present
10316          --  on the partial view. Make them visible to component declarations.
10317
10318          declare
10319             D : Entity_Id;
10320             --  Discriminant on T (full view) referencing expr on partial view
10321
10322             Prev_D : Entity_Id;
10323             --  Entity of corresponding discriminant on partial view
10324
10325             New_D : Node_Id;
10326             --  Discriminant specification for full view, expression is the
10327             --  syntactic copy on full view (which has been checked for
10328             --  conformance with partial view), only used here to post error
10329             --  message.
10330
10331          begin
10332             D     := First_Discriminant (T);
10333             New_D := First (Discriminant_Specifications (N));
10334             while Present (D) loop
10335                Prev_D := Current_Entity (D);
10336                Set_Current_Entity (D);
10337                Set_Is_Immediately_Visible (D);
10338                Set_Homonym (D, Prev_D);
10339
10340                --  Handle the case where there is an untagged partial view and
10341                --  the full view is tagged: must disallow discriminants with
10342                --  defaults, unless compiling for Ada 2012, which allows a
10343                --  limited tagged type to have defaulted discriminants (see
10344                --  AI05-0214). However, suppress the error here if it was
10345                --  already reported on the default expression of the partial
10346                --  view.
10347
10348                if Is_Tagged_Type (T)
10349                     and then Present (Expression (Parent (D)))
10350                     and then (not Is_Limited_Type (Current_Scope)
10351                                or else Ada_Version < Ada_2012)
10352                     and then not Error_Posted (Expression (Parent (D)))
10353                then
10354                   if Ada_Version >= Ada_2012 then
10355                      Error_Msg_N
10356                        ("discriminants of nonlimited tagged type cannot have"
10357                           & " defaults",
10358                         Expression (New_D));
10359                   else
10360                      Error_Msg_N
10361                        ("discriminants of tagged type cannot have defaults",
10362                         Expression (New_D));
10363                   end if;
10364                end if;
10365
10366                --  Ada 2005 (AI-230): Access discriminant allowed in
10367                --  non-limited record types.
10368
10369                if Ada_Version < Ada_2005 then
10370
10371                   --  This restriction gets applied to the full type here. It
10372                   --  has already been applied earlier to the partial view.
10373
10374                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
10375                end if;
10376
10377                Next_Discriminant (D);
10378                Next (New_D);
10379             end loop;
10380          end;
10381
10382       elsif Present (Discriminant_Specifications (N)) then
10383          Process_Discriminants (N, Prev);
10384       end if;
10385    end Check_Or_Process_Discriminants;
10386
10387    ----------------------
10388    -- Check_Real_Bound --
10389    ----------------------
10390
10391    procedure Check_Real_Bound (Bound : Node_Id) is
10392    begin
10393       if not Is_Real_Type (Etype (Bound)) then
10394          Error_Msg_N
10395            ("bound in real type definition must be of real type", Bound);
10396
10397       elsif not Is_OK_Static_Expression (Bound) then
10398          Flag_Non_Static_Expr
10399            ("non-static expression used for real type bound!", Bound);
10400
10401       else
10402          return;
10403       end if;
10404
10405       Rewrite
10406         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
10407       Analyze (Bound);
10408       Resolve (Bound, Standard_Float);
10409    end Check_Real_Bound;
10410
10411    ------------------------------
10412    -- Complete_Private_Subtype --
10413    ------------------------------
10414
10415    procedure Complete_Private_Subtype
10416      (Priv        : Entity_Id;
10417       Full        : Entity_Id;
10418       Full_Base   : Entity_Id;
10419       Related_Nod : Node_Id)
10420    is
10421       Save_Next_Entity : Entity_Id;
10422       Save_Homonym     : Entity_Id;
10423
10424    begin
10425       --  Set semantic attributes for (implicit) private subtype completion.
10426       --  If the full type has no discriminants, then it is a copy of the full
10427       --  view of the base. Otherwise, it is a subtype of the base with a
10428       --  possible discriminant constraint. Save and restore the original
10429       --  Next_Entity field of full to ensure that the calls to Copy_Node
10430       --  do not corrupt the entity chain.
10431
10432       --  Note that the type of the full view is the same entity as the type of
10433       --  the partial view. In this fashion, the subtype has access to the
10434       --  correct view of the parent.
10435
10436       Save_Next_Entity := Next_Entity (Full);
10437       Save_Homonym     := Homonym (Priv);
10438
10439       case Ekind (Full_Base) is
10440          when E_Record_Type    |
10441               E_Record_Subtype |
10442               Class_Wide_Kind  |
10443               Private_Kind     |
10444               Task_Kind        |
10445               Protected_Kind   =>
10446             Copy_Node (Priv, Full);
10447
10448             Set_Has_Discriminants
10449                              (Full, Has_Discriminants (Full_Base));
10450             Set_Has_Unknown_Discriminants
10451                              (Full, Has_Unknown_Discriminants (Full_Base));
10452             Set_First_Entity (Full, First_Entity (Full_Base));
10453             Set_Last_Entity  (Full, Last_Entity (Full_Base));
10454
10455             --  If the underlying base type is constrained, we know that the
10456             --  full view of the subtype is constrained as well (the converse
10457             --  is not necessarily true).
10458
10459             if Is_Constrained (Full_Base) then
10460                Set_Is_Constrained (Full);
10461             end if;
10462
10463          when others =>
10464             Copy_Node (Full_Base, Full);
10465
10466             Set_Chars         (Full, Chars (Priv));
10467             Conditional_Delay (Full, Priv);
10468             Set_Sloc          (Full, Sloc (Priv));
10469       end case;
10470
10471       Set_Next_Entity               (Full, Save_Next_Entity);
10472       Set_Homonym                   (Full, Save_Homonym);
10473       Set_Associated_Node_For_Itype (Full, Related_Nod);
10474
10475       --  Set common attributes for all subtypes: kind, convention, etc.
10476
10477       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
10478       Set_Convention (Full, Convention (Full_Base));
10479
10480       --  The Etype of the full view is inconsistent. Gigi needs to see the
10481       --  structural full view,  which is what the current scheme gives:
10482       --  the Etype of the full view is the etype of the full base. However,
10483       --  if the full base is a derived type, the full view then looks like
10484       --  a subtype of the parent, not a subtype of the full base. If instead
10485       --  we write:
10486
10487       --       Set_Etype (Full, Full_Base);
10488
10489       --  then we get inconsistencies in the front-end (confusion between
10490       --  views). Several outstanding bugs are related to this ???
10491
10492       Set_Is_First_Subtype (Full, False);
10493       Set_Scope            (Full, Scope (Priv));
10494       Set_Size_Info        (Full, Full_Base);
10495       Set_RM_Size          (Full, RM_Size (Full_Base));
10496       Set_Is_Itype         (Full);
10497
10498       --  A subtype of a private-type-without-discriminants, whose full-view
10499       --  has discriminants with default expressions, is not constrained!
10500
10501       if not Has_Discriminants (Priv) then
10502          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
10503
10504          if Has_Discriminants (Full_Base) then
10505             Set_Discriminant_Constraint
10506               (Full, Discriminant_Constraint (Full_Base));
10507
10508             --  The partial view may have been indefinite, the full view
10509             --  might not be.
10510
10511             Set_Has_Unknown_Discriminants
10512               (Full, Has_Unknown_Discriminants (Full_Base));
10513          end if;
10514       end if;
10515
10516       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
10517       Set_Depends_On_Private (Full, Has_Private_Component (Full));
10518
10519       --  Freeze the private subtype entity if its parent is delayed, and not
10520       --  already frozen. We skip this processing if the type is an anonymous
10521       --  subtype of a record component, or is the corresponding record of a
10522       --  protected type, since ???
10523
10524       if not Is_Type (Scope (Full)) then
10525          Set_Has_Delayed_Freeze (Full,
10526            Has_Delayed_Freeze (Full_Base)
10527              and then (not Is_Frozen (Full_Base)));
10528       end if;
10529
10530       Set_Freeze_Node (Full, Empty);
10531       Set_Is_Frozen (Full, False);
10532       Set_Full_View (Priv, Full);
10533
10534       if Has_Discriminants (Full) then
10535          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
10536          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
10537
10538          if Has_Unknown_Discriminants (Full) then
10539             Set_Discriminant_Constraint (Full, No_Elist);
10540          end if;
10541       end if;
10542
10543       if Ekind (Full_Base) = E_Record_Type
10544         and then Has_Discriminants (Full_Base)
10545         and then Has_Discriminants (Priv) -- might not, if errors
10546         and then not Has_Unknown_Discriminants (Priv)
10547         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
10548       then
10549          Create_Constrained_Components
10550            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
10551
10552       --  If the full base is itself derived from private, build a congruent
10553       --  subtype of its underlying type, for use by the back end. For a
10554       --  constrained record component, the declaration cannot be placed on
10555       --  the component list, but it must nevertheless be built an analyzed, to
10556       --  supply enough information for Gigi to compute the size of component.
10557
10558       elsif Ekind (Full_Base) in Private_Kind
10559         and then Is_Derived_Type (Full_Base)
10560         and then Has_Discriminants (Full_Base)
10561         and then (Ekind (Current_Scope) /= E_Record_Subtype)
10562       then
10563          if not Is_Itype (Priv)
10564            and then
10565              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
10566          then
10567             Build_Underlying_Full_View
10568               (Parent (Priv), Full, Etype (Full_Base));
10569
10570          elsif Nkind (Related_Nod) = N_Component_Declaration then
10571             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
10572          end if;
10573
10574       elsif Is_Record_Type (Full_Base) then
10575
10576          --  Show Full is simply a renaming of Full_Base
10577
10578          Set_Cloned_Subtype (Full, Full_Base);
10579       end if;
10580
10581       --  It is unsafe to share the bounds of a scalar type, because the Itype
10582       --  is elaborated on demand, and if a bound is non-static then different
10583       --  orders of elaboration in different units will lead to different
10584       --  external symbols.
10585
10586       if Is_Scalar_Type (Full_Base) then
10587          Set_Scalar_Range (Full,
10588            Make_Range (Sloc (Related_Nod),
10589              Low_Bound  =>
10590                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
10591              High_Bound =>
10592                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
10593
10594          --  This completion inherits the bounds of the full parent, but if
10595          --  the parent is an unconstrained floating point type, so is the
10596          --  completion.
10597
10598          if Is_Floating_Point_Type (Full_Base) then
10599             Set_Includes_Infinities
10600              (Scalar_Range (Full), Has_Infinities (Full_Base));
10601          end if;
10602       end if;
10603
10604       --  ??? It seems that a lot of fields are missing that should be copied
10605       --  from Full_Base to Full. Here are some that are introduced in a
10606       --  non-disruptive way but a cleanup is necessary.
10607
10608       if Is_Tagged_Type (Full_Base) then
10609          Set_Is_Tagged_Type (Full);
10610          Set_Direct_Primitive_Operations (Full,
10611            Direct_Primitive_Operations (Full_Base));
10612
10613          --  Inherit class_wide type of full_base in case the partial view was
10614          --  not tagged. Otherwise it has already been created when the private
10615          --  subtype was analyzed.
10616
10617          if No (Class_Wide_Type (Full)) then
10618             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
10619          end if;
10620
10621       --  If this is a subtype of a protected or task type, constrain its
10622       --  corresponding record, unless this is a subtype without constraints,
10623       --  i.e. a simple renaming as with an actual subtype in an instance.
10624
10625       elsif Is_Concurrent_Type (Full_Base) then
10626          if Has_Discriminants (Full)
10627            and then Present (Corresponding_Record_Type (Full_Base))
10628            and then
10629              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
10630          then
10631             Set_Corresponding_Record_Type (Full,
10632               Constrain_Corresponding_Record
10633                 (Full, Corresponding_Record_Type (Full_Base),
10634                   Related_Nod, Full_Base));
10635
10636          else
10637             Set_Corresponding_Record_Type (Full,
10638               Corresponding_Record_Type (Full_Base));
10639          end if;
10640       end if;
10641
10642       --  Link rep item chain, and also setting of Has_Predicates from private
10643       --  subtype to full subtype, since we will need these on the full subtype
10644       --  to create the predicate function. Note that the full subtype may
10645       --  already have rep items, inherited from the full view of the base
10646       --  type, so we must be sure not to overwrite these entries.
10647
10648       declare
10649          Append    : Boolean;
10650          Item      : Node_Id;
10651          Next_Item : Node_Id;
10652
10653       begin
10654          Item := First_Rep_Item (Full);
10655
10656          --  If no existing rep items on full type, we can just link directly
10657          --  to the list of items on the private type.
10658
10659          if No (Item) then
10660             Set_First_Rep_Item (Full, First_Rep_Item (Priv));
10661
10662          --  Otherwise, search to the end of items currently linked to the full
10663          --  subtype and append the private items to the end. However, if Priv
10664          --  and Full already have the same list of rep items, then the append
10665          --  is not done, as that would create a circularity.
10666
10667          elsif Item /= First_Rep_Item (Priv) then
10668             Append := True;
10669
10670             loop
10671                Next_Item := Next_Rep_Item (Item);
10672                exit when No (Next_Item);
10673                Item := Next_Item;
10674
10675                --  If the private view has aspect specifications, the full view
10676                --  inherits them. Since these aspects may already have been
10677                --  attached to the full view during derivation, do not append
10678                --  them if already present.
10679
10680                if Item = First_Rep_Item (Priv) then
10681                   Append := False;
10682                   exit;
10683                end if;
10684             end loop;
10685
10686             --  And link the private type items at the end of the chain
10687
10688             if Append then
10689                Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
10690             end if;
10691          end if;
10692       end;
10693
10694       --  Make sure Has_Predicates is set on full type if it is set on the
10695       --  private type. Note that it may already be set on the full type and
10696       --  if so, we don't want to unset it.
10697
10698       if Has_Predicates (Priv) then
10699          Set_Has_Predicates (Full);
10700       end if;
10701    end Complete_Private_Subtype;
10702
10703    ----------------------------
10704    -- Constant_Redeclaration --
10705    ----------------------------
10706
10707    procedure Constant_Redeclaration
10708      (Id : Entity_Id;
10709       N  : Node_Id;
10710       T  : out Entity_Id)
10711    is
10712       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
10713       Obj_Def : constant Node_Id := Object_Definition (N);
10714       New_T   : Entity_Id;
10715
10716       procedure Check_Possible_Deferred_Completion
10717         (Prev_Id      : Entity_Id;
10718          Prev_Obj_Def : Node_Id;
10719          Curr_Obj_Def : Node_Id);
10720       --  Determine whether the two object definitions describe the partial
10721       --  and the full view of a constrained deferred constant. Generate
10722       --  a subtype for the full view and verify that it statically matches
10723       --  the subtype of the partial view.
10724
10725       procedure Check_Recursive_Declaration (Typ : Entity_Id);
10726       --  If deferred constant is an access type initialized with an allocator,
10727       --  check whether there is an illegal recursion in the definition,
10728       --  through a default value of some record subcomponent. This is normally
10729       --  detected when generating init procs, but requires this additional
10730       --  mechanism when expansion is disabled.
10731
10732       ----------------------------------------
10733       -- Check_Possible_Deferred_Completion --
10734       ----------------------------------------
10735
10736       procedure Check_Possible_Deferred_Completion
10737         (Prev_Id      : Entity_Id;
10738          Prev_Obj_Def : Node_Id;
10739          Curr_Obj_Def : Node_Id)
10740       is
10741       begin
10742          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
10743            and then Present (Constraint (Prev_Obj_Def))
10744            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
10745            and then Present (Constraint (Curr_Obj_Def))
10746          then
10747             declare
10748                Loc    : constant Source_Ptr := Sloc (N);
10749                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
10750                Decl   : constant Node_Id    :=
10751                           Make_Subtype_Declaration (Loc,
10752                             Defining_Identifier => Def_Id,
10753                             Subtype_Indication  =>
10754                               Relocate_Node (Curr_Obj_Def));
10755
10756             begin
10757                Insert_Before_And_Analyze (N, Decl);
10758                Set_Etype (Id, Def_Id);
10759
10760                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
10761                   Error_Msg_Sloc := Sloc (Prev_Id);
10762                   Error_Msg_N ("subtype does not statically match deferred " &
10763                                "declaration#", N);
10764                end if;
10765             end;
10766          end if;
10767       end Check_Possible_Deferred_Completion;
10768
10769       ---------------------------------
10770       -- Check_Recursive_Declaration --
10771       ---------------------------------
10772
10773       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
10774          Comp : Entity_Id;
10775
10776       begin
10777          if Is_Record_Type (Typ) then
10778             Comp := First_Component (Typ);
10779             while Present (Comp) loop
10780                if Comes_From_Source (Comp) then
10781                   if Present (Expression (Parent (Comp)))
10782                     and then Is_Entity_Name (Expression (Parent (Comp)))
10783                     and then Entity (Expression (Parent (Comp))) = Prev
10784                   then
10785                      Error_Msg_Sloc := Sloc (Parent (Comp));
10786                      Error_Msg_NE
10787                        ("illegal circularity with declaration for&#",
10788                          N, Comp);
10789                      return;
10790
10791                   elsif Is_Record_Type (Etype (Comp)) then
10792                      Check_Recursive_Declaration (Etype (Comp));
10793                   end if;
10794                end if;
10795
10796                Next_Component (Comp);
10797             end loop;
10798          end if;
10799       end Check_Recursive_Declaration;
10800
10801    --  Start of processing for Constant_Redeclaration
10802
10803    begin
10804       if Nkind (Parent (Prev)) = N_Object_Declaration then
10805          if Nkind (Object_Definition
10806                      (Parent (Prev))) = N_Subtype_Indication
10807          then
10808             --  Find type of new declaration. The constraints of the two
10809             --  views must match statically, but there is no point in
10810             --  creating an itype for the full view.
10811
10812             if Nkind (Obj_Def) = N_Subtype_Indication then
10813                Find_Type (Subtype_Mark (Obj_Def));
10814                New_T := Entity (Subtype_Mark (Obj_Def));
10815
10816             else
10817                Find_Type (Obj_Def);
10818                New_T := Entity (Obj_Def);
10819             end if;
10820
10821             T := Etype (Prev);
10822
10823          else
10824             --  The full view may impose a constraint, even if the partial
10825             --  view does not, so construct the subtype.
10826
10827             New_T := Find_Type_Of_Object (Obj_Def, N);
10828             T     := New_T;
10829          end if;
10830
10831       else
10832          --  Current declaration is illegal, diagnosed below in Enter_Name
10833
10834          T := Empty;
10835          New_T := Any_Type;
10836       end if;
10837
10838       --  If previous full declaration or a renaming declaration exists, or if
10839       --  a homograph is present, let Enter_Name handle it, either with an
10840       --  error or with the removal of an overridden implicit subprogram.
10841
10842       if Ekind (Prev) /= E_Constant
10843         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
10844         or else Present (Expression (Parent (Prev)))
10845         or else Present (Full_View (Prev))
10846       then
10847          Enter_Name (Id);
10848
10849       --  Verify that types of both declarations match, or else that both types
10850       --  are anonymous access types whose designated subtypes statically match
10851       --  (as allowed in Ada 2005 by AI-385).
10852
10853       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
10854         and then
10855           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
10856              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
10857              or else Is_Access_Constant (Etype (New_T)) /=
10858                      Is_Access_Constant (Etype (Prev))
10859              or else Can_Never_Be_Null (Etype (New_T)) /=
10860                      Can_Never_Be_Null (Etype (Prev))
10861              or else Null_Exclusion_Present (Parent (Prev)) /=
10862                      Null_Exclusion_Present (Parent (Id))
10863              or else not Subtypes_Statically_Match
10864                            (Designated_Type (Etype (Prev)),
10865                             Designated_Type (Etype (New_T))))
10866       then
10867          Error_Msg_Sloc := Sloc (Prev);
10868          Error_Msg_N ("type does not match declaration#", N);
10869          Set_Full_View (Prev, Id);
10870          Set_Etype (Id, Any_Type);
10871
10872       elsif
10873         Null_Exclusion_Present (Parent (Prev))
10874           and then not Null_Exclusion_Present (N)
10875       then
10876          Error_Msg_Sloc := Sloc (Prev);
10877          Error_Msg_N ("null-exclusion does not match declaration#", N);
10878          Set_Full_View (Prev, Id);
10879          Set_Etype (Id, Any_Type);
10880
10881       --  If so, process the full constant declaration
10882
10883       else
10884          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
10885          --  the deferred declaration is constrained, then the subtype defined
10886          --  by the subtype_indication in the full declaration shall match it
10887          --  statically.
10888
10889          Check_Possible_Deferred_Completion
10890            (Prev_Id      => Prev,
10891             Prev_Obj_Def => Object_Definition (Parent (Prev)),
10892             Curr_Obj_Def => Obj_Def);
10893
10894          Set_Full_View (Prev, Id);
10895          Set_Is_Public (Id, Is_Public (Prev));
10896          Set_Is_Internal (Id);
10897          Append_Entity (Id, Current_Scope);
10898
10899          --  Check ALIASED present if present before (RM 7.4(7))
10900
10901          if Is_Aliased (Prev)
10902            and then not Aliased_Present (N)
10903          then
10904             Error_Msg_Sloc := Sloc (Prev);
10905             Error_Msg_N ("ALIASED required (see declaration#)", N);
10906          end if;
10907
10908          --  Check that placement is in private part and that the incomplete
10909          --  declaration appeared in the visible part.
10910
10911          if Ekind (Current_Scope) = E_Package
10912            and then not In_Private_Part (Current_Scope)
10913          then
10914             Error_Msg_Sloc := Sloc (Prev);
10915             Error_Msg_N
10916               ("full constant for declaration#"
10917                & " must be in private part", N);
10918
10919          elsif Ekind (Current_Scope) = E_Package
10920            and then
10921              List_Containing (Parent (Prev)) /=
10922                Visible_Declarations (Package_Specification (Current_Scope))
10923          then
10924             Error_Msg_N
10925               ("deferred constant must be declared in visible part",
10926                  Parent (Prev));
10927          end if;
10928
10929          if Is_Access_Type (T)
10930            and then Nkind (Expression (N)) = N_Allocator
10931          then
10932             Check_Recursive_Declaration (Designated_Type (T));
10933          end if;
10934
10935          --  A deferred constant is a visible entity. If type has invariants,
10936          --  verify that the initial value satisfies them.
10937
10938          if Has_Invariants (T) and then Present (Invariant_Procedure (T)) then
10939             Insert_After (N,
10940               Make_Invariant_Call (New_Occurrence_Of (Prev, Sloc (N))));
10941          end if;
10942       end if;
10943    end Constant_Redeclaration;
10944
10945    ----------------------
10946    -- Constrain_Access --
10947    ----------------------
10948
10949    procedure Constrain_Access
10950      (Def_Id      : in out Entity_Id;
10951       S           : Node_Id;
10952       Related_Nod : Node_Id)
10953    is
10954       T             : constant Entity_Id := Entity (Subtype_Mark (S));
10955       Desig_Type    : constant Entity_Id := Designated_Type (T);
10956       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
10957       Constraint_OK : Boolean := True;
10958
10959       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
10960       --  Simple predicate to test for defaulted discriminants
10961       --  Shouldn't this be in sem_util???
10962
10963       ---------------------------------
10964       -- Has_Defaulted_Discriminants --
10965       ---------------------------------
10966
10967       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
10968       begin
10969          return Has_Discriminants (Typ)
10970           and then Present (First_Discriminant (Typ))
10971           and then Present
10972             (Discriminant_Default_Value (First_Discriminant (Typ)));
10973       end Has_Defaulted_Discriminants;
10974
10975    --  Start of processing for Constrain_Access
10976
10977    begin
10978       if Is_Array_Type (Desig_Type) then
10979          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
10980
10981       elsif (Is_Record_Type (Desig_Type)
10982               or else Is_Incomplete_Or_Private_Type (Desig_Type))
10983         and then not Is_Constrained (Desig_Type)
10984       then
10985          --  ??? The following code is a temporary kludge to ignore a
10986          --  discriminant constraint on access type if it is constraining
10987          --  the current record. Avoid creating the implicit subtype of the
10988          --  record we are currently compiling since right now, we cannot
10989          --  handle these. For now, just return the access type itself.
10990
10991          if Desig_Type = Current_Scope
10992            and then No (Def_Id)
10993          then
10994             Set_Ekind (Desig_Subtype, E_Record_Subtype);
10995             Def_Id := Entity (Subtype_Mark (S));
10996
10997             --  This call added to ensure that the constraint is analyzed
10998             --  (needed for a B test). Note that we still return early from
10999             --  this procedure to avoid recursive processing. ???
11000
11001             Constrain_Discriminated_Type
11002               (Desig_Subtype, S, Related_Nod, For_Access => True);
11003             return;
11004          end if;
11005
11006          --  Enforce rule that the constraint is illegal if there is an
11007          --  unconstrained view of the designated type. This means that the
11008          --  partial view (either a private type declaration or a derivation
11009          --  from a private type) has no discriminants. (Defect Report
11010          --  8652/0008, Technical Corrigendum 1, checked by ACATS B371001).
11011
11012          --  Rule updated for Ada 2005: the private type is said to have
11013          --  a constrained partial view, given that objects of the type
11014          --  can be declared. Furthermore, the rule applies to all access
11015          --  types, unlike the rule concerning default discriminants (see
11016          --  RM 3.7.1(7/3))
11017
11018          if (Ekind (T) = E_General_Access_Type
11019               or else Ada_Version >= Ada_2005)
11020            and then Has_Private_Declaration (Desig_Type)
11021            and then In_Open_Scopes (Scope (Desig_Type))
11022            and then Has_Discriminants (Desig_Type)
11023          then
11024             declare
11025                Pack  : constant Node_Id :=
11026                          Unit_Declaration_Node (Scope (Desig_Type));
11027                Decls : List_Id;
11028                Decl  : Node_Id;
11029
11030             begin
11031                if Nkind (Pack) = N_Package_Declaration then
11032                   Decls := Visible_Declarations (Specification (Pack));
11033                   Decl := First (Decls);
11034                   while Present (Decl) loop
11035                      if (Nkind (Decl) = N_Private_Type_Declaration
11036                           and then
11037                             Chars (Defining_Identifier (Decl)) =
11038                                                      Chars (Desig_Type))
11039
11040                        or else
11041                         (Nkind (Decl) = N_Full_Type_Declaration
11042                           and then
11043                             Chars (Defining_Identifier (Decl)) =
11044                                                      Chars (Desig_Type)
11045                           and then Is_Derived_Type (Desig_Type)
11046                           and then
11047                             Has_Private_Declaration (Etype (Desig_Type)))
11048                      then
11049                         if No (Discriminant_Specifications (Decl)) then
11050                            Error_Msg_N
11051                             ("cannot constrain access type if designated " &
11052                                "type has constrained partial view", S);
11053                         end if;
11054
11055                         exit;
11056                      end if;
11057
11058                      Next (Decl);
11059                   end loop;
11060                end if;
11061             end;
11062          end if;
11063
11064          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
11065            For_Access => True);
11066
11067       elsif (Is_Task_Type (Desig_Type)
11068               or else Is_Protected_Type (Desig_Type))
11069         and then not Is_Constrained (Desig_Type)
11070       then
11071          Constrain_Concurrent
11072            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
11073
11074       else
11075          Error_Msg_N ("invalid constraint on access type", S);
11076          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
11077          Constraint_OK := False;
11078       end if;
11079
11080       if No (Def_Id) then
11081          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
11082       else
11083          Set_Ekind (Def_Id, E_Access_Subtype);
11084       end if;
11085
11086       if Constraint_OK then
11087          Set_Etype (Def_Id, Base_Type (T));
11088
11089          if Is_Private_Type (Desig_Type) then
11090             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
11091          end if;
11092       else
11093          Set_Etype (Def_Id, Any_Type);
11094       end if;
11095
11096       Set_Size_Info                (Def_Id, T);
11097       Set_Is_Constrained           (Def_Id, Constraint_OK);
11098       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
11099       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
11100       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
11101
11102       Conditional_Delay (Def_Id, T);
11103
11104       --  AI-363 : Subtypes of general access types whose designated types have
11105       --  default discriminants are disallowed. In instances, the rule has to
11106       --  be checked against the actual, of which T is the subtype. In a
11107       --  generic body, the rule is checked assuming that the actual type has
11108       --  defaulted discriminants.
11109
11110       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
11111          if Ekind (Base_Type (T)) = E_General_Access_Type
11112            and then Has_Defaulted_Discriminants (Desig_Type)
11113          then
11114             if Ada_Version < Ada_2005 then
11115                Error_Msg_N
11116                  ("access subtype of general access type would not " &
11117                   "be allowed in Ada 2005?y?", S);
11118             else
11119                Error_Msg_N
11120                  ("access subtype of general access type not allowed", S);
11121             end if;
11122
11123             Error_Msg_N ("\discriminants have defaults", S);
11124
11125          elsif Is_Access_Type (T)
11126            and then Is_Generic_Type (Desig_Type)
11127            and then Has_Discriminants (Desig_Type)
11128            and then In_Package_Body (Current_Scope)
11129          then
11130             if Ada_Version < Ada_2005 then
11131                Error_Msg_N
11132                  ("access subtype would not be allowed in generic body " &
11133                   "in Ada 2005?y?", S);
11134             else
11135                Error_Msg_N
11136                  ("access subtype not allowed in generic body", S);
11137             end if;
11138
11139             Error_Msg_N
11140               ("\designated type is a discriminated formal", S);
11141          end if;
11142       end if;
11143    end Constrain_Access;
11144
11145    ---------------------
11146    -- Constrain_Array --
11147    ---------------------
11148
11149    procedure Constrain_Array
11150      (Def_Id      : in out Entity_Id;
11151       SI          : Node_Id;
11152       Related_Nod : Node_Id;
11153       Related_Id  : Entity_Id;
11154       Suffix      : Character)
11155    is
11156       C                     : constant Node_Id := Constraint (SI);
11157       Number_Of_Constraints : Nat := 0;
11158       Index                 : Node_Id;
11159       S, T                  : Entity_Id;
11160       Constraint_OK         : Boolean := True;
11161
11162    begin
11163       T := Entity (Subtype_Mark (SI));
11164
11165       if Ekind (T) in Access_Kind then
11166          T := Designated_Type (T);
11167       end if;
11168
11169       --  If an index constraint follows a subtype mark in a subtype indication
11170       --  then the type or subtype denoted by the subtype mark must not already
11171       --  impose an index constraint. The subtype mark must denote either an
11172       --  unconstrained array type or an access type whose designated type
11173       --  is such an array type... (RM 3.6.1)
11174
11175       if Is_Constrained (T) then
11176          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
11177          Constraint_OK := False;
11178
11179       else
11180          S := First (Constraints (C));
11181          while Present (S) loop
11182             Number_Of_Constraints := Number_Of_Constraints + 1;
11183             Next (S);
11184          end loop;
11185
11186          --  In either case, the index constraint must provide a discrete
11187          --  range for each index of the array type and the type of each
11188          --  discrete range must be the same as that of the corresponding
11189          --  index. (RM 3.6.1)
11190
11191          if Number_Of_Constraints /= Number_Dimensions (T) then
11192             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
11193             Constraint_OK := False;
11194
11195          else
11196             S := First (Constraints (C));
11197             Index := First_Index (T);
11198             Analyze (Index);
11199
11200             --  Apply constraints to each index type
11201
11202             for J in 1 .. Number_Of_Constraints loop
11203                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
11204                Next (Index);
11205                Next (S);
11206             end loop;
11207
11208          end if;
11209       end if;
11210
11211       if No (Def_Id) then
11212          Def_Id :=
11213            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
11214          Set_Parent (Def_Id, Related_Nod);
11215
11216       else
11217          Set_Ekind (Def_Id, E_Array_Subtype);
11218       end if;
11219
11220       Set_Size_Info      (Def_Id,                (T));
11221       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11222       Set_Etype          (Def_Id, Base_Type      (T));
11223
11224       if Constraint_OK then
11225          Set_First_Index (Def_Id, First (Constraints (C)));
11226       else
11227          Set_First_Index (Def_Id, First_Index (T));
11228       end if;
11229
11230       Set_Is_Constrained     (Def_Id, True);
11231       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
11232       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
11233
11234       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
11235       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
11236
11237       --  A subtype does not inherit the packed_array_type of is parent. We
11238       --  need to initialize the attribute because if Def_Id is previously
11239       --  analyzed through a limited_with clause, it will have the attributes
11240       --  of an incomplete type, one of which is an Elist that overlaps the
11241       --  Packed_Array_Type field.
11242
11243       Set_Packed_Array_Type (Def_Id, Empty);
11244
11245       --  Build a freeze node if parent still needs one. Also make sure that
11246       --  the Depends_On_Private status is set because the subtype will need
11247       --  reprocessing at the time the base type does, and also we must set a
11248       --  conditional delay.
11249
11250       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
11251       Conditional_Delay (Def_Id, T);
11252    end Constrain_Array;
11253
11254    ------------------------------
11255    -- Constrain_Component_Type --
11256    ------------------------------
11257
11258    function Constrain_Component_Type
11259      (Comp            : Entity_Id;
11260       Constrained_Typ : Entity_Id;
11261       Related_Node    : Node_Id;
11262       Typ             : Entity_Id;
11263       Constraints     : Elist_Id) return Entity_Id
11264    is
11265       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
11266       Compon_Type : constant Entity_Id := Etype (Comp);
11267       Array_Comp  : Node_Id;
11268
11269       function Build_Constrained_Array_Type
11270         (Old_Type : Entity_Id) return Entity_Id;
11271       --  If Old_Type is an array type, one of whose indexes is constrained
11272       --  by a discriminant, build an Itype whose constraint replaces the
11273       --  discriminant with its value in the constraint.
11274
11275       function Build_Constrained_Discriminated_Type
11276         (Old_Type : Entity_Id) return Entity_Id;
11277       --  Ditto for record components
11278
11279       function Build_Constrained_Access_Type
11280         (Old_Type : Entity_Id) return Entity_Id;
11281       --  Ditto for access types. Makes use of previous two functions, to
11282       --  constrain designated type.
11283
11284       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
11285       --  T is an array or discriminated type, C is a list of constraints
11286       --  that apply to T. This routine builds the constrained subtype.
11287
11288       function Is_Discriminant (Expr : Node_Id) return Boolean;
11289       --  Returns True if Expr is a discriminant
11290
11291       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
11292       --  Find the value of discriminant Discrim in Constraint
11293
11294       -----------------------------------
11295       -- Build_Constrained_Access_Type --
11296       -----------------------------------
11297
11298       function Build_Constrained_Access_Type
11299         (Old_Type : Entity_Id) return Entity_Id
11300       is
11301          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
11302          Itype         : Entity_Id;
11303          Desig_Subtype : Entity_Id;
11304          Scop          : Entity_Id;
11305
11306       begin
11307          --  if the original access type was not embedded in the enclosing
11308          --  type definition, there is no need to produce a new access
11309          --  subtype. In fact every access type with an explicit constraint
11310          --  generates an itype whose scope is the enclosing record.
11311
11312          if not Is_Type (Scope (Old_Type)) then
11313             return Old_Type;
11314
11315          elsif Is_Array_Type (Desig_Type) then
11316             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
11317
11318          elsif Has_Discriminants (Desig_Type) then
11319
11320             --  This may be an access type to an enclosing record type for
11321             --  which we are constructing the constrained components. Return
11322             --  the enclosing record subtype. This is not always correct,
11323             --  but avoids infinite recursion. ???
11324
11325             Desig_Subtype := Any_Type;
11326
11327             for J in reverse 0 .. Scope_Stack.Last loop
11328                Scop := Scope_Stack.Table (J).Entity;
11329
11330                if Is_Type (Scop)
11331                  and then Base_Type (Scop) = Base_Type (Desig_Type)
11332                then
11333                   Desig_Subtype := Scop;
11334                end if;
11335
11336                exit when not Is_Type (Scop);
11337             end loop;
11338
11339             if Desig_Subtype = Any_Type then
11340                Desig_Subtype :=
11341                  Build_Constrained_Discriminated_Type (Desig_Type);
11342             end if;
11343
11344          else
11345             return Old_Type;
11346          end if;
11347
11348          if Desig_Subtype /= Desig_Type then
11349
11350             --  The Related_Node better be here or else we won't be able
11351             --  to attach new itypes to a node in the tree.
11352
11353             pragma Assert (Present (Related_Node));
11354
11355             Itype := Create_Itype (E_Access_Subtype, Related_Node);
11356
11357             Set_Etype                    (Itype, Base_Type      (Old_Type));
11358             Set_Size_Info                (Itype,                (Old_Type));
11359             Set_Directly_Designated_Type (Itype, Desig_Subtype);
11360             Set_Depends_On_Private       (Itype, Has_Private_Component
11361                                                                 (Old_Type));
11362             Set_Is_Access_Constant       (Itype, Is_Access_Constant
11363                                                                 (Old_Type));
11364
11365             --  The new itype needs freezing when it depends on a not frozen
11366             --  type and the enclosing subtype needs freezing.
11367
11368             if Has_Delayed_Freeze (Constrained_Typ)
11369               and then not Is_Frozen (Constrained_Typ)
11370             then
11371                Conditional_Delay (Itype, Base_Type (Old_Type));
11372             end if;
11373
11374             return Itype;
11375
11376          else
11377             return Old_Type;
11378          end if;
11379       end Build_Constrained_Access_Type;
11380
11381       ----------------------------------
11382       -- Build_Constrained_Array_Type --
11383       ----------------------------------
11384
11385       function Build_Constrained_Array_Type
11386         (Old_Type : Entity_Id) return Entity_Id
11387       is
11388          Lo_Expr     : Node_Id;
11389          Hi_Expr     : Node_Id;
11390          Old_Index   : Node_Id;
11391          Range_Node  : Node_Id;
11392          Constr_List : List_Id;
11393
11394          Need_To_Create_Itype : Boolean := False;
11395
11396       begin
11397          Old_Index := First_Index (Old_Type);
11398          while Present (Old_Index) loop
11399             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
11400
11401             if Is_Discriminant (Lo_Expr)
11402               or else Is_Discriminant (Hi_Expr)
11403             then
11404                Need_To_Create_Itype := True;
11405             end if;
11406
11407             Next_Index (Old_Index);
11408          end loop;
11409
11410          if Need_To_Create_Itype then
11411             Constr_List := New_List;
11412
11413             Old_Index := First_Index (Old_Type);
11414             while Present (Old_Index) loop
11415                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
11416
11417                if Is_Discriminant (Lo_Expr) then
11418                   Lo_Expr := Get_Discr_Value (Lo_Expr);
11419                end if;
11420
11421                if Is_Discriminant (Hi_Expr) then
11422                   Hi_Expr := Get_Discr_Value (Hi_Expr);
11423                end if;
11424
11425                Range_Node :=
11426                  Make_Range
11427                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
11428
11429                Append (Range_Node, To => Constr_List);
11430
11431                Next_Index (Old_Index);
11432             end loop;
11433
11434             return Build_Subtype (Old_Type, Constr_List);
11435
11436          else
11437             return Old_Type;
11438          end if;
11439       end Build_Constrained_Array_Type;
11440
11441       ------------------------------------------
11442       -- Build_Constrained_Discriminated_Type --
11443       ------------------------------------------
11444
11445       function Build_Constrained_Discriminated_Type
11446         (Old_Type : Entity_Id) return Entity_Id
11447       is
11448          Expr           : Node_Id;
11449          Constr_List    : List_Id;
11450          Old_Constraint : Elmt_Id;
11451
11452          Need_To_Create_Itype : Boolean := False;
11453
11454       begin
11455          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
11456          while Present (Old_Constraint) loop
11457             Expr := Node (Old_Constraint);
11458
11459             if Is_Discriminant (Expr) then
11460                Need_To_Create_Itype := True;
11461             end if;
11462
11463             Next_Elmt (Old_Constraint);
11464          end loop;
11465
11466          if Need_To_Create_Itype then
11467             Constr_List := New_List;
11468
11469             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
11470             while Present (Old_Constraint) loop
11471                Expr := Node (Old_Constraint);
11472
11473                if Is_Discriminant (Expr) then
11474                   Expr := Get_Discr_Value (Expr);
11475                end if;
11476
11477                Append (New_Copy_Tree (Expr), To => Constr_List);
11478
11479                Next_Elmt (Old_Constraint);
11480             end loop;
11481
11482             return Build_Subtype (Old_Type, Constr_List);
11483
11484          else
11485             return Old_Type;
11486          end if;
11487       end Build_Constrained_Discriminated_Type;
11488
11489       -------------------
11490       -- Build_Subtype --
11491       -------------------
11492
11493       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
11494          Indic       : Node_Id;
11495          Subtyp_Decl : Node_Id;
11496          Def_Id      : Entity_Id;
11497          Btyp        : Entity_Id := Base_Type (T);
11498
11499       begin
11500          --  The Related_Node better be here or else we won't be able to
11501          --  attach new itypes to a node in the tree.
11502
11503          pragma Assert (Present (Related_Node));
11504
11505          --  If the view of the component's type is incomplete or private
11506          --  with unknown discriminants, then the constraint must be applied
11507          --  to the full type.
11508
11509          if Has_Unknown_Discriminants (Btyp)
11510            and then Present (Underlying_Type (Btyp))
11511          then
11512             Btyp := Underlying_Type (Btyp);
11513          end if;
11514
11515          Indic :=
11516            Make_Subtype_Indication (Loc,
11517              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
11518              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
11519
11520          Def_Id := Create_Itype (Ekind (T), Related_Node);
11521
11522          Subtyp_Decl :=
11523            Make_Subtype_Declaration (Loc,
11524              Defining_Identifier => Def_Id,
11525              Subtype_Indication  => Indic);
11526
11527          Set_Parent (Subtyp_Decl, Parent (Related_Node));
11528
11529          --  Itypes must be analyzed with checks off (see package Itypes)
11530
11531          Analyze (Subtyp_Decl, Suppress => All_Checks);
11532
11533          return Def_Id;
11534       end Build_Subtype;
11535
11536       ---------------------
11537       -- Get_Discr_Value --
11538       ---------------------
11539
11540       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
11541          D : Entity_Id;
11542          E : Elmt_Id;
11543
11544       begin
11545          --  The discriminant may be declared for the type, in which case we
11546          --  find it by iterating over the list of discriminants. If the
11547          --  discriminant is inherited from a parent type, it appears as the
11548          --  corresponding discriminant of the current type. This will be the
11549          --  case when constraining an inherited component whose constraint is
11550          --  given by a discriminant of the parent.
11551
11552          D := First_Discriminant (Typ);
11553          E := First_Elmt (Constraints);
11554
11555          while Present (D) loop
11556             if D = Entity (Discrim)
11557               or else D = CR_Discriminant (Entity (Discrim))
11558               or else Corresponding_Discriminant (D) = Entity (Discrim)
11559             then
11560                return Node (E);
11561             end if;
11562
11563             Next_Discriminant (D);
11564             Next_Elmt (E);
11565          end loop;
11566
11567          --  The Corresponding_Discriminant mechanism is incomplete, because
11568          --  the correspondence between new and old discriminants is not one
11569          --  to one: one new discriminant can constrain several old ones. In
11570          --  that case, scan sequentially the stored_constraint, the list of
11571          --  discriminants of the parents, and the constraints.
11572
11573          --  Previous code checked for the present of the Stored_Constraint
11574          --  list for the derived type, but did not use it at all. Should it
11575          --  be present when the component is a discriminated task type?
11576
11577          if Is_Derived_Type (Typ)
11578            and then Scope (Entity (Discrim)) = Etype (Typ)
11579          then
11580             D := First_Discriminant (Etype (Typ));
11581             E := First_Elmt (Constraints);
11582             while Present (D) loop
11583                if D = Entity (Discrim) then
11584                   return Node (E);
11585                end if;
11586
11587                Next_Discriminant (D);
11588                Next_Elmt (E);
11589             end loop;
11590          end if;
11591
11592          --  Something is wrong if we did not find the value
11593
11594          raise Program_Error;
11595       end Get_Discr_Value;
11596
11597       ---------------------
11598       -- Is_Discriminant --
11599       ---------------------
11600
11601       function Is_Discriminant (Expr : Node_Id) return Boolean is
11602          Discrim_Scope : Entity_Id;
11603
11604       begin
11605          if Denotes_Discriminant (Expr) then
11606             Discrim_Scope := Scope (Entity (Expr));
11607
11608             --  Either we have a reference to one of Typ's discriminants,
11609
11610             pragma Assert (Discrim_Scope = Typ
11611
11612                --  or to the discriminants of the parent type, in the case
11613                --  of a derivation of a tagged type with variants.
11614
11615                or else Discrim_Scope = Etype (Typ)
11616                or else Full_View (Discrim_Scope) = Etype (Typ)
11617
11618                --  or same as above for the case where the discriminants
11619                --  were declared in Typ's private view.
11620
11621                or else (Is_Private_Type (Discrim_Scope)
11622                         and then Chars (Discrim_Scope) = Chars (Typ))
11623
11624                --  or else we are deriving from the full view and the
11625                --  discriminant is declared in the private entity.
11626
11627                or else (Is_Private_Type (Typ)
11628                          and then Chars (Discrim_Scope) = Chars (Typ))
11629
11630                --  Or we are constrained the corresponding record of a
11631                --  synchronized type that completes a private declaration.
11632
11633                or else (Is_Concurrent_Record_Type (Typ)
11634                          and then
11635                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
11636
11637                --  or we have a class-wide type, in which case make sure the
11638                --  discriminant found belongs to the root type.
11639
11640                or else (Is_Class_Wide_Type (Typ)
11641                          and then Etype (Typ) = Discrim_Scope));
11642
11643             return True;
11644          end if;
11645
11646          --  In all other cases we have something wrong
11647
11648          return False;
11649       end Is_Discriminant;
11650
11651    --  Start of processing for Constrain_Component_Type
11652
11653    begin
11654       if Nkind (Parent (Comp)) = N_Component_Declaration
11655         and then Comes_From_Source (Parent (Comp))
11656         and then Comes_From_Source
11657           (Subtype_Indication (Component_Definition (Parent (Comp))))
11658         and then
11659           Is_Entity_Name
11660             (Subtype_Indication (Component_Definition (Parent (Comp))))
11661       then
11662          return Compon_Type;
11663
11664       elsif Is_Array_Type (Compon_Type) then
11665          Array_Comp := Build_Constrained_Array_Type (Compon_Type);
11666
11667          --  If the component of the parent is packed, and the record type is
11668          --  already frozen, as is the case for an itype, the component type
11669          --  itself will not be frozen, and the packed array type for it must
11670          --  be constructed explicitly. Since the creation of packed types is
11671          --  an expansion activity, we only do this if expansion is active.
11672
11673          if Expander_Active
11674            and then Is_Packed (Compon_Type)
11675            and then Is_Frozen (Current_Scope)
11676          then
11677             Create_Packed_Array_Type (Array_Comp);
11678          end if;
11679
11680          return Array_Comp;
11681
11682       elsif Has_Discriminants (Compon_Type) then
11683          return Build_Constrained_Discriminated_Type (Compon_Type);
11684
11685       elsif Is_Access_Type (Compon_Type) then
11686          return Build_Constrained_Access_Type (Compon_Type);
11687
11688       else
11689          return Compon_Type;
11690       end if;
11691    end Constrain_Component_Type;
11692
11693    --------------------------
11694    -- Constrain_Concurrent --
11695    --------------------------
11696
11697    --  For concurrent types, the associated record value type carries the same
11698    --  discriminants, so when we constrain a concurrent type, we must constrain
11699    --  the corresponding record type as well.
11700
11701    procedure Constrain_Concurrent
11702      (Def_Id      : in out Entity_Id;
11703       SI          : Node_Id;
11704       Related_Nod : Node_Id;
11705       Related_Id  : Entity_Id;
11706       Suffix      : Character)
11707    is
11708       --  Retrieve Base_Type to ensure getting to the concurrent type in the
11709       --  case of a private subtype (needed when only doing semantic analysis).
11710
11711       T_Ent : Entity_Id := Base_Type (Entity (Subtype_Mark (SI)));
11712       T_Val : Entity_Id;
11713
11714    begin
11715       if Ekind (T_Ent) in Access_Kind then
11716          T_Ent := Designated_Type (T_Ent);
11717       end if;
11718
11719       T_Val := Corresponding_Record_Type (T_Ent);
11720
11721       if Present (T_Val) then
11722
11723          if No (Def_Id) then
11724             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11725          end if;
11726
11727          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11728
11729          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
11730          Set_Corresponding_Record_Type (Def_Id,
11731            Constrain_Corresponding_Record
11732              (Def_Id, T_Val, Related_Nod, Related_Id));
11733
11734       else
11735          --  If there is no associated record, expansion is disabled and this
11736          --  is a generic context. Create a subtype in any case, so that
11737          --  semantic analysis can proceed.
11738
11739          if No (Def_Id) then
11740             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11741          end if;
11742
11743          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11744       end if;
11745    end Constrain_Concurrent;
11746
11747    ------------------------------------
11748    -- Constrain_Corresponding_Record --
11749    ------------------------------------
11750
11751    function Constrain_Corresponding_Record
11752      (Prot_Subt   : Entity_Id;
11753       Corr_Rec    : Entity_Id;
11754       Related_Nod : Node_Id;
11755       Related_Id  : Entity_Id) return Entity_Id
11756    is
11757       T_Sub : constant Entity_Id :=
11758                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
11759
11760    begin
11761       Set_Etype             (T_Sub, Corr_Rec);
11762       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
11763       Set_Is_Constrained    (T_Sub, True);
11764       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
11765       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
11766
11767       --  As elsewhere, we do not want to create a freeze node for this itype
11768       --  if it is created for a constrained component of an enclosing record
11769       --  because references to outer discriminants will appear out of scope.
11770
11771       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
11772          Conditional_Delay (T_Sub, Corr_Rec);
11773       else
11774          Set_Is_Frozen (T_Sub);
11775       end if;
11776
11777       if Has_Discriminants (Prot_Subt) then -- False only if errors.
11778          Set_Discriminant_Constraint
11779            (T_Sub, Discriminant_Constraint (Prot_Subt));
11780          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
11781          Create_Constrained_Components
11782            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
11783       end if;
11784
11785       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
11786
11787       return T_Sub;
11788    end Constrain_Corresponding_Record;
11789
11790    -----------------------
11791    -- Constrain_Decimal --
11792    -----------------------
11793
11794    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
11795       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
11796       C           : constant Node_Id    := Constraint (S);
11797       Loc         : constant Source_Ptr := Sloc (C);
11798       Range_Expr  : Node_Id;
11799       Digits_Expr : Node_Id;
11800       Digits_Val  : Uint;
11801       Bound_Val   : Ureal;
11802
11803    begin
11804       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
11805
11806       if Nkind (C) = N_Range_Constraint then
11807          Range_Expr := Range_Expression (C);
11808          Digits_Val := Digits_Value (T);
11809
11810       else
11811          pragma Assert (Nkind (C) = N_Digits_Constraint);
11812
11813          Check_SPARK_Restriction ("digits constraint is not allowed", S);
11814
11815          Digits_Expr := Digits_Expression (C);
11816          Analyze_And_Resolve (Digits_Expr, Any_Integer);
11817
11818          Check_Digits_Expression (Digits_Expr);
11819          Digits_Val := Expr_Value (Digits_Expr);
11820
11821          if Digits_Val > Digits_Value (T) then
11822             Error_Msg_N
11823                ("digits expression is incompatible with subtype", C);
11824             Digits_Val := Digits_Value (T);
11825          end if;
11826
11827          if Present (Range_Constraint (C)) then
11828             Range_Expr := Range_Expression (Range_Constraint (C));
11829          else
11830             Range_Expr := Empty;
11831          end if;
11832       end if;
11833
11834       Set_Etype            (Def_Id, Base_Type        (T));
11835       Set_Size_Info        (Def_Id,                  (T));
11836       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11837       Set_Delta_Value      (Def_Id, Delta_Value      (T));
11838       Set_Scale_Value      (Def_Id, Scale_Value      (T));
11839       Set_Small_Value      (Def_Id, Small_Value      (T));
11840       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
11841       Set_Digits_Value     (Def_Id, Digits_Val);
11842
11843       --  Manufacture range from given digits value if no range present
11844
11845       if No (Range_Expr) then
11846          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
11847          Range_Expr :=
11848            Make_Range (Loc,
11849              Low_Bound =>
11850                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
11851              High_Bound =>
11852                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
11853       end if;
11854
11855       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
11856       Set_Discrete_RM_Size (Def_Id);
11857
11858       --  Unconditionally delay the freeze, since we cannot set size
11859       --  information in all cases correctly until the freeze point.
11860
11861       Set_Has_Delayed_Freeze (Def_Id);
11862    end Constrain_Decimal;
11863
11864    ----------------------------------
11865    -- Constrain_Discriminated_Type --
11866    ----------------------------------
11867
11868    procedure Constrain_Discriminated_Type
11869      (Def_Id      : Entity_Id;
11870       S           : Node_Id;
11871       Related_Nod : Node_Id;
11872       For_Access  : Boolean := False)
11873    is
11874       E     : constant Entity_Id := Entity (Subtype_Mark (S));
11875       T     : Entity_Id;
11876       C     : Node_Id;
11877       Elist : Elist_Id := New_Elmt_List;
11878
11879       procedure Fixup_Bad_Constraint;
11880       --  This is called after finding a bad constraint, and after having
11881       --  posted an appropriate error message. The mission is to leave the
11882       --  entity T in as reasonable state as possible!
11883
11884       --------------------------
11885       -- Fixup_Bad_Constraint --
11886       --------------------------
11887
11888       procedure Fixup_Bad_Constraint is
11889       begin
11890          --  Set a reasonable Ekind for the entity. For an incomplete type,
11891          --  we can't do much, but for other types, we can set the proper
11892          --  corresponding subtype kind.
11893
11894          if Ekind (T) = E_Incomplete_Type then
11895             Set_Ekind (Def_Id, Ekind (T));
11896          else
11897             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
11898          end if;
11899
11900          --  Set Etype to the known type, to reduce chances of cascaded errors
11901
11902          Set_Etype (Def_Id, E);
11903          Set_Error_Posted (Def_Id);
11904       end Fixup_Bad_Constraint;
11905
11906    --  Start of processing for Constrain_Discriminated_Type
11907
11908    begin
11909       C := Constraint (S);
11910
11911       --  A discriminant constraint is only allowed in a subtype indication,
11912       --  after a subtype mark. This subtype mark must denote either a type
11913       --  with discriminants, or an access type whose designated type is a
11914       --  type with discriminants. A discriminant constraint specifies the
11915       --  values of these discriminants (RM 3.7.2(5)).
11916
11917       T := Base_Type (Entity (Subtype_Mark (S)));
11918
11919       if Ekind (T) in Access_Kind then
11920          T := Designated_Type (T);
11921       end if;
11922
11923       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
11924       --  Avoid generating an error for access-to-incomplete subtypes.
11925
11926       if Ada_Version >= Ada_2005
11927         and then Ekind (T) = E_Incomplete_Type
11928         and then Nkind (Parent (S)) = N_Subtype_Declaration
11929         and then not Is_Itype (Def_Id)
11930       then
11931          --  A little sanity check, emit an error message if the type
11932          --  has discriminants to begin with. Type T may be a regular
11933          --  incomplete type or imported via a limited with clause.
11934
11935          if Has_Discriminants (T)
11936            or else
11937              (From_With_Type (T)
11938                 and then Present (Non_Limited_View (T))
11939                 and then Nkind (Parent (Non_Limited_View (T))) =
11940                            N_Full_Type_Declaration
11941                 and then Present (Discriminant_Specifications
11942                           (Parent (Non_Limited_View (T)))))
11943          then
11944             Error_Msg_N
11945               ("(Ada 2005) incomplete subtype may not be constrained", C);
11946          else
11947             Error_Msg_N ("invalid constraint: type has no discriminant", C);
11948          end if;
11949
11950          Fixup_Bad_Constraint;
11951          return;
11952
11953       --  Check that the type has visible discriminants. The type may be
11954       --  a private type with unknown discriminants whose full view has
11955       --  discriminants which are invisible.
11956
11957       elsif not Has_Discriminants (T)
11958         or else
11959           (Has_Unknown_Discriminants (T)
11960              and then Is_Private_Type (T))
11961       then
11962          Error_Msg_N ("invalid constraint: type has no discriminant", C);
11963          Fixup_Bad_Constraint;
11964          return;
11965
11966       elsif Is_Constrained (E)
11967         or else (Ekind (E) = E_Class_Wide_Subtype
11968                   and then Present (Discriminant_Constraint (E)))
11969       then
11970          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
11971          Fixup_Bad_Constraint;
11972          return;
11973       end if;
11974
11975       --  T may be an unconstrained subtype (e.g. a generic actual).
11976       --  Constraint applies to the base type.
11977
11978       T := Base_Type (T);
11979
11980       Elist := Build_Discriminant_Constraints (T, S);
11981
11982       --  If the list returned was empty we had an error in building the
11983       --  discriminant constraint. We have also already signalled an error
11984       --  in the incomplete type case
11985
11986       if Is_Empty_Elmt_List (Elist) then
11987          Fixup_Bad_Constraint;
11988          return;
11989       end if;
11990
11991       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
11992    end Constrain_Discriminated_Type;
11993
11994    ---------------------------
11995    -- Constrain_Enumeration --
11996    ---------------------------
11997
11998    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
11999       T : constant Entity_Id := Entity (Subtype_Mark (S));
12000       C : constant Node_Id   := Constraint (S);
12001
12002    begin
12003       Set_Ekind (Def_Id, E_Enumeration_Subtype);
12004
12005       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
12006
12007       Set_Etype             (Def_Id, Base_Type         (T));
12008       Set_Size_Info         (Def_Id,                   (T));
12009       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
12010       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
12011
12012       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
12013
12014       Set_Discrete_RM_Size (Def_Id);
12015    end Constrain_Enumeration;
12016
12017    ----------------------
12018    -- Constrain_Float --
12019    ----------------------
12020
12021    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
12022       T    : constant Entity_Id := Entity (Subtype_Mark (S));
12023       C    : Node_Id;
12024       D    : Node_Id;
12025       Rais : Node_Id;
12026
12027    begin
12028       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
12029
12030       Set_Etype          (Def_Id, Base_Type      (T));
12031       Set_Size_Info      (Def_Id,                (T));
12032       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
12033
12034       --  Process the constraint
12035
12036       C := Constraint (S);
12037
12038       --  Digits constraint present
12039
12040       if Nkind (C) = N_Digits_Constraint then
12041
12042          Check_SPARK_Restriction ("digits constraint is not allowed", S);
12043          Check_Restriction (No_Obsolescent_Features, C);
12044
12045          if Warn_On_Obsolescent_Feature then
12046             Error_Msg_N
12047               ("subtype digits constraint is an " &
12048                "obsolescent feature (RM J.3(8))?j?", C);
12049          end if;
12050
12051          D := Digits_Expression (C);
12052          Analyze_And_Resolve (D, Any_Integer);
12053          Check_Digits_Expression (D);
12054          Set_Digits_Value (Def_Id, Expr_Value (D));
12055
12056          --  Check that digits value is in range. Obviously we can do this
12057          --  at compile time, but it is strictly a runtime check, and of
12058          --  course there is an ACVC test that checks this!
12059
12060          if Digits_Value (Def_Id) > Digits_Value (T) then
12061             Error_Msg_Uint_1 := Digits_Value (T);
12062             Error_Msg_N ("??digits value is too large, maximum is ^", D);
12063             Rais :=
12064               Make_Raise_Constraint_Error (Sloc (D),
12065                 Reason => CE_Range_Check_Failed);
12066             Insert_Action (Declaration_Node (Def_Id), Rais);
12067          end if;
12068
12069          C := Range_Constraint (C);
12070
12071       --  No digits constraint present
12072
12073       else
12074          Set_Digits_Value (Def_Id, Digits_Value (T));
12075       end if;
12076
12077       --  Range constraint present
12078
12079       if Nkind (C) = N_Range_Constraint then
12080          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
12081
12082       --  No range constraint present
12083
12084       else
12085          pragma Assert (No (C));
12086          Set_Scalar_Range (Def_Id, Scalar_Range (T));
12087       end if;
12088
12089       Set_Is_Constrained (Def_Id);
12090    end Constrain_Float;
12091
12092    ---------------------
12093    -- Constrain_Index --
12094    ---------------------
12095
12096    procedure Constrain_Index
12097      (Index        : Node_Id;
12098       S            : Node_Id;
12099       Related_Nod  : Node_Id;
12100       Related_Id   : Entity_Id;
12101       Suffix       : Character;
12102       Suffix_Index : Nat)
12103    is
12104       Def_Id : Entity_Id;
12105       R      : Node_Id := Empty;
12106       T      : constant Entity_Id := Etype (Index);
12107
12108    begin
12109       if Nkind (S) = N_Range
12110         or else
12111           (Nkind (S) = N_Attribute_Reference
12112             and then Attribute_Name (S) = Name_Range)
12113       then
12114          --  A Range attribute will be transformed into N_Range by Resolve
12115
12116          Analyze (S);
12117          Set_Etype (S, T);
12118          R := S;
12119
12120          Process_Range_Expr_In_Decl (R, T, Empty_List);
12121
12122          if not Error_Posted (S)
12123            and then
12124              (Nkind (S) /= N_Range
12125                or else not Covers (T, (Etype (Low_Bound (S))))
12126                or else not Covers (T, (Etype (High_Bound (S)))))
12127          then
12128             if Base_Type (T) /= Any_Type
12129               and then Etype (Low_Bound (S)) /= Any_Type
12130               and then Etype (High_Bound (S)) /= Any_Type
12131             then
12132                Error_Msg_N ("range expected", S);
12133             end if;
12134          end if;
12135
12136       elsif Nkind (S) = N_Subtype_Indication then
12137
12138          --  The parser has verified that this is a discrete indication
12139
12140          Resolve_Discrete_Subtype_Indication (S, T);
12141          R := Range_Expression (Constraint (S));
12142
12143          --  Capture values of bounds and generate temporaries for them if
12144          --  needed, since checks may cause duplication of the expressions
12145          --  which must not be reevaluated.
12146
12147          --  The forced evaluation removes side effects from expressions,
12148          --  which should occur also in SPARK mode. Otherwise, we end up with
12149          --  unexpected insertions of actions at places where this is not
12150          --  supposed to occur, e.g. on default parameters of a call.
12151
12152          if Expander_Active then
12153             Force_Evaluation (Low_Bound (R));
12154             Force_Evaluation (High_Bound (R));
12155          end if;
12156
12157       elsif Nkind (S) = N_Discriminant_Association then
12158
12159          --  Syntactically valid in subtype indication
12160
12161          Error_Msg_N ("invalid index constraint", S);
12162          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
12163          return;
12164
12165       --  Subtype_Mark case, no anonymous subtypes to construct
12166
12167       else
12168          Analyze (S);
12169
12170          if Is_Entity_Name (S) then
12171             if not Is_Type (Entity (S)) then
12172                Error_Msg_N ("expect subtype mark for index constraint", S);
12173
12174             elsif Base_Type (Entity (S)) /= Base_Type (T) then
12175                Wrong_Type (S, Base_Type (T));
12176
12177             --  Check error of subtype with predicate in index constraint
12178
12179             else
12180                Bad_Predicated_Subtype_Use
12181                  ("subtype& has predicate, not allowed in index constraint",
12182                   S, Entity (S));
12183             end if;
12184
12185             return;
12186
12187          else
12188             Error_Msg_N ("invalid index constraint", S);
12189             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
12190             return;
12191          end if;
12192       end if;
12193
12194       Def_Id :=
12195         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
12196
12197       Set_Etype (Def_Id, Base_Type (T));
12198
12199       if Is_Modular_Integer_Type (T) then
12200          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
12201
12202       elsif Is_Integer_Type (T) then
12203          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
12204
12205       else
12206          Set_Ekind (Def_Id, E_Enumeration_Subtype);
12207          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
12208          Set_First_Literal     (Def_Id, First_Literal (T));
12209       end if;
12210
12211       Set_Size_Info      (Def_Id,                (T));
12212       Set_RM_Size        (Def_Id, RM_Size        (T));
12213       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
12214
12215       Set_Scalar_Range   (Def_Id, R);
12216
12217       Set_Etype (S, Def_Id);
12218       Set_Discrete_RM_Size (Def_Id);
12219    end Constrain_Index;
12220
12221    -----------------------
12222    -- Constrain_Integer --
12223    -----------------------
12224
12225    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
12226       T : constant Entity_Id := Entity (Subtype_Mark (S));
12227       C : constant Node_Id   := Constraint (S);
12228
12229    begin
12230       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
12231
12232       if Is_Modular_Integer_Type (T) then
12233          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
12234       else
12235          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
12236       end if;
12237
12238       Set_Etype            (Def_Id, Base_Type      (T));
12239       Set_Size_Info        (Def_Id,                (T));
12240       Set_First_Rep_Item   (Def_Id, First_Rep_Item (T));
12241       Set_Discrete_RM_Size (Def_Id);
12242    end Constrain_Integer;
12243
12244    ------------------------------
12245    -- Constrain_Ordinary_Fixed --
12246    ------------------------------
12247
12248    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
12249       T    : constant Entity_Id := Entity (Subtype_Mark (S));
12250       C    : Node_Id;
12251       D    : Node_Id;
12252       Rais : Node_Id;
12253
12254    begin
12255       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
12256       Set_Etype          (Def_Id, Base_Type      (T));
12257       Set_Size_Info      (Def_Id,                (T));
12258       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
12259       Set_Small_Value    (Def_Id, Small_Value    (T));
12260
12261       --  Process the constraint
12262
12263       C := Constraint (S);
12264
12265       --  Delta constraint present
12266
12267       if Nkind (C) = N_Delta_Constraint then
12268
12269          Check_SPARK_Restriction ("delta constraint is not allowed", S);
12270          Check_Restriction (No_Obsolescent_Features, C);
12271
12272          if Warn_On_Obsolescent_Feature then
12273             Error_Msg_S
12274               ("subtype delta constraint is an " &
12275                "obsolescent feature (RM J.3(7))?j?");
12276          end if;
12277
12278          D := Delta_Expression (C);
12279          Analyze_And_Resolve (D, Any_Real);
12280          Check_Delta_Expression (D);
12281          Set_Delta_Value (Def_Id, Expr_Value_R (D));
12282
12283          --  Check that delta value is in range. Obviously we can do this
12284          --  at compile time, but it is strictly a runtime check, and of
12285          --  course there is an ACVC test that checks this!
12286
12287          if Delta_Value (Def_Id) < Delta_Value (T) then
12288             Error_Msg_N ("??delta value is too small", D);
12289             Rais :=
12290               Make_Raise_Constraint_Error (Sloc (D),
12291                 Reason => CE_Range_Check_Failed);
12292             Insert_Action (Declaration_Node (Def_Id), Rais);
12293          end if;
12294
12295          C := Range_Constraint (C);
12296
12297       --  No delta constraint present
12298
12299       else
12300          Set_Delta_Value (Def_Id, Delta_Value (T));
12301       end if;
12302
12303       --  Range constraint present
12304
12305       if Nkind (C) = N_Range_Constraint then
12306          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
12307
12308       --  No range constraint present
12309
12310       else
12311          pragma Assert (No (C));
12312          Set_Scalar_Range (Def_Id, Scalar_Range (T));
12313
12314       end if;
12315
12316       Set_Discrete_RM_Size (Def_Id);
12317
12318       --  Unconditionally delay the freeze, since we cannot set size
12319       --  information in all cases correctly until the freeze point.
12320
12321       Set_Has_Delayed_Freeze (Def_Id);
12322    end Constrain_Ordinary_Fixed;
12323
12324    -----------------------
12325    -- Contain_Interface --
12326    -----------------------
12327
12328    function Contain_Interface
12329      (Iface  : Entity_Id;
12330       Ifaces : Elist_Id) return Boolean
12331    is
12332       Iface_Elmt : Elmt_Id;
12333
12334    begin
12335       if Present (Ifaces) then
12336          Iface_Elmt := First_Elmt (Ifaces);
12337          while Present (Iface_Elmt) loop
12338             if Node (Iface_Elmt) = Iface then
12339                return True;
12340             end if;
12341
12342             Next_Elmt (Iface_Elmt);
12343          end loop;
12344       end if;
12345
12346       return False;
12347    end Contain_Interface;
12348
12349    ---------------------------
12350    -- Convert_Scalar_Bounds --
12351    ---------------------------
12352
12353    procedure Convert_Scalar_Bounds
12354      (N            : Node_Id;
12355       Parent_Type  : Entity_Id;
12356       Derived_Type : Entity_Id;
12357       Loc          : Source_Ptr)
12358    is
12359       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
12360
12361       Lo  : Node_Id;
12362       Hi  : Node_Id;
12363       Rng : Node_Id;
12364
12365    begin
12366       --  Defend against previous errors
12367
12368       if No (Scalar_Range (Derived_Type)) then
12369          Check_Error_Detected;
12370          return;
12371       end if;
12372
12373       Lo := Build_Scalar_Bound
12374               (Type_Low_Bound (Derived_Type),
12375                Parent_Type, Implicit_Base);
12376
12377       Hi := Build_Scalar_Bound
12378               (Type_High_Bound (Derived_Type),
12379                Parent_Type, Implicit_Base);
12380
12381       Rng :=
12382         Make_Range (Loc,
12383           Low_Bound  => Lo,
12384           High_Bound => Hi);
12385
12386       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
12387
12388       Set_Parent (Rng, N);
12389       Set_Scalar_Range (Derived_Type, Rng);
12390
12391       --  Analyze the bounds
12392
12393       Analyze_And_Resolve (Lo, Implicit_Base);
12394       Analyze_And_Resolve (Hi, Implicit_Base);
12395
12396       --  Analyze the range itself, except that we do not analyze it if
12397       --  the bounds are real literals, and we have a fixed-point type.
12398       --  The reason for this is that we delay setting the bounds in this
12399       --  case till we know the final Small and Size values (see circuit
12400       --  in Freeze.Freeze_Fixed_Point_Type for further details).
12401
12402       if Is_Fixed_Point_Type (Parent_Type)
12403         and then Nkind (Lo) = N_Real_Literal
12404         and then Nkind (Hi) = N_Real_Literal
12405       then
12406          return;
12407
12408       --  Here we do the analysis of the range
12409
12410       --  Note: we do this manually, since if we do a normal Analyze and
12411       --  Resolve call, there are problems with the conversions used for
12412       --  the derived type range.
12413
12414       else
12415          Set_Etype    (Rng, Implicit_Base);
12416          Set_Analyzed (Rng, True);
12417       end if;
12418    end Convert_Scalar_Bounds;
12419
12420    -------------------
12421    -- Copy_And_Swap --
12422    -------------------
12423
12424    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
12425    begin
12426       --  Initialize new full declaration entity by copying the pertinent
12427       --  fields of the corresponding private declaration entity.
12428
12429       --  We temporarily set Ekind to a value appropriate for a type to
12430       --  avoid assert failures in Einfo from checking for setting type
12431       --  attributes on something that is not a type. Ekind (Priv) is an
12432       --  appropriate choice, since it allowed the attributes to be set
12433       --  in the first place. This Ekind value will be modified later.
12434
12435       Set_Ekind (Full, Ekind (Priv));
12436
12437       --  Also set Etype temporarily to Any_Type, again, in the absence
12438       --  of errors, it will be properly reset, and if there are errors,
12439       --  then we want a value of Any_Type to remain.
12440
12441       Set_Etype (Full, Any_Type);
12442
12443       --  Now start copying attributes
12444
12445       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
12446
12447       if Has_Discriminants (Full) then
12448          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
12449          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
12450       end if;
12451
12452       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
12453       Set_Homonym                    (Full, Homonym                 (Priv));
12454       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
12455       Set_Is_Public                  (Full, Is_Public               (Priv));
12456       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
12457       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
12458       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
12459       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
12460       Set_Has_Pragma_Unreferenced_Objects
12461                                      (Full, Has_Pragma_Unreferenced_Objects
12462                                                                     (Priv));
12463
12464       Conditional_Delay              (Full,                          Priv);
12465
12466       if Is_Tagged_Type (Full) then
12467          Set_Direct_Primitive_Operations (Full,
12468            Direct_Primitive_Operations (Priv));
12469
12470          if Is_Base_Type (Priv) then
12471             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
12472          end if;
12473       end if;
12474
12475       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
12476       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
12477       Set_Scope                      (Full, Scope                   (Priv));
12478       Set_Next_Entity                (Full, Next_Entity             (Priv));
12479       Set_First_Entity               (Full, First_Entity            (Priv));
12480       Set_Last_Entity                (Full, Last_Entity             (Priv));
12481
12482       --  If access types have been recorded for later handling, keep them in
12483       --  the full view so that they get handled when the full view freeze
12484       --  node is expanded.
12485
12486       if Present (Freeze_Node (Priv))
12487         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
12488       then
12489          Ensure_Freeze_Node (Full);
12490          Set_Access_Types_To_Process
12491            (Freeze_Node (Full),
12492             Access_Types_To_Process (Freeze_Node (Priv)));
12493       end if;
12494
12495       --  Swap the two entities. Now Private is the full type entity and Full
12496       --  is the private one. They will be swapped back at the end of the
12497       --  private part. This swapping ensures that the entity that is visible
12498       --  in the private part is the full declaration.
12499
12500       Exchange_Entities (Priv, Full);
12501       Append_Entity (Full, Scope (Full));
12502    end Copy_And_Swap;
12503
12504    -------------------------------------
12505    -- Copy_Array_Base_Type_Attributes --
12506    -------------------------------------
12507
12508    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
12509    begin
12510       Set_Component_Alignment      (T1, Component_Alignment      (T2));
12511       Set_Component_Type           (T1, Component_Type           (T2));
12512       Set_Component_Size           (T1, Component_Size           (T2));
12513       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
12514       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
12515       Set_Has_Task                 (T1, Has_Task                 (T2));
12516       Set_Is_Packed                (T1, Is_Packed                (T2));
12517       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
12518       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
12519       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
12520    end Copy_Array_Base_Type_Attributes;
12521
12522    -----------------------------------
12523    -- Copy_Array_Subtype_Attributes --
12524    -----------------------------------
12525
12526    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
12527    begin
12528       Set_Size_Info (T1, T2);
12529
12530       Set_First_Index          (T1, First_Index           (T2));
12531       Set_Is_Aliased           (T1, Is_Aliased            (T2));
12532       Set_Is_Volatile          (T1, Is_Volatile           (T2));
12533       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
12534       Set_Is_Constrained       (T1, Is_Constrained        (T2));
12535       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
12536       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
12537       Set_Convention           (T1, Convention            (T2));
12538       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
12539       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
12540       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
12541    end Copy_Array_Subtype_Attributes;
12542
12543    -----------------------------------
12544    -- Create_Constrained_Components --
12545    -----------------------------------
12546
12547    procedure Create_Constrained_Components
12548      (Subt        : Entity_Id;
12549       Decl_Node   : Node_Id;
12550       Typ         : Entity_Id;
12551       Constraints : Elist_Id)
12552    is
12553       Loc         : constant Source_Ptr := Sloc (Subt);
12554       Comp_List   : constant Elist_Id   := New_Elmt_List;
12555       Parent_Type : constant Entity_Id  := Etype (Typ);
12556       Assoc_List  : constant List_Id    := New_List;
12557       Discr_Val   : Elmt_Id;
12558       Errors      : Boolean;
12559       New_C       : Entity_Id;
12560       Old_C       : Entity_Id;
12561       Is_Static   : Boolean := True;
12562
12563       procedure Collect_Fixed_Components (Typ : Entity_Id);
12564       --  Collect parent type components that do not appear in a variant part
12565
12566       procedure Create_All_Components;
12567       --  Iterate over Comp_List to create the components of the subtype
12568
12569       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
12570       --  Creates a new component from Old_Compon, copying all the fields from
12571       --  it, including its Etype, inserts the new component in the Subt entity
12572       --  chain and returns the new component.
12573
12574       function Is_Variant_Record (T : Entity_Id) return Boolean;
12575       --  If true, and discriminants are static, collect only components from
12576       --  variants selected by discriminant values.
12577
12578       ------------------------------
12579       -- Collect_Fixed_Components --
12580       ------------------------------
12581
12582       procedure Collect_Fixed_Components (Typ : Entity_Id) is
12583       begin
12584       --  Build association list for discriminants, and find components of the
12585       --  variant part selected by the values of the discriminants.
12586
12587          Old_C := First_Discriminant (Typ);
12588          Discr_Val := First_Elmt (Constraints);
12589          while Present (Old_C) loop
12590             Append_To (Assoc_List,
12591               Make_Component_Association (Loc,
12592                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
12593                  Expression => New_Copy (Node (Discr_Val))));
12594
12595             Next_Elmt (Discr_Val);
12596             Next_Discriminant (Old_C);
12597          end loop;
12598
12599          --  The tag and the possible parent component are unconditionally in
12600          --  the subtype.
12601
12602          if Is_Tagged_Type (Typ)
12603            or else Has_Controlled_Component (Typ)
12604          then
12605             Old_C := First_Component (Typ);
12606             while Present (Old_C) loop
12607                if Nam_In (Chars (Old_C), Name_uTag, Name_uParent) then
12608                   Append_Elmt (Old_C, Comp_List);
12609                end if;
12610
12611                Next_Component (Old_C);
12612             end loop;
12613          end if;
12614       end Collect_Fixed_Components;
12615
12616       ---------------------------
12617       -- Create_All_Components --
12618       ---------------------------
12619
12620       procedure Create_All_Components is
12621          Comp : Elmt_Id;
12622
12623       begin
12624          Comp := First_Elmt (Comp_List);
12625          while Present (Comp) loop
12626             Old_C := Node (Comp);
12627             New_C := Create_Component (Old_C);
12628
12629             Set_Etype
12630               (New_C,
12631                Constrain_Component_Type
12632                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12633             Set_Is_Public (New_C, Is_Public (Subt));
12634
12635             Next_Elmt (Comp);
12636          end loop;
12637       end Create_All_Components;
12638
12639       ----------------------
12640       -- Create_Component --
12641       ----------------------
12642
12643       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
12644          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
12645
12646       begin
12647          if Ekind (Old_Compon) = E_Discriminant
12648            and then Is_Completely_Hidden (Old_Compon)
12649          then
12650             --  This is a shadow discriminant created for a discriminant of
12651             --  the parent type, which needs to be present in the subtype.
12652             --  Give the shadow discriminant an internal name that cannot
12653             --  conflict with that of visible components.
12654
12655             Set_Chars (New_Compon, New_Internal_Name ('C'));
12656          end if;
12657
12658          --  Set the parent so we have a proper link for freezing etc. This is
12659          --  not a real parent pointer, since of course our parent does not own
12660          --  up to us and reference us, we are an illegitimate child of the
12661          --  original parent!
12662
12663          Set_Parent (New_Compon, Parent (Old_Compon));
12664
12665          --  If the old component's Esize was already determined and is a
12666          --  static value, then the new component simply inherits it. Otherwise
12667          --  the old component's size may require run-time determination, but
12668          --  the new component's size still might be statically determinable
12669          --  (if, for example it has a static constraint). In that case we want
12670          --  Layout_Type to recompute the component's size, so we reset its
12671          --  size and positional fields.
12672
12673          if Frontend_Layout_On_Target
12674            and then not Known_Static_Esize (Old_Compon)
12675          then
12676             Set_Esize (New_Compon, Uint_0);
12677             Init_Normalized_First_Bit    (New_Compon);
12678             Init_Normalized_Position     (New_Compon);
12679             Init_Normalized_Position_Max (New_Compon);
12680          end if;
12681
12682          --  We do not want this node marked as Comes_From_Source, since
12683          --  otherwise it would get first class status and a separate cross-
12684          --  reference line would be generated. Illegitimate children do not
12685          --  rate such recognition.
12686
12687          Set_Comes_From_Source (New_Compon, False);
12688
12689          --  But it is a real entity, and a birth certificate must be properly
12690          --  registered by entering it into the entity list.
12691
12692          Enter_Name (New_Compon);
12693
12694          return New_Compon;
12695       end Create_Component;
12696
12697       -----------------------
12698       -- Is_Variant_Record --
12699       -----------------------
12700
12701       function Is_Variant_Record (T : Entity_Id) return Boolean is
12702       begin
12703          return Nkind (Parent (T)) = N_Full_Type_Declaration
12704            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
12705            and then Present (Component_List (Type_Definition (Parent (T))))
12706            and then
12707              Present
12708                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
12709       end Is_Variant_Record;
12710
12711    --  Start of processing for Create_Constrained_Components
12712
12713    begin
12714       pragma Assert (Subt /= Base_Type (Subt));
12715       pragma Assert (Typ = Base_Type (Typ));
12716
12717       Set_First_Entity (Subt, Empty);
12718       Set_Last_Entity  (Subt, Empty);
12719
12720       --  Check whether constraint is fully static, in which case we can
12721       --  optimize the list of components.
12722
12723       Discr_Val := First_Elmt (Constraints);
12724       while Present (Discr_Val) loop
12725          if not Is_OK_Static_Expression (Node (Discr_Val)) then
12726             Is_Static := False;
12727             exit;
12728          end if;
12729
12730          Next_Elmt (Discr_Val);
12731       end loop;
12732
12733       Set_Has_Static_Discriminants (Subt, Is_Static);
12734
12735       Push_Scope (Subt);
12736
12737       --  Inherit the discriminants of the parent type
12738
12739       Add_Discriminants : declare
12740          Num_Disc : Int;
12741          Num_Gird : Int;
12742
12743       begin
12744          Num_Disc := 0;
12745          Old_C := First_Discriminant (Typ);
12746
12747          while Present (Old_C) loop
12748             Num_Disc := Num_Disc + 1;
12749             New_C := Create_Component (Old_C);
12750             Set_Is_Public (New_C, Is_Public (Subt));
12751             Next_Discriminant (Old_C);
12752          end loop;
12753
12754          --  For an untagged derived subtype, the number of discriminants may
12755          --  be smaller than the number of inherited discriminants, because
12756          --  several of them may be renamed by a single new discriminant or
12757          --  constrained. In this case, add the hidden discriminants back into
12758          --  the subtype, because they need to be present if the optimizer of
12759          --  the GCC 4.x back-end decides to break apart assignments between
12760          --  objects using the parent view into member-wise assignments.
12761
12762          Num_Gird := 0;
12763
12764          if Is_Derived_Type (Typ)
12765            and then not Is_Tagged_Type (Typ)
12766          then
12767             Old_C := First_Stored_Discriminant (Typ);
12768
12769             while Present (Old_C) loop
12770                Num_Gird := Num_Gird + 1;
12771                Next_Stored_Discriminant (Old_C);
12772             end loop;
12773          end if;
12774
12775          if Num_Gird > Num_Disc then
12776
12777             --  Find out multiple uses of new discriminants, and add hidden
12778             --  components for the extra renamed discriminants. We recognize
12779             --  multiple uses through the Corresponding_Discriminant of a
12780             --  new discriminant: if it constrains several old discriminants,
12781             --  this field points to the last one in the parent type. The
12782             --  stored discriminants of the derived type have the same name
12783             --  as those of the parent.
12784
12785             declare
12786                Constr    : Elmt_Id;
12787                New_Discr : Entity_Id;
12788                Old_Discr : Entity_Id;
12789
12790             begin
12791                Constr    := First_Elmt (Stored_Constraint (Typ));
12792                Old_Discr := First_Stored_Discriminant (Typ);
12793                while Present (Constr) loop
12794                   if Is_Entity_Name (Node (Constr))
12795                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
12796                   then
12797                      New_Discr := Entity (Node (Constr));
12798
12799                      if Chars (Corresponding_Discriminant (New_Discr)) /=
12800                         Chars (Old_Discr)
12801                      then
12802                         --  The new discriminant has been used to rename a
12803                         --  subsequent old discriminant. Introduce a shadow
12804                         --  component for the current old discriminant.
12805
12806                         New_C := Create_Component (Old_Discr);
12807                         Set_Original_Record_Component (New_C, Old_Discr);
12808                      end if;
12809
12810                   else
12811                      --  The constraint has eliminated the old discriminant.
12812                      --  Introduce a shadow component.
12813
12814                      New_C := Create_Component (Old_Discr);
12815                      Set_Original_Record_Component (New_C, Old_Discr);
12816                   end if;
12817
12818                   Next_Elmt (Constr);
12819                   Next_Stored_Discriminant (Old_Discr);
12820                end loop;
12821             end;
12822          end if;
12823       end Add_Discriminants;
12824
12825       if Is_Static
12826         and then Is_Variant_Record (Typ)
12827       then
12828          Collect_Fixed_Components (Typ);
12829
12830          Gather_Components (
12831            Typ,
12832            Component_List (Type_Definition (Parent (Typ))),
12833            Governed_By   => Assoc_List,
12834            Into          => Comp_List,
12835            Report_Errors => Errors);
12836          pragma Assert (not Errors);
12837
12838          Create_All_Components;
12839
12840       --  If the subtype declaration is created for a tagged type derivation
12841       --  with constraints, we retrieve the record definition of the parent
12842       --  type to select the components of the proper variant.
12843
12844       elsif Is_Static
12845         and then Is_Tagged_Type (Typ)
12846         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
12847         and then
12848           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
12849         and then Is_Variant_Record (Parent_Type)
12850       then
12851          Collect_Fixed_Components (Typ);
12852
12853          Gather_Components (
12854            Typ,
12855            Component_List (Type_Definition (Parent (Parent_Type))),
12856            Governed_By   => Assoc_List,
12857            Into          => Comp_List,
12858            Report_Errors => Errors);
12859          pragma Assert (not Errors);
12860
12861          --  If the tagged derivation has a type extension, collect all the
12862          --  new components therein.
12863
12864          if Present
12865               (Record_Extension_Part (Type_Definition (Parent (Typ))))
12866          then
12867             Old_C := First_Component (Typ);
12868             while Present (Old_C) loop
12869                if Original_Record_Component (Old_C) = Old_C
12870                 and then Chars (Old_C) /= Name_uTag
12871                 and then Chars (Old_C) /= Name_uParent
12872                then
12873                   Append_Elmt (Old_C, Comp_List);
12874                end if;
12875
12876                Next_Component (Old_C);
12877             end loop;
12878          end if;
12879
12880          Create_All_Components;
12881
12882       else
12883          --  If discriminants are not static, or if this is a multi-level type
12884          --  extension, we have to include all components of the parent type.
12885
12886          Old_C := First_Component (Typ);
12887          while Present (Old_C) loop
12888             New_C := Create_Component (Old_C);
12889
12890             Set_Etype
12891               (New_C,
12892                Constrain_Component_Type
12893                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12894             Set_Is_Public (New_C, Is_Public (Subt));
12895
12896             Next_Component (Old_C);
12897          end loop;
12898       end if;
12899
12900       End_Scope;
12901    end Create_Constrained_Components;
12902
12903    ------------------------------------------
12904    -- Decimal_Fixed_Point_Type_Declaration --
12905    ------------------------------------------
12906
12907    procedure Decimal_Fixed_Point_Type_Declaration
12908      (T   : Entity_Id;
12909       Def : Node_Id)
12910    is
12911       Loc           : constant Source_Ptr := Sloc (Def);
12912       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
12913       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
12914       Implicit_Base : Entity_Id;
12915       Digs_Val      : Uint;
12916       Delta_Val     : Ureal;
12917       Scale_Val     : Uint;
12918       Bound_Val     : Ureal;
12919
12920    begin
12921       Check_SPARK_Restriction
12922         ("decimal fixed point type is not allowed", Def);
12923       Check_Restriction (No_Fixed_Point, Def);
12924
12925       --  Create implicit base type
12926
12927       Implicit_Base :=
12928         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
12929       Set_Etype (Implicit_Base, Implicit_Base);
12930
12931       --  Analyze and process delta expression
12932
12933       Analyze_And_Resolve (Delta_Expr, Universal_Real);
12934
12935       Check_Delta_Expression (Delta_Expr);
12936       Delta_Val := Expr_Value_R (Delta_Expr);
12937
12938       --  Check delta is power of 10, and determine scale value from it
12939
12940       declare
12941          Val : Ureal;
12942
12943       begin
12944          Scale_Val := Uint_0;
12945          Val := Delta_Val;
12946
12947          if Val < Ureal_1 then
12948             while Val < Ureal_1 loop
12949                Val := Val * Ureal_10;
12950                Scale_Val := Scale_Val + 1;
12951             end loop;
12952
12953             if Scale_Val > 18 then
12954                Error_Msg_N ("scale exceeds maximum value of 18", Def);
12955                Scale_Val := UI_From_Int (+18);
12956             end if;
12957
12958          else
12959             while Val > Ureal_1 loop
12960                Val := Val / Ureal_10;
12961                Scale_Val := Scale_Val - 1;
12962             end loop;
12963
12964             if Scale_Val < -18 then
12965                Error_Msg_N ("scale is less than minimum value of -18", Def);
12966                Scale_Val := UI_From_Int (-18);
12967             end if;
12968          end if;
12969
12970          if Val /= Ureal_1 then
12971             Error_Msg_N ("delta expression must be a power of 10", Def);
12972             Delta_Val := Ureal_10 ** (-Scale_Val);
12973          end if;
12974       end;
12975
12976       --  Set delta, scale and small (small = delta for decimal type)
12977
12978       Set_Delta_Value (Implicit_Base, Delta_Val);
12979       Set_Scale_Value (Implicit_Base, Scale_Val);
12980       Set_Small_Value (Implicit_Base, Delta_Val);
12981
12982       --  Analyze and process digits expression
12983
12984       Analyze_And_Resolve (Digs_Expr, Any_Integer);
12985       Check_Digits_Expression (Digs_Expr);
12986       Digs_Val := Expr_Value (Digs_Expr);
12987
12988       if Digs_Val > 18 then
12989          Digs_Val := UI_From_Int (+18);
12990          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
12991       end if;
12992
12993       Set_Digits_Value (Implicit_Base, Digs_Val);
12994       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
12995
12996       --  Set range of base type from digits value for now. This will be
12997       --  expanded to represent the true underlying base range by Freeze.
12998
12999       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
13000
13001       --  Note: We leave size as zero for now, size will be set at freeze
13002       --  time. We have to do this for ordinary fixed-point, because the size
13003       --  depends on the specified small, and we might as well do the same for
13004       --  decimal fixed-point.
13005
13006       pragma Assert (Esize (Implicit_Base) = Uint_0);
13007
13008       --  If there are bounds given in the declaration use them as the
13009       --  bounds of the first named subtype.
13010
13011       if Present (Real_Range_Specification (Def)) then
13012          declare
13013             RRS      : constant Node_Id := Real_Range_Specification (Def);
13014             Low      : constant Node_Id := Low_Bound (RRS);
13015             High     : constant Node_Id := High_Bound (RRS);
13016             Low_Val  : Ureal;
13017             High_Val : Ureal;
13018
13019          begin
13020             Analyze_And_Resolve (Low, Any_Real);
13021             Analyze_And_Resolve (High, Any_Real);
13022             Check_Real_Bound (Low);
13023             Check_Real_Bound (High);
13024             Low_Val := Expr_Value_R (Low);
13025             High_Val := Expr_Value_R (High);
13026
13027             if Low_Val < (-Bound_Val) then
13028                Error_Msg_N
13029                  ("range low bound too small for digits value", Low);
13030                Low_Val := -Bound_Val;
13031             end if;
13032
13033             if High_Val > Bound_Val then
13034                Error_Msg_N
13035                  ("range high bound too large for digits value", High);
13036                High_Val := Bound_Val;
13037             end if;
13038
13039             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
13040          end;
13041
13042       --  If no explicit range, use range that corresponds to given
13043       --  digits value. This will end up as the final range for the
13044       --  first subtype.
13045
13046       else
13047          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
13048       end if;
13049
13050       --  Complete entity for first subtype
13051
13052       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
13053       Set_Etype          (T, Implicit_Base);
13054       Set_Size_Info      (T, Implicit_Base);
13055       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
13056       Set_Digits_Value   (T, Digs_Val);
13057       Set_Delta_Value    (T, Delta_Val);
13058       Set_Small_Value    (T, Delta_Val);
13059       Set_Scale_Value    (T, Scale_Val);
13060       Set_Is_Constrained (T);
13061    end Decimal_Fixed_Point_Type_Declaration;
13062
13063    -----------------------------------
13064    -- Derive_Progenitor_Subprograms --
13065    -----------------------------------
13066
13067    procedure Derive_Progenitor_Subprograms
13068      (Parent_Type : Entity_Id;
13069       Tagged_Type : Entity_Id)
13070    is
13071       E          : Entity_Id;
13072       Elmt       : Elmt_Id;
13073       Iface      : Entity_Id;
13074       Iface_Elmt : Elmt_Id;
13075       Iface_Subp : Entity_Id;
13076       New_Subp   : Entity_Id := Empty;
13077       Prim_Elmt  : Elmt_Id;
13078       Subp       : Entity_Id;
13079       Typ        : Entity_Id;
13080
13081    begin
13082       pragma Assert (Ada_Version >= Ada_2005
13083         and then Is_Record_Type (Tagged_Type)
13084         and then Is_Tagged_Type (Tagged_Type)
13085         and then Has_Interfaces (Tagged_Type));
13086
13087       --  Step 1: Transfer to the full-view primitives associated with the
13088       --  partial-view that cover interface primitives. Conceptually this
13089       --  work should be done later by Process_Full_View; done here to
13090       --  simplify its implementation at later stages. It can be safely
13091       --  done here because interfaces must be visible in the partial and
13092       --  private view (RM 7.3(7.3/2)).
13093
13094       --  Small optimization: This work is only required if the parent may
13095       --  have entities whose Alias attribute reference an interface primitive.
13096       --  Such a situation may occur if the parent is an abstract type and the
13097       --  primitive has not been yet overridden or if the parent is a generic
13098       --  formal type covering interfaces.
13099
13100       --  If the tagged type is not abstract, it cannot have abstract
13101       --  primitives (the only entities in the list of primitives of
13102       --  non-abstract tagged types that can reference abstract primitives
13103       --  through its Alias attribute are the internal entities that have
13104       --  attribute Interface_Alias, and these entities are generated later
13105       --  by Add_Internal_Interface_Entities).
13106
13107       if In_Private_Part (Current_Scope)
13108         and then (Is_Abstract_Type (Parent_Type)
13109                     or else
13110                   Is_Generic_Type  (Parent_Type))
13111       then
13112          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
13113          while Present (Elmt) loop
13114             Subp := Node (Elmt);
13115
13116             --  At this stage it is not possible to have entities in the list
13117             --  of primitives that have attribute Interface_Alias.
13118
13119             pragma Assert (No (Interface_Alias (Subp)));
13120
13121             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
13122
13123             if Is_Interface (Typ) then
13124                E := Find_Primitive_Covering_Interface
13125                       (Tagged_Type => Tagged_Type,
13126                        Iface_Prim  => Subp);
13127
13128                if Present (E)
13129                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
13130                then
13131                   Replace_Elmt (Elmt, E);
13132                   Remove_Homonym (Subp);
13133                end if;
13134             end if;
13135
13136             Next_Elmt (Elmt);
13137          end loop;
13138       end if;
13139
13140       --  Step 2: Add primitives of progenitors that are not implemented by
13141       --  parents of Tagged_Type.
13142
13143       if Present (Interfaces (Base_Type (Tagged_Type))) then
13144          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
13145          while Present (Iface_Elmt) loop
13146             Iface := Node (Iface_Elmt);
13147
13148             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
13149             while Present (Prim_Elmt) loop
13150                Iface_Subp := Node (Prim_Elmt);
13151
13152                --  Exclude derivation of predefined primitives except those
13153                --  that come from source, or are inherited from one that comes
13154                --  from source. Required to catch declarations of equality
13155                --  operators of interfaces. For example:
13156
13157                --     type Iface is interface;
13158                --     function "=" (Left, Right : Iface) return Boolean;
13159
13160                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
13161                  or else Comes_From_Source (Ultimate_Alias (Iface_Subp))
13162                then
13163                   E := Find_Primitive_Covering_Interface
13164                          (Tagged_Type => Tagged_Type,
13165                           Iface_Prim  => Iface_Subp);
13166
13167                   --  If not found we derive a new primitive leaving its alias
13168                   --  attribute referencing the interface primitive.
13169
13170                   if No (E) then
13171                      Derive_Subprogram
13172                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
13173
13174                   --  Ada 2012 (AI05-0197): If the covering primitive's name
13175                   --  differs from the name of the interface primitive then it
13176                   --  is a private primitive inherited from a parent type. In
13177                   --  such case, given that Tagged_Type covers the interface,
13178                   --  the inherited private primitive becomes visible. For such
13179                   --  purpose we add a new entity that renames the inherited
13180                   --  private primitive.
13181
13182                   elsif Chars (E) /= Chars (Iface_Subp) then
13183                      pragma Assert (Has_Suffix (E, 'P'));
13184                      Derive_Subprogram
13185                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
13186                      Set_Alias (New_Subp, E);
13187                      Set_Is_Abstract_Subprogram (New_Subp,
13188                        Is_Abstract_Subprogram (E));
13189
13190                   --  Propagate to the full view interface entities associated
13191                   --  with the partial view.
13192
13193                   elsif In_Private_Part (Current_Scope)
13194                     and then Present (Alias (E))
13195                     and then Alias (E) = Iface_Subp
13196                     and then
13197                       List_Containing (Parent (E)) /=
13198                         Private_Declarations
13199                           (Specification
13200                             (Unit_Declaration_Node (Current_Scope)))
13201                   then
13202                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
13203                   end if;
13204                end if;
13205
13206                Next_Elmt (Prim_Elmt);
13207             end loop;
13208
13209             Next_Elmt (Iface_Elmt);
13210          end loop;
13211       end if;
13212    end Derive_Progenitor_Subprograms;
13213
13214    -----------------------
13215    -- Derive_Subprogram --
13216    -----------------------
13217
13218    procedure Derive_Subprogram
13219      (New_Subp     : in out Entity_Id;
13220       Parent_Subp  : Entity_Id;
13221       Derived_Type : Entity_Id;
13222       Parent_Type  : Entity_Id;
13223       Actual_Subp  : Entity_Id := Empty)
13224    is
13225       Formal : Entity_Id;
13226       --  Formal parameter of parent primitive operation
13227
13228       Formal_Of_Actual : Entity_Id;
13229       --  Formal parameter of actual operation, when the derivation is to
13230       --  create a renaming for a primitive operation of an actual in an
13231       --  instantiation.
13232
13233       New_Formal : Entity_Id;
13234       --  Formal of inherited operation
13235
13236       Visible_Subp : Entity_Id := Parent_Subp;
13237
13238       function Is_Private_Overriding return Boolean;
13239       --  If Subp is a private overriding of a visible operation, the inherited
13240       --  operation derives from the overridden op (even though its body is the
13241       --  overriding one) and the inherited operation is visible now. See
13242       --  sem_disp to see the full details of the handling of the overridden
13243       --  subprogram, which is removed from the list of primitive operations of
13244       --  the type. The overridden subprogram is saved locally in Visible_Subp,
13245       --  and used to diagnose abstract operations that need overriding in the
13246       --  derived type.
13247
13248       procedure Replace_Type (Id, New_Id : Entity_Id);
13249       --  When the type is an anonymous access type, create a new access type
13250       --  designating the derived type.
13251
13252       procedure Set_Derived_Name;
13253       --  This procedure sets the appropriate Chars name for New_Subp. This
13254       --  is normally just a copy of the parent name. An exception arises for
13255       --  type support subprograms, where the name is changed to reflect the
13256       --  name of the derived type, e.g. if type foo is derived from type bar,
13257       --  then a procedure barDA is derived with a name fooDA.
13258
13259       ---------------------------
13260       -- Is_Private_Overriding --
13261       ---------------------------
13262
13263       function Is_Private_Overriding return Boolean is
13264          Prev : Entity_Id;
13265
13266       begin
13267          --  If the parent is not a dispatching operation there is no
13268          --  need to investigate overridings
13269
13270          if not Is_Dispatching_Operation (Parent_Subp) then
13271             return False;
13272          end if;
13273
13274          --  The visible operation that is overridden is a homonym of the
13275          --  parent subprogram. We scan the homonym chain to find the one
13276          --  whose alias is the subprogram we are deriving.
13277
13278          Prev := Current_Entity (Parent_Subp);
13279          while Present (Prev) loop
13280             if Ekind (Prev) = Ekind (Parent_Subp)
13281               and then Alias (Prev) = Parent_Subp
13282               and then Scope (Parent_Subp) = Scope (Prev)
13283               and then not Is_Hidden (Prev)
13284             then
13285                Visible_Subp := Prev;
13286                return True;
13287             end if;
13288
13289             Prev := Homonym (Prev);
13290          end loop;
13291
13292          return False;
13293       end Is_Private_Overriding;
13294
13295       ------------------
13296       -- Replace_Type --
13297       ------------------
13298
13299       procedure Replace_Type (Id, New_Id : Entity_Id) is
13300          Acc_Type : Entity_Id;
13301          Par      : constant Node_Id := Parent (Derived_Type);
13302
13303       begin
13304          --  When the type is an anonymous access type, create a new access
13305          --  type designating the derived type. This itype must be elaborated
13306          --  at the point of the derivation, not on subsequent calls that may
13307          --  be out of the proper scope for Gigi, so we insert a reference to
13308          --  it after the derivation.
13309
13310          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
13311             declare
13312                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
13313
13314             begin
13315                if Ekind (Desig_Typ) = E_Record_Type_With_Private
13316                  and then Present (Full_View (Desig_Typ))
13317                  and then not Is_Private_Type (Parent_Type)
13318                then
13319                   Desig_Typ := Full_View (Desig_Typ);
13320                end if;
13321
13322                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
13323
13324                   --  Ada 2005 (AI-251): Handle also derivations of abstract
13325                   --  interface primitives.
13326
13327                  or else (Is_Interface (Desig_Typ)
13328                           and then not Is_Class_Wide_Type (Desig_Typ))
13329                then
13330                   Acc_Type := New_Copy (Etype (Id));
13331                   Set_Etype (Acc_Type, Acc_Type);
13332                   Set_Scope (Acc_Type, New_Subp);
13333
13334                   --  Compute size of anonymous access type
13335
13336                   if Is_Array_Type (Desig_Typ)
13337                     and then not Is_Constrained (Desig_Typ)
13338                   then
13339                      Init_Size (Acc_Type, 2 * System_Address_Size);
13340                   else
13341                      Init_Size (Acc_Type, System_Address_Size);
13342                   end if;
13343
13344                   Init_Alignment (Acc_Type);
13345                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
13346
13347                   Set_Etype (New_Id, Acc_Type);
13348                   Set_Scope (New_Id, New_Subp);
13349
13350                   --  Create a reference to it
13351                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
13352
13353                else
13354                   Set_Etype (New_Id, Etype (Id));
13355                end if;
13356             end;
13357
13358          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
13359            or else
13360              (Ekind (Etype (Id)) = E_Record_Type_With_Private
13361                and then Present (Full_View (Etype (Id)))
13362                and then
13363                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
13364          then
13365             --  Constraint checks on formals are generated during expansion,
13366             --  based on the signature of the original subprogram. The bounds
13367             --  of the derived type are not relevant, and thus we can use
13368             --  the base type for the formals. However, the return type may be
13369             --  used in a context that requires that the proper static bounds
13370             --  be used (a case statement, for example)  and for those cases
13371             --  we must use the derived type (first subtype), not its base.
13372
13373             --  If the derived_type_definition has no constraints, we know that
13374             --  the derived type has the same constraints as the first subtype
13375             --  of the parent, and we can also use it rather than its base,
13376             --  which can lead to more efficient code.
13377
13378             if Etype (Id) = Parent_Type then
13379                if Is_Scalar_Type (Parent_Type)
13380                  and then
13381                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
13382                then
13383                   Set_Etype (New_Id, Derived_Type);
13384
13385                elsif Nkind (Par) = N_Full_Type_Declaration
13386                  and then
13387                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
13388                  and then
13389                    Is_Entity_Name
13390                      (Subtype_Indication (Type_Definition (Par)))
13391                then
13392                   Set_Etype (New_Id, Derived_Type);
13393
13394                else
13395                   Set_Etype (New_Id, Base_Type (Derived_Type));
13396                end if;
13397
13398             else
13399                Set_Etype (New_Id, Base_Type (Derived_Type));
13400             end if;
13401
13402          else
13403             Set_Etype (New_Id, Etype (Id));
13404          end if;
13405       end Replace_Type;
13406
13407       ----------------------
13408       -- Set_Derived_Name --
13409       ----------------------
13410
13411       procedure Set_Derived_Name is
13412          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
13413       begin
13414          if Nm = TSS_Null then
13415             Set_Chars (New_Subp, Chars (Parent_Subp));
13416          else
13417             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
13418          end if;
13419       end Set_Derived_Name;
13420
13421    --  Start of processing for Derive_Subprogram
13422
13423    begin
13424       New_Subp :=
13425          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
13426       Set_Ekind (New_Subp, Ekind (Parent_Subp));
13427       Set_Contract (New_Subp, Make_Contract (Sloc (New_Subp)));
13428
13429       --  Check whether the inherited subprogram is a private operation that
13430       --  should be inherited but not yet made visible. Such subprograms can
13431       --  become visible at a later point (e.g., the private part of a public
13432       --  child unit) via Declare_Inherited_Private_Subprograms. If the
13433       --  following predicate is true, then this is not such a private
13434       --  operation and the subprogram simply inherits the name of the parent
13435       --  subprogram. Note the special check for the names of controlled
13436       --  operations, which are currently exempted from being inherited with
13437       --  a hidden name because they must be findable for generation of
13438       --  implicit run-time calls.
13439
13440       if not Is_Hidden (Parent_Subp)
13441         or else Is_Internal (Parent_Subp)
13442         or else Is_Private_Overriding
13443         or else Is_Internal_Name (Chars (Parent_Subp))
13444         or else Nam_In (Chars (Parent_Subp), Name_Initialize,
13445                                              Name_Adjust,
13446                                              Name_Finalize)
13447       then
13448          Set_Derived_Name;
13449
13450       --  An inherited dispatching equality will be overridden by an internally
13451       --  generated one, or by an explicit one, so preserve its name and thus
13452       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
13453       --  private operation it may become invisible if the full view has
13454       --  progenitors, and the dispatch table will be malformed.
13455       --  We check that the type is limited to handle the anomalous declaration
13456       --  of Limited_Controlled, which is derived from a non-limited type, and
13457       --  which is handled specially elsewhere as well.
13458
13459       elsif Chars (Parent_Subp) = Name_Op_Eq
13460         and then Is_Dispatching_Operation (Parent_Subp)
13461         and then Etype (Parent_Subp) = Standard_Boolean
13462         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
13463         and then
13464           Etype (First_Formal (Parent_Subp)) =
13465             Etype (Next_Formal (First_Formal (Parent_Subp)))
13466       then
13467          Set_Derived_Name;
13468
13469       --  If parent is hidden, this can be a regular derivation if the
13470       --  parent is immediately visible in a non-instantiating context,
13471       --  or if we are in the private part of an instance. This test
13472       --  should still be refined ???
13473
13474       --  The test for In_Instance_Not_Visible avoids inheriting the derived
13475       --  operation as a non-visible operation in cases where the parent
13476       --  subprogram might not be visible now, but was visible within the
13477       --  original generic, so it would be wrong to make the inherited
13478       --  subprogram non-visible now. (Not clear if this test is fully
13479       --  correct; are there any cases where we should declare the inherited
13480       --  operation as not visible to avoid it being overridden, e.g., when
13481       --  the parent type is a generic actual with private primitives ???)
13482
13483       --  (they should be treated the same as other private inherited
13484       --  subprograms, but it's not clear how to do this cleanly). ???
13485
13486       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
13487               and then Is_Immediately_Visible (Parent_Subp)
13488               and then not In_Instance)
13489         or else In_Instance_Not_Visible
13490       then
13491          Set_Derived_Name;
13492
13493       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
13494       --  overrides an interface primitive because interface primitives
13495       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
13496
13497       elsif Ada_Version >= Ada_2005
13498          and then Is_Dispatching_Operation (Parent_Subp)
13499          and then Covers_Some_Interface (Parent_Subp)
13500       then
13501          Set_Derived_Name;
13502
13503       --  Otherwise, the type is inheriting a private operation, so enter
13504       --  it with a special name so it can't be overridden.
13505
13506       else
13507          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
13508       end if;
13509
13510       Set_Parent (New_Subp, Parent (Derived_Type));
13511
13512       if Present (Actual_Subp) then
13513          Replace_Type (Actual_Subp, New_Subp);
13514       else
13515          Replace_Type (Parent_Subp, New_Subp);
13516       end if;
13517
13518       Conditional_Delay (New_Subp, Parent_Subp);
13519
13520       --  If we are creating a renaming for a primitive operation of an
13521       --  actual of a generic derived type, we must examine the signature
13522       --  of the actual primitive, not that of the generic formal, which for
13523       --  example may be an interface. However the name and initial value
13524       --  of the inherited operation are those of the formal primitive.
13525
13526       Formal := First_Formal (Parent_Subp);
13527
13528       if Present (Actual_Subp) then
13529          Formal_Of_Actual := First_Formal (Actual_Subp);
13530       else
13531          Formal_Of_Actual := Empty;
13532       end if;
13533
13534       while Present (Formal) loop
13535          New_Formal := New_Copy (Formal);
13536
13537          --  Normally we do not go copying parents, but in the case of
13538          --  formals, we need to link up to the declaration (which is the
13539          --  parameter specification), and it is fine to link up to the
13540          --  original formal's parameter specification in this case.
13541
13542          Set_Parent (New_Formal, Parent (Formal));
13543          Append_Entity (New_Formal, New_Subp);
13544
13545          if Present (Formal_Of_Actual) then
13546             Replace_Type (Formal_Of_Actual, New_Formal);
13547             Next_Formal (Formal_Of_Actual);
13548          else
13549             Replace_Type (Formal, New_Formal);
13550          end if;
13551
13552          Next_Formal (Formal);
13553       end loop;
13554
13555       --  If this derivation corresponds to a tagged generic actual, then
13556       --  primitive operations rename those of the actual. Otherwise the
13557       --  primitive operations rename those of the parent type, If the parent
13558       --  renames an intrinsic operator, so does the new subprogram. We except
13559       --  concatenation, which is always properly typed, and does not get
13560       --  expanded as other intrinsic operations.
13561
13562       if No (Actual_Subp) then
13563          if Is_Intrinsic_Subprogram (Parent_Subp) then
13564             Set_Is_Intrinsic_Subprogram (New_Subp);
13565
13566             if Present (Alias (Parent_Subp))
13567               and then Chars (Parent_Subp) /= Name_Op_Concat
13568             then
13569                Set_Alias (New_Subp, Alias (Parent_Subp));
13570             else
13571                Set_Alias (New_Subp, Parent_Subp);
13572             end if;
13573
13574          else
13575             Set_Alias (New_Subp, Parent_Subp);
13576          end if;
13577
13578       else
13579          Set_Alias (New_Subp, Actual_Subp);
13580       end if;
13581
13582       --  Derived subprograms of a tagged type must inherit the convention
13583       --  of the parent subprogram (a requirement of AI-117). Derived
13584       --  subprograms of untagged types simply get convention Ada by default.
13585
13586       --  If the derived type is a tagged generic formal type with unknown
13587       --  discriminants, its convention is intrinsic (RM 6.3.1 (8)).
13588
13589       --  However, if the type is derived from a generic formal, the further
13590       --  inherited subprogram has the convention of the non-generic ancestor.
13591       --  Otherwise there would be no way to override the operation.
13592       --  (This is subject to forthcoming ARG discussions).
13593
13594       if Is_Tagged_Type (Derived_Type) then
13595          if Is_Generic_Type (Derived_Type)
13596            and then Has_Unknown_Discriminants (Derived_Type)
13597          then
13598             Set_Convention (New_Subp, Convention_Intrinsic);
13599
13600          else
13601             if Is_Generic_Type (Parent_Type)
13602               and then Has_Unknown_Discriminants (Parent_Type)
13603             then
13604                Set_Convention (New_Subp, Convention (Alias (Parent_Subp)));
13605             else
13606                Set_Convention (New_Subp, Convention (Parent_Subp));
13607             end if;
13608          end if;
13609       end if;
13610
13611       --  Predefined controlled operations retain their name even if the parent
13612       --  is hidden (see above), but they are not primitive operations if the
13613       --  ancestor is not visible, for example if the parent is a private
13614       --  extension completed with a controlled extension. Note that a full
13615       --  type that is controlled can break privacy: the flag Is_Controlled is
13616       --  set on both views of the type.
13617
13618       if Is_Controlled (Parent_Type)
13619         and then Nam_In (Chars (Parent_Subp), Name_Initialize,
13620                                               Name_Adjust,
13621                                               Name_Finalize)
13622         and then Is_Hidden (Parent_Subp)
13623         and then not Is_Visibly_Controlled (Parent_Type)
13624       then
13625          Set_Is_Hidden (New_Subp);
13626       end if;
13627
13628       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
13629       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
13630
13631       if Ekind (Parent_Subp) = E_Procedure then
13632          Set_Is_Valued_Procedure
13633            (New_Subp, Is_Valued_Procedure (Parent_Subp));
13634       else
13635          Set_Has_Controlling_Result
13636            (New_Subp, Has_Controlling_Result (Parent_Subp));
13637       end if;
13638
13639       --  No_Return must be inherited properly. If this is overridden in the
13640       --  case of a dispatching operation, then a check is made in Sem_Disp
13641       --  that the overriding operation is also No_Return (no such check is
13642       --  required for the case of non-dispatching operation.
13643
13644       Set_No_Return (New_Subp, No_Return (Parent_Subp));
13645
13646       --  A derived function with a controlling result is abstract. If the
13647       --  Derived_Type is a nonabstract formal generic derived type, then
13648       --  inherited operations are not abstract: the required check is done at
13649       --  instantiation time. If the derivation is for a generic actual, the
13650       --  function is not abstract unless the actual is.
13651
13652       if Is_Generic_Type (Derived_Type)
13653         and then not Is_Abstract_Type (Derived_Type)
13654       then
13655          null;
13656
13657       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
13658       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
13659
13660       elsif Ada_Version >= Ada_2005
13661         and then (Is_Abstract_Subprogram (Alias (New_Subp))
13662                    or else (Is_Tagged_Type (Derived_Type)
13663                              and then Etype (New_Subp) = Derived_Type
13664                              and then not Is_Null_Extension (Derived_Type))
13665                    or else (Is_Tagged_Type (Derived_Type)
13666                              and then Ekind (Etype (New_Subp)) =
13667                                                        E_Anonymous_Access_Type
13668                              and then Designated_Type (Etype (New_Subp)) =
13669                                                         Derived_Type
13670                              and then not Is_Null_Extension (Derived_Type)))
13671         and then No (Actual_Subp)
13672       then
13673          if not Is_Tagged_Type (Derived_Type)
13674            or else Is_Abstract_Type (Derived_Type)
13675            or else Is_Abstract_Subprogram (Alias (New_Subp))
13676          then
13677             Set_Is_Abstract_Subprogram (New_Subp);
13678          else
13679             Set_Requires_Overriding (New_Subp);
13680          end if;
13681
13682       elsif Ada_Version < Ada_2005
13683         and then (Is_Abstract_Subprogram (Alias (New_Subp))
13684                    or else (Is_Tagged_Type (Derived_Type)
13685                              and then Etype (New_Subp) = Derived_Type
13686                              and then No (Actual_Subp)))
13687       then
13688          Set_Is_Abstract_Subprogram (New_Subp);
13689
13690       --  AI05-0097 : an inherited operation that dispatches on result is
13691       --  abstract if the derived type is abstract, even if the parent type
13692       --  is concrete and the derived type is a null extension.
13693
13694       elsif Has_Controlling_Result (Alias (New_Subp))
13695         and then Is_Abstract_Type (Etype (New_Subp))
13696       then
13697          Set_Is_Abstract_Subprogram (New_Subp);
13698
13699       --  Finally, if the parent type is abstract we must verify that all
13700       --  inherited operations are either non-abstract or overridden, or that
13701       --  the derived type itself is abstract (this check is performed at the
13702       --  end of a package declaration, in Check_Abstract_Overriding). A
13703       --  private overriding in the parent type will not be visible in the
13704       --  derivation if we are not in an inner package or in a child unit of
13705       --  the parent type, in which case the abstractness of the inherited
13706       --  operation is carried to the new subprogram.
13707
13708       elsif Is_Abstract_Type (Parent_Type)
13709         and then not In_Open_Scopes (Scope (Parent_Type))
13710         and then Is_Private_Overriding
13711         and then Is_Abstract_Subprogram (Visible_Subp)
13712       then
13713          if No (Actual_Subp) then
13714             Set_Alias (New_Subp, Visible_Subp);
13715             Set_Is_Abstract_Subprogram (New_Subp, True);
13716
13717          else
13718             --  If this is a derivation for an instance of a formal derived
13719             --  type, abstractness comes from the primitive operation of the
13720             --  actual, not from the operation inherited from the ancestor.
13721
13722             Set_Is_Abstract_Subprogram
13723               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
13724          end if;
13725       end if;
13726
13727       New_Overloaded_Entity (New_Subp, Derived_Type);
13728
13729       --  Check for case of a derived subprogram for the instantiation of a
13730       --  formal derived tagged type, if so mark the subprogram as dispatching
13731       --  and inherit the dispatching attributes of the actual subprogram. The
13732       --  derived subprogram is effectively renaming of the actual subprogram,
13733       --  so it needs to have the same attributes as the actual.
13734
13735       if Present (Actual_Subp)
13736         and then Is_Dispatching_Operation (Actual_Subp)
13737       then
13738          Set_Is_Dispatching_Operation (New_Subp);
13739
13740          if Present (DTC_Entity (Actual_Subp)) then
13741             Set_DTC_Entity (New_Subp, DTC_Entity (Actual_Subp));
13742             Set_DT_Position (New_Subp, DT_Position (Actual_Subp));
13743          end if;
13744       end if;
13745
13746       --  Indicate that a derived subprogram does not require a body and that
13747       --  it does not require processing of default expressions.
13748
13749       Set_Has_Completion (New_Subp);
13750       Set_Default_Expressions_Processed (New_Subp);
13751
13752       if Ekind (New_Subp) = E_Function then
13753          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
13754       end if;
13755    end Derive_Subprogram;
13756
13757    ------------------------
13758    -- Derive_Subprograms --
13759    ------------------------
13760
13761    procedure Derive_Subprograms
13762      (Parent_Type    : Entity_Id;
13763       Derived_Type   : Entity_Id;
13764       Generic_Actual : Entity_Id := Empty)
13765    is
13766       Op_List : constant Elist_Id :=
13767                   Collect_Primitive_Operations (Parent_Type);
13768
13769       function Check_Derived_Type return Boolean;
13770       --  Check that all the entities derived from Parent_Type are found in
13771       --  the list of primitives of Derived_Type exactly in the same order.
13772
13773       procedure Derive_Interface_Subprogram
13774         (New_Subp    : in out Entity_Id;
13775          Subp        : Entity_Id;
13776          Actual_Subp : Entity_Id);
13777       --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
13778       --  (which is an interface primitive). If Generic_Actual is present then
13779       --  Actual_Subp is the actual subprogram corresponding with the generic
13780       --  subprogram Subp.
13781
13782       function Check_Derived_Type return Boolean is
13783          E        : Entity_Id;
13784          Elmt     : Elmt_Id;
13785          List     : Elist_Id;
13786          New_Subp : Entity_Id;
13787          Op_Elmt  : Elmt_Id;
13788          Subp     : Entity_Id;
13789
13790       begin
13791          --  Traverse list of entities in the current scope searching for
13792          --  an incomplete type whose full-view is derived type
13793
13794          E := First_Entity (Scope (Derived_Type));
13795          while Present (E) and then E /= Derived_Type loop
13796             if Ekind (E) = E_Incomplete_Type
13797               and then Present (Full_View (E))
13798               and then Full_View (E) = Derived_Type
13799             then
13800                --  Disable this test if Derived_Type completes an incomplete
13801                --  type because in such case more primitives can be added
13802                --  later to the list of primitives of Derived_Type by routine
13803                --  Process_Incomplete_Dependents
13804
13805                return True;
13806             end if;
13807
13808             E := Next_Entity (E);
13809          end loop;
13810
13811          List := Collect_Primitive_Operations (Derived_Type);
13812          Elmt := First_Elmt (List);
13813
13814          Op_Elmt := First_Elmt (Op_List);
13815          while Present (Op_Elmt) loop
13816             Subp     := Node (Op_Elmt);
13817             New_Subp := Node (Elmt);
13818
13819             --  At this early stage Derived_Type has no entities with attribute
13820             --  Interface_Alias. In addition, such primitives are always
13821             --  located at the end of the list of primitives of Parent_Type.
13822             --  Therefore, if found we can safely stop processing pending
13823             --  entities.
13824
13825             exit when Present (Interface_Alias (Subp));
13826
13827             --  Handle hidden entities
13828
13829             if not Is_Predefined_Dispatching_Operation (Subp)
13830               and then Is_Hidden (Subp)
13831             then
13832                if Present (New_Subp)
13833                  and then Primitive_Names_Match (Subp, New_Subp)
13834                then
13835                   Next_Elmt (Elmt);
13836                end if;
13837
13838             else
13839                if not Present (New_Subp)
13840                  or else Ekind (Subp) /= Ekind (New_Subp)
13841                  or else not Primitive_Names_Match (Subp, New_Subp)
13842                then
13843                   return False;
13844                end if;
13845
13846                Next_Elmt (Elmt);
13847             end if;
13848
13849             Next_Elmt (Op_Elmt);
13850          end loop;
13851
13852          return True;
13853       end Check_Derived_Type;
13854
13855       ---------------------------------
13856       -- Derive_Interface_Subprogram --
13857       ---------------------------------
13858
13859       procedure Derive_Interface_Subprogram
13860         (New_Subp    : in out Entity_Id;
13861          Subp        : Entity_Id;
13862          Actual_Subp : Entity_Id)
13863       is
13864          Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
13865          Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
13866
13867       begin
13868          pragma Assert (Is_Interface (Iface_Type));
13869
13870          Derive_Subprogram
13871            (New_Subp     => New_Subp,
13872             Parent_Subp  => Iface_Subp,
13873             Derived_Type => Derived_Type,
13874             Parent_Type  => Iface_Type,
13875             Actual_Subp  => Actual_Subp);
13876
13877          --  Given that this new interface entity corresponds with a primitive
13878          --  of the parent that was not overridden we must leave it associated
13879          --  with its parent primitive to ensure that it will share the same
13880          --  dispatch table slot when overridden.
13881
13882          if No (Actual_Subp) then
13883             Set_Alias (New_Subp, Subp);
13884
13885          --  For instantiations this is not needed since the previous call to
13886          --  Derive_Subprogram leaves the entity well decorated.
13887
13888          else
13889             pragma Assert (Alias (New_Subp) = Actual_Subp);
13890             null;
13891          end if;
13892       end Derive_Interface_Subprogram;
13893
13894       --  Local variables
13895
13896       Alias_Subp   : Entity_Id;
13897       Act_List     : Elist_Id;
13898       Act_Elmt     : Elmt_Id;
13899       Act_Subp     : Entity_Id := Empty;
13900       Elmt         : Elmt_Id;
13901       Need_Search  : Boolean   := False;
13902       New_Subp     : Entity_Id := Empty;
13903       Parent_Base  : Entity_Id;
13904       Subp         : Entity_Id;
13905
13906    --  Start of processing for Derive_Subprograms
13907
13908    begin
13909       if Ekind (Parent_Type) = E_Record_Type_With_Private
13910         and then Has_Discriminants (Parent_Type)
13911         and then Present (Full_View (Parent_Type))
13912       then
13913          Parent_Base := Full_View (Parent_Type);
13914       else
13915          Parent_Base := Parent_Type;
13916       end if;
13917
13918       if Present (Generic_Actual) then
13919          Act_List := Collect_Primitive_Operations (Generic_Actual);
13920          Act_Elmt := First_Elmt (Act_List);
13921       else
13922          Act_List := No_Elist;
13923          Act_Elmt := No_Elmt;
13924       end if;
13925
13926       --  Derive primitives inherited from the parent. Note that if the generic
13927       --  actual is present, this is not really a type derivation, it is a
13928       --  completion within an instance.
13929
13930       --  Case 1: Derived_Type does not implement interfaces
13931
13932       if not Is_Tagged_Type (Derived_Type)
13933         or else (not Has_Interfaces (Derived_Type)
13934                   and then not (Present (Generic_Actual)
13935                                  and then Has_Interfaces (Generic_Actual)))
13936       then
13937          Elmt := First_Elmt (Op_List);
13938          while Present (Elmt) loop
13939             Subp := Node (Elmt);
13940
13941             --  Literals are derived earlier in the process of building the
13942             --  derived type, and are skipped here.
13943
13944             if Ekind (Subp) = E_Enumeration_Literal then
13945                null;
13946
13947             --  The actual is a direct descendant and the common primitive
13948             --  operations appear in the same order.
13949
13950             --  If the generic parent type is present, the derived type is an
13951             --  instance of a formal derived type, and within the instance its
13952             --  operations are those of the actual. We derive from the formal
13953             --  type but make the inherited operations aliases of the
13954             --  corresponding operations of the actual.
13955
13956             else
13957                pragma Assert (No (Node (Act_Elmt))
13958                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
13959                            and then
13960                              Type_Conformant
13961                                (Subp, Node (Act_Elmt),
13962                                 Skip_Controlling_Formals => True)));
13963
13964                Derive_Subprogram
13965                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
13966
13967                if Present (Act_Elmt) then
13968                   Next_Elmt (Act_Elmt);
13969                end if;
13970             end if;
13971
13972             Next_Elmt (Elmt);
13973          end loop;
13974
13975       --  Case 2: Derived_Type implements interfaces
13976
13977       else
13978          --  If the parent type has no predefined primitives we remove
13979          --  predefined primitives from the list of primitives of generic
13980          --  actual to simplify the complexity of this algorithm.
13981
13982          if Present (Generic_Actual) then
13983             declare
13984                Has_Predefined_Primitives : Boolean := False;
13985
13986             begin
13987                --  Check if the parent type has predefined primitives
13988
13989                Elmt := First_Elmt (Op_List);
13990                while Present (Elmt) loop
13991                   Subp := Node (Elmt);
13992
13993                   if Is_Predefined_Dispatching_Operation (Subp)
13994                     and then not Comes_From_Source (Ultimate_Alias (Subp))
13995                   then
13996                      Has_Predefined_Primitives := True;
13997                      exit;
13998                   end if;
13999
14000                   Next_Elmt (Elmt);
14001                end loop;
14002
14003                --  Remove predefined primitives of Generic_Actual. We must use
14004                --  an auxiliary list because in case of tagged types the value
14005                --  returned by Collect_Primitive_Operations is the value stored
14006                --  in its Primitive_Operations attribute (and we don't want to
14007                --  modify its current contents).
14008
14009                if not Has_Predefined_Primitives then
14010                   declare
14011                      Aux_List : constant Elist_Id := New_Elmt_List;
14012
14013                   begin
14014                      Elmt := First_Elmt (Act_List);
14015                      while Present (Elmt) loop
14016                         Subp := Node (Elmt);
14017
14018                         if not Is_Predefined_Dispatching_Operation (Subp)
14019                           or else Comes_From_Source (Subp)
14020                         then
14021                            Append_Elmt (Subp, Aux_List);
14022                         end if;
14023
14024                         Next_Elmt (Elmt);
14025                      end loop;
14026
14027                      Act_List := Aux_List;
14028                   end;
14029                end if;
14030
14031                Act_Elmt := First_Elmt (Act_List);
14032                Act_Subp := Node (Act_Elmt);
14033             end;
14034          end if;
14035
14036          --  Stage 1: If the generic actual is not present we derive the
14037          --  primitives inherited from the parent type. If the generic parent
14038          --  type is present, the derived type is an instance of a formal
14039          --  derived type, and within the instance its operations are those of
14040          --  the actual. We derive from the formal type but make the inherited
14041          --  operations aliases of the corresponding operations of the actual.
14042
14043          Elmt := First_Elmt (Op_List);
14044          while Present (Elmt) loop
14045             Subp       := Node (Elmt);
14046             Alias_Subp := Ultimate_Alias (Subp);
14047
14048             --  Do not derive internal entities of the parent that link
14049             --  interface primitives with their covering primitive. These
14050             --  entities will be added to this type when frozen.
14051
14052             if Present (Interface_Alias (Subp)) then
14053                goto Continue;
14054             end if;
14055
14056             --  If the generic actual is present find the corresponding
14057             --  operation in the generic actual. If the parent type is a
14058             --  direct ancestor of the derived type then, even if it is an
14059             --  interface, the operations are inherited from the primary
14060             --  dispatch table and are in the proper order. If we detect here
14061             --  that primitives are not in the same order we traverse the list
14062             --  of primitive operations of the actual to find the one that
14063             --  implements the interface primitive.
14064
14065             if Need_Search
14066               or else
14067                 (Present (Generic_Actual)
14068                   and then Present (Act_Subp)
14069                   and then not
14070                     (Primitive_Names_Match (Subp, Act_Subp)
14071                        and then
14072                      Type_Conformant (Subp, Act_Subp,
14073                                       Skip_Controlling_Formals => True)))
14074             then
14075                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
14076                                                Use_Full_View => True));
14077
14078                --  Remember that we need searching for all pending primitives
14079
14080                Need_Search := True;
14081
14082                --  Handle entities associated with interface primitives
14083
14084                if Present (Alias_Subp)
14085                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
14086                  and then not Is_Predefined_Dispatching_Operation (Subp)
14087                then
14088                   --  Search for the primitive in the homonym chain
14089
14090                   Act_Subp :=
14091                     Find_Primitive_Covering_Interface
14092                       (Tagged_Type => Generic_Actual,
14093                        Iface_Prim  => Alias_Subp);
14094
14095                   --  Previous search may not locate primitives covering
14096                   --  interfaces defined in generics units or instantiations.
14097                   --  (it fails if the covering primitive has formals whose
14098                   --  type is also defined in generics or instantiations).
14099                   --  In such case we search in the list of primitives of the
14100                   --  generic actual for the internal entity that links the
14101                   --  interface primitive and the covering primitive.
14102
14103                   if No (Act_Subp)
14104                     and then Is_Generic_Type (Parent_Type)
14105                   then
14106                      --  This code has been designed to handle only generic
14107                      --  formals that implement interfaces that are defined
14108                      --  in a generic unit or instantiation. If this code is
14109                      --  needed for other cases we must review it because
14110                      --  (given that it relies on Original_Location to locate
14111                      --  the primitive of Generic_Actual that covers the
14112                      --  interface) it could leave linked through attribute
14113                      --  Alias entities of unrelated instantiations).
14114
14115                      pragma Assert
14116                        (Is_Generic_Unit
14117                           (Scope (Find_Dispatching_Type (Alias_Subp)))
14118                          or else
14119                            Instantiation_Depth
14120                              (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
14121
14122                      declare
14123                         Iface_Prim_Loc : constant Source_Ptr :=
14124                                          Original_Location (Sloc (Alias_Subp));
14125
14126                         Elmt : Elmt_Id;
14127                         Prim : Entity_Id;
14128
14129                      begin
14130                         Elmt :=
14131                           First_Elmt (Primitive_Operations (Generic_Actual));
14132
14133                         Search : while Present (Elmt) loop
14134                            Prim := Node (Elmt);
14135
14136                            if Present (Interface_Alias (Prim))
14137                              and then Original_Location
14138                                         (Sloc (Interface_Alias (Prim))) =
14139                                                               Iface_Prim_Loc
14140                            then
14141                               Act_Subp := Alias (Prim);
14142                               exit Search;
14143                            end if;
14144
14145                            Next_Elmt (Elmt);
14146                         end loop Search;
14147                      end;
14148                   end if;
14149
14150                   pragma Assert (Present (Act_Subp)
14151                     or else Is_Abstract_Type (Generic_Actual)
14152                     or else Serious_Errors_Detected > 0);
14153
14154                --  Handle predefined primitives plus the rest of user-defined
14155                --  primitives
14156
14157                else
14158                   Act_Elmt := First_Elmt (Act_List);
14159                   while Present (Act_Elmt) loop
14160                      Act_Subp := Node (Act_Elmt);
14161
14162                      exit when Primitive_Names_Match (Subp, Act_Subp)
14163                        and then Type_Conformant
14164                                   (Subp, Act_Subp,
14165                                    Skip_Controlling_Formals => True)
14166                        and then No (Interface_Alias (Act_Subp));
14167
14168                      Next_Elmt (Act_Elmt);
14169                   end loop;
14170
14171                   if No (Act_Elmt) then
14172                      Act_Subp := Empty;
14173                   end if;
14174                end if;
14175             end if;
14176
14177             --   Case 1: If the parent is a limited interface then it has the
14178             --   predefined primitives of synchronized interfaces. However, the
14179             --   actual type may be a non-limited type and hence it does not
14180             --   have such primitives.
14181
14182             if Present (Generic_Actual)
14183               and then not Present (Act_Subp)
14184               and then Is_Limited_Interface (Parent_Base)
14185               and then Is_Predefined_Interface_Primitive (Subp)
14186             then
14187                null;
14188
14189             --  Case 2: Inherit entities associated with interfaces that were
14190             --  not covered by the parent type. We exclude here null interface
14191             --  primitives because they do not need special management.
14192
14193             --  We also exclude interface operations that are renamings. If the
14194             --  subprogram is an explicit renaming of an interface primitive,
14195             --  it is a regular primitive operation, and the presence of its
14196             --  alias is not relevant: it has to be derived like any other
14197             --  primitive.
14198
14199             elsif Present (Alias (Subp))
14200               and then Nkind (Unit_Declaration_Node (Subp)) /=
14201                                             N_Subprogram_Renaming_Declaration
14202               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
14203               and then not
14204                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
14205                   and then Null_Present (Parent (Alias_Subp)))
14206             then
14207                --  If this is an abstract private type then we transfer the
14208                --  derivation of the interface primitive from the partial view
14209                --  to the full view. This is safe because all the interfaces
14210                --  must be visible in the partial view. Done to avoid adding
14211                --  a new interface derivation to the private part of the
14212                --  enclosing package; otherwise this new derivation would be
14213                --  decorated as hidden when the analysis of the enclosing
14214                --  package completes.
14215
14216                if Is_Abstract_Type (Derived_Type)
14217                  and then In_Private_Part (Current_Scope)
14218                  and then Has_Private_Declaration (Derived_Type)
14219                then
14220                   declare
14221                      Partial_View : Entity_Id;
14222                      Elmt         : Elmt_Id;
14223                      Ent          : Entity_Id;
14224
14225                   begin
14226                      Partial_View := First_Entity (Current_Scope);
14227                      loop
14228                         exit when No (Partial_View)
14229                           or else (Has_Private_Declaration (Partial_View)
14230                                      and then
14231                                    Full_View (Partial_View) = Derived_Type);
14232
14233                         Next_Entity (Partial_View);
14234                      end loop;
14235
14236                      --  If the partial view was not found then the source code
14237                      --  has errors and the derivation is not needed.
14238
14239                      if Present (Partial_View) then
14240                         Elmt :=
14241                           First_Elmt (Primitive_Operations (Partial_View));
14242                         while Present (Elmt) loop
14243                            Ent := Node (Elmt);
14244
14245                            if Present (Alias (Ent))
14246                              and then Ultimate_Alias (Ent) = Alias (Subp)
14247                            then
14248                               Append_Elmt
14249                                 (Ent, Primitive_Operations (Derived_Type));
14250                               exit;
14251                            end if;
14252
14253                            Next_Elmt (Elmt);
14254                         end loop;
14255
14256                         --  If the interface primitive was not found in the
14257                         --  partial view then this interface primitive was
14258                         --  overridden. We add a derivation to activate in
14259                         --  Derive_Progenitor_Subprograms the machinery to
14260                         --  search for it.
14261
14262                         if No (Elmt) then
14263                            Derive_Interface_Subprogram
14264                              (New_Subp    => New_Subp,
14265                               Subp        => Subp,
14266                               Actual_Subp => Act_Subp);
14267                         end if;
14268                      end if;
14269                   end;
14270                else
14271                   Derive_Interface_Subprogram
14272                     (New_Subp     => New_Subp,
14273                      Subp         => Subp,
14274                      Actual_Subp  => Act_Subp);
14275                end if;
14276
14277             --  Case 3: Common derivation
14278
14279             else
14280                Derive_Subprogram
14281                  (New_Subp     => New_Subp,
14282                   Parent_Subp  => Subp,
14283                   Derived_Type => Derived_Type,
14284                   Parent_Type  => Parent_Base,
14285                   Actual_Subp  => Act_Subp);
14286             end if;
14287
14288             --  No need to update Act_Elm if we must search for the
14289             --  corresponding operation in the generic actual
14290
14291             if not Need_Search
14292               and then Present (Act_Elmt)
14293             then
14294                Next_Elmt (Act_Elmt);
14295                Act_Subp := Node (Act_Elmt);
14296             end if;
14297
14298             <<Continue>>
14299             Next_Elmt (Elmt);
14300          end loop;
14301
14302          --  Inherit additional operations from progenitors. If the derived
14303          --  type is a generic actual, there are not new primitive operations
14304          --  for the type because it has those of the actual, and therefore
14305          --  nothing needs to be done. The renamings generated above are not
14306          --  primitive operations, and their purpose is simply to make the
14307          --  proper operations visible within an instantiation.
14308
14309          if No (Generic_Actual) then
14310             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
14311          end if;
14312       end if;
14313
14314       --  Final check: Direct descendants must have their primitives in the
14315       --  same order. We exclude from this test untagged types and instances
14316       --  of formal derived types. We skip this test if we have already
14317       --  reported serious errors in the sources.
14318
14319       pragma Assert (not Is_Tagged_Type (Derived_Type)
14320         or else Present (Generic_Actual)
14321         or else Serious_Errors_Detected > 0
14322         or else Check_Derived_Type);
14323    end Derive_Subprograms;
14324
14325    --------------------------------
14326    -- Derived_Standard_Character --
14327    --------------------------------
14328
14329    procedure Derived_Standard_Character
14330      (N            : Node_Id;
14331       Parent_Type  : Entity_Id;
14332       Derived_Type : Entity_Id)
14333    is
14334       Loc           : constant Source_Ptr := Sloc (N);
14335       Def           : constant Node_Id    := Type_Definition (N);
14336       Indic         : constant Node_Id    := Subtype_Indication (Def);
14337       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
14338       Implicit_Base : constant Entity_Id  :=
14339                         Create_Itype
14340                           (E_Enumeration_Type, N, Derived_Type, 'B');
14341
14342       Lo : Node_Id;
14343       Hi : Node_Id;
14344
14345    begin
14346       Discard_Node (Process_Subtype (Indic, N));
14347
14348       Set_Etype     (Implicit_Base, Parent_Base);
14349       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
14350       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
14351
14352       Set_Is_Character_Type  (Implicit_Base, True);
14353       Set_Has_Delayed_Freeze (Implicit_Base);
14354
14355       --  The bounds of the implicit base are the bounds of the parent base.
14356       --  Note that their type is the parent base.
14357
14358       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
14359       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
14360
14361       Set_Scalar_Range (Implicit_Base,
14362         Make_Range (Loc,
14363           Low_Bound  => Lo,
14364           High_Bound => Hi));
14365
14366       Conditional_Delay (Derived_Type, Parent_Type);
14367
14368       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
14369       Set_Etype (Derived_Type, Implicit_Base);
14370       Set_Size_Info         (Derived_Type, Parent_Type);
14371
14372       if Unknown_RM_Size (Derived_Type) then
14373          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
14374       end if;
14375
14376       Set_Is_Character_Type (Derived_Type, True);
14377
14378       if Nkind (Indic) /= N_Subtype_Indication then
14379
14380          --  If no explicit constraint, the bounds are those
14381          --  of the parent type.
14382
14383          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
14384          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
14385          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
14386       end if;
14387
14388       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
14389
14390       --  Because the implicit base is used in the conversion of the bounds, we
14391       --  have to freeze it now. This is similar to what is done for numeric
14392       --  types, and it equally suspicious, but otherwise a non-static bound
14393       --  will have a reference to an unfrozen type, which is rejected by Gigi
14394       --  (???). This requires specific care for definition of stream
14395       --  attributes. For details, see comments at the end of
14396       --  Build_Derived_Numeric_Type.
14397
14398       Freeze_Before (N, Implicit_Base);
14399    end Derived_Standard_Character;
14400
14401    ------------------------------
14402    -- Derived_Type_Declaration --
14403    ------------------------------
14404
14405    procedure Derived_Type_Declaration
14406      (T             : Entity_Id;
14407       N             : Node_Id;
14408       Is_Completion : Boolean)
14409    is
14410       Parent_Type  : Entity_Id;
14411
14412       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
14413       --  Check whether the parent type is a generic formal, or derives
14414       --  directly or indirectly from one.
14415
14416       ------------------------
14417       -- Comes_From_Generic --
14418       ------------------------
14419
14420       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
14421       begin
14422          if Is_Generic_Type (Typ) then
14423             return True;
14424
14425          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
14426             return True;
14427
14428          elsif Is_Private_Type (Typ)
14429            and then Present (Full_View (Typ))
14430            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
14431          then
14432             return True;
14433
14434          elsif Is_Generic_Actual_Type (Typ) then
14435             return True;
14436
14437          else
14438             return False;
14439          end if;
14440       end Comes_From_Generic;
14441
14442       --  Local variables
14443
14444       Def          : constant Node_Id := Type_Definition (N);
14445       Iface_Def    : Node_Id;
14446       Indic        : constant Node_Id := Subtype_Indication (Def);
14447       Extension    : constant Node_Id := Record_Extension_Part (Def);
14448       Parent_Node  : Node_Id;
14449       Taggd        : Boolean;
14450
14451    --  Start of processing for Derived_Type_Declaration
14452
14453    begin
14454       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
14455
14456       --  Ada 2005 (AI-251): In case of interface derivation check that the
14457       --  parent is also an interface.
14458
14459       if Interface_Present (Def) then
14460          Check_SPARK_Restriction ("interface is not allowed", Def);
14461
14462          if not Is_Interface (Parent_Type) then
14463             Diagnose_Interface (Indic, Parent_Type);
14464
14465          else
14466             Parent_Node := Parent (Base_Type (Parent_Type));
14467             Iface_Def   := Type_Definition (Parent_Node);
14468
14469             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
14470             --  other limited interfaces.
14471
14472             if Limited_Present (Def) then
14473                if Limited_Present (Iface_Def) then
14474                   null;
14475
14476                elsif Protected_Present (Iface_Def) then
14477                   Error_Msg_NE
14478                     ("descendant of& must be declared"
14479                        & " as a protected interface",
14480                          N, Parent_Type);
14481
14482                elsif Synchronized_Present (Iface_Def) then
14483                   Error_Msg_NE
14484                     ("descendant of& must be declared"
14485                        & " as a synchronized interface",
14486                          N, Parent_Type);
14487
14488                elsif Task_Present (Iface_Def) then
14489                   Error_Msg_NE
14490                     ("descendant of& must be declared as a task interface",
14491                        N, Parent_Type);
14492
14493                else
14494                   Error_Msg_N
14495                     ("(Ada 2005) limited interface cannot "
14496                      & "inherit from non-limited interface", Indic);
14497                end if;
14498
14499             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
14500             --  from non-limited or limited interfaces.
14501
14502             elsif not Protected_Present (Def)
14503               and then not Synchronized_Present (Def)
14504               and then not Task_Present (Def)
14505             then
14506                if Limited_Present (Iface_Def) then
14507                   null;
14508
14509                elsif Protected_Present (Iface_Def) then
14510                   Error_Msg_NE
14511                     ("descendant of& must be declared"
14512                        & " as a protected interface",
14513                          N, Parent_Type);
14514
14515                elsif Synchronized_Present (Iface_Def) then
14516                   Error_Msg_NE
14517                     ("descendant of& must be declared"
14518                        & " as a synchronized interface",
14519                          N, Parent_Type);
14520
14521                elsif Task_Present (Iface_Def) then
14522                   Error_Msg_NE
14523                     ("descendant of& must be declared as a task interface",
14524                        N, Parent_Type);
14525                else
14526                   null;
14527                end if;
14528             end if;
14529          end if;
14530       end if;
14531
14532       if Is_Tagged_Type (Parent_Type)
14533         and then Is_Concurrent_Type (Parent_Type)
14534         and then not Is_Interface (Parent_Type)
14535       then
14536          Error_Msg_N
14537            ("parent type of a record extension cannot be "
14538             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
14539          Set_Etype (T, Any_Type);
14540          return;
14541       end if;
14542
14543       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
14544       --  interfaces
14545
14546       if Is_Tagged_Type (Parent_Type)
14547         and then Is_Non_Empty_List (Interface_List (Def))
14548       then
14549          declare
14550             Intf : Node_Id;
14551             T    : Entity_Id;
14552
14553          begin
14554             Intf := First (Interface_List (Def));
14555             while Present (Intf) loop
14556                T := Find_Type_Of_Subtype_Indic (Intf);
14557
14558                if not Is_Interface (T) then
14559                   Diagnose_Interface (Intf, T);
14560
14561                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
14562                --  a limited type from having a nonlimited progenitor.
14563
14564                elsif (Limited_Present (Def)
14565                        or else (not Is_Interface (Parent_Type)
14566                                  and then Is_Limited_Type (Parent_Type)))
14567                  and then not Is_Limited_Interface (T)
14568                then
14569                   Error_Msg_NE
14570                    ("progenitor interface& of limited type must be limited",
14571                      N, T);
14572                end if;
14573
14574                Next (Intf);
14575             end loop;
14576          end;
14577       end if;
14578
14579       if Parent_Type = Any_Type
14580         or else Etype (Parent_Type) = Any_Type
14581         or else (Is_Class_Wide_Type (Parent_Type)
14582                    and then Etype (Parent_Type) = T)
14583       then
14584          --  If Parent_Type is undefined or illegal, make new type into a
14585          --  subtype of Any_Type, and set a few attributes to prevent cascaded
14586          --  errors. If this is a self-definition, emit error now.
14587
14588          if T = Parent_Type
14589            or else T = Etype (Parent_Type)
14590          then
14591             Error_Msg_N ("type cannot be used in its own definition", Indic);
14592          end if;
14593
14594          Set_Ekind        (T, Ekind (Parent_Type));
14595          Set_Etype        (T, Any_Type);
14596          Set_Scalar_Range (T, Scalar_Range (Any_Type));
14597
14598          if Is_Tagged_Type (T)
14599            and then Is_Record_Type (T)
14600          then
14601             Set_Direct_Primitive_Operations (T, New_Elmt_List);
14602          end if;
14603
14604          return;
14605       end if;
14606
14607       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
14608       --  an interface is special because the list of interfaces in the full
14609       --  view can be given in any order. For example:
14610
14611       --     type A is interface;
14612       --     type B is interface and A;
14613       --     type D is new B with private;
14614       --   private
14615       --     type D is new A and B with null record; -- 1 --
14616
14617       --  In this case we perform the following transformation of -1-:
14618
14619       --     type D is new B and A with null record;
14620
14621       --  If the parent of the full-view covers the parent of the partial-view
14622       --  we have two possible cases:
14623
14624       --     1) They have the same parent
14625       --     2) The parent of the full-view implements some further interfaces
14626
14627       --  In both cases we do not need to perform the transformation. In the
14628       --  first case the source program is correct and the transformation is
14629       --  not needed; in the second case the source program does not fulfill
14630       --  the no-hidden interfaces rule (AI-396) and the error will be reported
14631       --  later.
14632
14633       --  This transformation not only simplifies the rest of the analysis of
14634       --  this type declaration but also simplifies the correct generation of
14635       --  the object layout to the expander.
14636
14637       if In_Private_Part (Current_Scope)
14638         and then Is_Interface (Parent_Type)
14639       then
14640          declare
14641             Iface               : Node_Id;
14642             Partial_View        : Entity_Id;
14643             Partial_View_Parent : Entity_Id;
14644             New_Iface           : Node_Id;
14645
14646          begin
14647             --  Look for the associated private type declaration
14648
14649             Partial_View := First_Entity (Current_Scope);
14650             loop
14651                exit when No (Partial_View)
14652                  or else (Has_Private_Declaration (Partial_View)
14653                            and then Full_View (Partial_View) = T);
14654
14655                Next_Entity (Partial_View);
14656             end loop;
14657
14658             --  If the partial view was not found then the source code has
14659             --  errors and the transformation is not needed.
14660
14661             if Present (Partial_View) then
14662                Partial_View_Parent := Etype (Partial_View);
14663
14664                --  If the parent of the full-view covers the parent of the
14665                --  partial-view we have nothing else to do.
14666
14667                if Interface_Present_In_Ancestor
14668                     (Parent_Type, Partial_View_Parent)
14669                then
14670                   null;
14671
14672                --  Traverse the list of interfaces of the full-view to look
14673                --  for the parent of the partial-view and perform the tree
14674                --  transformation.
14675
14676                else
14677                   Iface := First (Interface_List (Def));
14678                   while Present (Iface) loop
14679                      if Etype (Iface) = Etype (Partial_View) then
14680                         Rewrite (Subtype_Indication (Def),
14681                           New_Copy (Subtype_Indication
14682                                      (Parent (Partial_View))));
14683
14684                         New_Iface :=
14685                           Make_Identifier (Sloc (N), Chars (Parent_Type));
14686                         Append (New_Iface, Interface_List (Def));
14687
14688                         --  Analyze the transformed code
14689
14690                         Derived_Type_Declaration (T, N, Is_Completion);
14691                         return;
14692                      end if;
14693
14694                      Next (Iface);
14695                   end loop;
14696                end if;
14697             end if;
14698          end;
14699       end if;
14700
14701       --  Only composite types other than array types are allowed to have
14702       --  discriminants. In SPARK, no types are allowed to have discriminants.
14703
14704       if Present (Discriminant_Specifications (N)) then
14705          if (Is_Elementary_Type (Parent_Type)
14706               or else Is_Array_Type (Parent_Type))
14707            and then not Error_Posted (N)
14708          then
14709             Error_Msg_N
14710               ("elementary or array type cannot have discriminants",
14711                Defining_Identifier (First (Discriminant_Specifications (N))));
14712             Set_Has_Discriminants (T, False);
14713          else
14714             Check_SPARK_Restriction ("discriminant type is not allowed", N);
14715          end if;
14716       end if;
14717
14718       --  In Ada 83, a derived type defined in a package specification cannot
14719       --  be used for further derivation until the end of its visible part.
14720       --  Note that derivation in the private part of the package is allowed.
14721
14722       if Ada_Version = Ada_83
14723         and then Is_Derived_Type (Parent_Type)
14724         and then In_Visible_Part (Scope (Parent_Type))
14725       then
14726          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
14727             Error_Msg_N
14728               ("(Ada 83): premature use of type for derivation", Indic);
14729          end if;
14730       end if;
14731
14732       --  Check for early use of incomplete or private type
14733
14734       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
14735          Error_Msg_N ("premature derivation of incomplete type", Indic);
14736          return;
14737
14738       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
14739               and then not Comes_From_Generic (Parent_Type))
14740         or else Has_Private_Component (Parent_Type)
14741       then
14742          --  The ancestor type of a formal type can be incomplete, in which
14743          --  case only the operations of the partial view are available in the
14744          --  generic. Subsequent checks may be required when the full view is
14745          --  analyzed to verify that a derivation from a tagged type has an
14746          --  extension.
14747
14748          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
14749             null;
14750
14751          elsif No (Underlying_Type (Parent_Type))
14752            or else Has_Private_Component (Parent_Type)
14753          then
14754             Error_Msg_N
14755               ("premature derivation of derived or private type", Indic);
14756
14757             --  Flag the type itself as being in error, this prevents some
14758             --  nasty problems with subsequent uses of the malformed type.
14759
14760             Set_Error_Posted (T);
14761
14762          --  Check that within the immediate scope of an untagged partial
14763          --  view it's illegal to derive from the partial view if the
14764          --  full view is tagged. (7.3(7))
14765
14766          --  We verify that the Parent_Type is a partial view by checking
14767          --  that it is not a Full_Type_Declaration (i.e. a private type or
14768          --  private extension declaration), to distinguish a partial view
14769          --  from  a derivation from a private type which also appears as
14770          --  E_Private_Type. If the parent base type is not declared in an
14771          --  enclosing scope there is no need to check.
14772
14773          elsif Present (Full_View (Parent_Type))
14774            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
14775            and then not Is_Tagged_Type (Parent_Type)
14776            and then Is_Tagged_Type (Full_View (Parent_Type))
14777            and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
14778          then
14779             Error_Msg_N
14780               ("premature derivation from type with tagged full view",
14781                 Indic);
14782          end if;
14783       end if;
14784
14785       --  Check that form of derivation is appropriate
14786
14787       Taggd := Is_Tagged_Type (Parent_Type);
14788
14789       --  Perhaps the parent type should be changed to the class-wide type's
14790       --  specific type in this case to prevent cascading errors ???
14791
14792       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
14793          Error_Msg_N ("parent type must not be a class-wide type", Indic);
14794          return;
14795       end if;
14796
14797       if Present (Extension) and then not Taggd then
14798          Error_Msg_N
14799            ("type derived from untagged type cannot have extension", Indic);
14800
14801       elsif No (Extension) and then Taggd then
14802
14803          --  If this declaration is within a private part (or body) of a
14804          --  generic instantiation then the derivation is allowed (the parent
14805          --  type can only appear tagged in this case if it's a generic actual
14806          --  type, since it would otherwise have been rejected in the analysis
14807          --  of the generic template).
14808
14809          if not Is_Generic_Actual_Type (Parent_Type)
14810            or else In_Visible_Part (Scope (Parent_Type))
14811          then
14812             if Is_Class_Wide_Type (Parent_Type) then
14813                Error_Msg_N
14814                  ("parent type must not be a class-wide type", Indic);
14815
14816                --  Use specific type to prevent cascaded errors.
14817
14818                Parent_Type := Etype (Parent_Type);
14819
14820             else
14821                Error_Msg_N
14822                  ("type derived from tagged type must have extension", Indic);
14823             end if;
14824          end if;
14825       end if;
14826
14827       --  AI-443: Synchronized formal derived types require a private
14828       --  extension. There is no point in checking the ancestor type or
14829       --  the progenitors since the construct is wrong to begin with.
14830
14831       if Ada_Version >= Ada_2005
14832         and then Is_Generic_Type (T)
14833         and then Present (Original_Node (N))
14834       then
14835          declare
14836             Decl : constant Node_Id := Original_Node (N);
14837
14838          begin
14839             if Nkind (Decl) = N_Formal_Type_Declaration
14840               and then Nkind (Formal_Type_Definition (Decl)) =
14841                          N_Formal_Derived_Type_Definition
14842               and then Synchronized_Present (Formal_Type_Definition (Decl))
14843               and then No (Extension)
14844
14845                --  Avoid emitting a duplicate error message
14846
14847               and then not Error_Posted (Indic)
14848             then
14849                Error_Msg_N
14850                  ("synchronized derived type must have extension", N);
14851             end if;
14852          end;
14853       end if;
14854
14855       if Null_Exclusion_Present (Def)
14856         and then not Is_Access_Type (Parent_Type)
14857       then
14858          Error_Msg_N ("null exclusion can only apply to an access type", N);
14859       end if;
14860
14861       --  Avoid deriving parent primitives of underlying record views
14862
14863       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
14864         Derive_Subps => not Is_Underlying_Record_View (T));
14865
14866       --  AI-419: The parent type of an explicitly limited derived type must
14867       --  be a limited type or a limited interface.
14868
14869       if Limited_Present (Def) then
14870          Set_Is_Limited_Record (T);
14871
14872          if Is_Interface (T) then
14873             Set_Is_Limited_Interface (T);
14874          end if;
14875
14876          if not Is_Limited_Type (Parent_Type)
14877            and then
14878              (not Is_Interface (Parent_Type)
14879                or else not Is_Limited_Interface (Parent_Type))
14880          then
14881             --  AI05-0096: a derivation in the private part of an instance is
14882             --  legal if the generic formal is untagged limited, and the actual
14883             --  is non-limited.
14884
14885             if Is_Generic_Actual_Type (Parent_Type)
14886               and then In_Private_Part (Current_Scope)
14887               and then
14888                 not Is_Tagged_Type
14889                       (Generic_Parent_Type (Parent (Parent_Type)))
14890             then
14891                null;
14892
14893             else
14894                Error_Msg_NE
14895                  ("parent type& of limited type must be limited",
14896                   N, Parent_Type);
14897             end if;
14898          end if;
14899       end if;
14900
14901       --  In SPARK, there are no derived type definitions other than type
14902       --  extensions of tagged record types.
14903
14904       if No (Extension) then
14905          Check_SPARK_Restriction
14906            ("derived type is not allowed", Original_Node (N));
14907       end if;
14908    end Derived_Type_Declaration;
14909
14910    ------------------------
14911    -- Diagnose_Interface --
14912    ------------------------
14913
14914    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
14915    begin
14916       if not Is_Interface (E)
14917         and then  E /= Any_Type
14918       then
14919          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
14920       end if;
14921    end Diagnose_Interface;
14922
14923    ----------------------------------
14924    -- Enumeration_Type_Declaration --
14925    ----------------------------------
14926
14927    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14928       Ev     : Uint;
14929       L      : Node_Id;
14930       R_Node : Node_Id;
14931       B_Node : Node_Id;
14932
14933    begin
14934       --  Create identifier node representing lower bound
14935
14936       B_Node := New_Node (N_Identifier, Sloc (Def));
14937       L := First (Literals (Def));
14938       Set_Chars (B_Node, Chars (L));
14939       Set_Entity (B_Node,  L);
14940       Set_Etype (B_Node, T);
14941       Set_Is_Static_Expression (B_Node, True);
14942
14943       R_Node := New_Node (N_Range, Sloc (Def));
14944       Set_Low_Bound  (R_Node, B_Node);
14945
14946       Set_Ekind (T, E_Enumeration_Type);
14947       Set_First_Literal (T, L);
14948       Set_Etype (T, T);
14949       Set_Is_Constrained (T);
14950
14951       Ev := Uint_0;
14952
14953       --  Loop through literals of enumeration type setting pos and rep values
14954       --  except that if the Ekind is already set, then it means the literal
14955       --  was already constructed (case of a derived type declaration and we
14956       --  should not disturb the Pos and Rep values.
14957
14958       while Present (L) loop
14959          if Ekind (L) /= E_Enumeration_Literal then
14960             Set_Ekind (L, E_Enumeration_Literal);
14961             Set_Enumeration_Pos (L, Ev);
14962             Set_Enumeration_Rep (L, Ev);
14963             Set_Is_Known_Valid  (L, True);
14964          end if;
14965
14966          Set_Etype (L, T);
14967          New_Overloaded_Entity (L);
14968          Generate_Definition (L);
14969          Set_Convention (L, Convention_Intrinsic);
14970
14971          --  Case of character literal
14972
14973          if Nkind (L) = N_Defining_Character_Literal then
14974             Set_Is_Character_Type (T, True);
14975
14976             --  Check violation of No_Wide_Characters
14977
14978             if Restriction_Check_Required (No_Wide_Characters) then
14979                Get_Name_String (Chars (L));
14980
14981                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
14982                   Check_Restriction (No_Wide_Characters, L);
14983                end if;
14984             end if;
14985          end if;
14986
14987          Ev := Ev + 1;
14988          Next (L);
14989       end loop;
14990
14991       --  Now create a node representing upper bound
14992
14993       B_Node := New_Node (N_Identifier, Sloc (Def));
14994       Set_Chars (B_Node, Chars (Last (Literals (Def))));
14995       Set_Entity (B_Node,  Last (Literals (Def)));
14996       Set_Etype (B_Node, T);
14997       Set_Is_Static_Expression (B_Node, True);
14998
14999       Set_High_Bound (R_Node, B_Node);
15000
15001       --  Initialize various fields of the type. Some of this information
15002       --  may be overwritten later through rep.clauses.
15003
15004       Set_Scalar_Range    (T, R_Node);
15005       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
15006       Set_Enum_Esize      (T);
15007       Set_Enum_Pos_To_Rep (T, Empty);
15008
15009       --  Set Discard_Names if configuration pragma set, or if there is
15010       --  a parameterless pragma in the current declarative region
15011
15012       if Global_Discard_Names or else Discard_Names (Scope (T)) then
15013          Set_Discard_Names (T);
15014       end if;
15015
15016       --  Process end label if there is one
15017
15018       if Present (Def) then
15019          Process_End_Label (Def, 'e', T);
15020       end if;
15021    end Enumeration_Type_Declaration;
15022
15023    ---------------------------------
15024    -- Expand_To_Stored_Constraint --
15025    ---------------------------------
15026
15027    function Expand_To_Stored_Constraint
15028      (Typ        : Entity_Id;
15029       Constraint : Elist_Id) return Elist_Id
15030    is
15031       Explicitly_Discriminated_Type : Entity_Id;
15032       Expansion    : Elist_Id;
15033       Discriminant : Entity_Id;
15034
15035       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
15036       --  Find the nearest type that actually specifies discriminants
15037
15038       ---------------------------------
15039       -- Type_With_Explicit_Discrims --
15040       ---------------------------------
15041
15042       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
15043          Typ : constant E := Base_Type (Id);
15044
15045       begin
15046          if Ekind (Typ) in Incomplete_Or_Private_Kind then
15047             if Present (Full_View (Typ)) then
15048                return Type_With_Explicit_Discrims (Full_View (Typ));
15049             end if;
15050
15051          else
15052             if Has_Discriminants (Typ) then
15053                return Typ;
15054             end if;
15055          end if;
15056
15057          if Etype (Typ) = Typ then
15058             return Empty;
15059          elsif Has_Discriminants (Typ) then
15060             return Typ;
15061          else
15062             return Type_With_Explicit_Discrims (Etype (Typ));
15063          end if;
15064
15065       end Type_With_Explicit_Discrims;
15066
15067    --  Start of processing for Expand_To_Stored_Constraint
15068
15069    begin
15070       if No (Constraint)
15071         or else Is_Empty_Elmt_List (Constraint)
15072       then
15073          return No_Elist;
15074       end if;
15075
15076       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
15077
15078       if No (Explicitly_Discriminated_Type) then
15079          return No_Elist;
15080       end if;
15081
15082       Expansion := New_Elmt_List;
15083
15084       Discriminant :=
15085          First_Stored_Discriminant (Explicitly_Discriminated_Type);
15086       while Present (Discriminant) loop
15087          Append_Elmt (
15088            Get_Discriminant_Value (
15089              Discriminant, Explicitly_Discriminated_Type, Constraint),
15090            Expansion);
15091          Next_Stored_Discriminant (Discriminant);
15092       end loop;
15093
15094       return Expansion;
15095    end Expand_To_Stored_Constraint;
15096
15097    ---------------------------
15098    -- Find_Hidden_Interface --
15099    ---------------------------
15100
15101    function Find_Hidden_Interface
15102      (Src  : Elist_Id;
15103       Dest : Elist_Id) return Entity_Id
15104    is
15105       Iface      : Entity_Id;
15106       Iface_Elmt : Elmt_Id;
15107
15108    begin
15109       if Present (Src) and then Present (Dest) then
15110          Iface_Elmt := First_Elmt (Src);
15111          while Present (Iface_Elmt) loop
15112             Iface := Node (Iface_Elmt);
15113
15114             if Is_Interface (Iface)
15115               and then not Contain_Interface (Iface, Dest)
15116             then
15117                return Iface;
15118             end if;
15119
15120             Next_Elmt (Iface_Elmt);
15121          end loop;
15122       end if;
15123
15124       return Empty;
15125    end Find_Hidden_Interface;
15126
15127    --------------------
15128    -- Find_Type_Name --
15129    --------------------
15130
15131    function Find_Type_Name (N : Node_Id) return Entity_Id is
15132       Id       : constant Entity_Id := Defining_Identifier (N);
15133       Prev     : Entity_Id;
15134       New_Id   : Entity_Id;
15135       Prev_Par : Node_Id;
15136
15137       procedure Check_Duplicate_Aspects;
15138       --  Check that aspects specified in a completion have not been specified
15139       --  already in the partial view. Type_Invariant and others can be
15140       --  specified on either view but never on both.
15141
15142       procedure Tag_Mismatch;
15143       --  Diagnose a tagged partial view whose full view is untagged.
15144       --  We post the message on the full view, with a reference to
15145       --  the previous partial view. The partial view can be private
15146       --  or incomplete, and these are handled in a different manner,
15147       --  so we determine the position of the error message from the
15148       --  respective slocs of both.
15149
15150       -----------------------------
15151       -- Check_Duplicate_Aspects --
15152       -----------------------------
15153       procedure Check_Duplicate_Aspects is
15154          Prev_Aspects   : constant List_Id := Aspect_Specifications (Prev_Par);
15155          Full_Aspects   : constant List_Id := Aspect_Specifications (N);
15156          F_Spec, P_Spec : Node_Id;
15157
15158       begin
15159          if Present (Prev_Aspects) and then Present (Full_Aspects) then
15160             F_Spec := First (Full_Aspects);
15161             while Present (F_Spec) loop
15162                P_Spec := First (Prev_Aspects);
15163                while Present (P_Spec) loop
15164                   if
15165                     Chars (Identifier (P_Spec)) = Chars (Identifier (F_Spec))
15166                   then
15167                      Error_Msg_N
15168                        ("aspect already specified in private declaration",
15169                          F_Spec);
15170                      Remove (F_Spec);
15171                      return;
15172                   end if;
15173
15174                   Next (P_Spec);
15175                end loop;
15176
15177                Next (F_Spec);
15178             end loop;
15179          end if;
15180       end Check_Duplicate_Aspects;
15181
15182       ------------------
15183       -- Tag_Mismatch --
15184       ------------------
15185
15186       procedure Tag_Mismatch is
15187       begin
15188          if Sloc (Prev) < Sloc (Id) then
15189             if Ada_Version >= Ada_2012
15190               and then Nkind (N) = N_Private_Type_Declaration
15191             then
15192                Error_Msg_NE
15193                  ("declaration of private } must be a tagged type ", Id, Prev);
15194             else
15195                Error_Msg_NE
15196                  ("full declaration of } must be a tagged type ", Id, Prev);
15197             end if;
15198          else
15199             if Ada_Version >= Ada_2012
15200               and then Nkind (N) = N_Private_Type_Declaration
15201             then
15202                Error_Msg_NE
15203                  ("declaration of private } must be a tagged type ", Prev, Id);
15204             else
15205                Error_Msg_NE
15206                  ("full declaration of } must be a tagged type ", Prev, Id);
15207             end if;
15208          end if;
15209       end Tag_Mismatch;
15210
15211    --  Start of processing for Find_Type_Name
15212
15213    begin
15214       --  Find incomplete declaration, if one was given
15215
15216       Prev := Current_Entity_In_Scope (Id);
15217
15218       --  New type declaration
15219
15220       if No (Prev) then
15221          Enter_Name (Id);
15222          return Id;
15223
15224       --  Previous declaration exists
15225
15226       else
15227          Prev_Par := Parent (Prev);
15228
15229          --  Error if not incomplete/private case except if previous
15230          --  declaration is implicit, etc. Enter_Name will emit error if
15231          --  appropriate.
15232
15233          if not Is_Incomplete_Or_Private_Type (Prev) then
15234             Enter_Name (Id);
15235             New_Id := Id;
15236
15237          --  Check invalid completion of private or incomplete type
15238
15239          elsif not Nkind_In (N, N_Full_Type_Declaration,
15240                                 N_Task_Type_Declaration,
15241                                 N_Protected_Type_Declaration)
15242            and then
15243              (Ada_Version < Ada_2012
15244                 or else not Is_Incomplete_Type (Prev)
15245                 or else not Nkind_In (N, N_Private_Type_Declaration,
15246                                          N_Private_Extension_Declaration))
15247          then
15248             --  Completion must be a full type declarations (RM 7.3(4))
15249
15250             Error_Msg_Sloc := Sloc (Prev);
15251             Error_Msg_NE ("invalid completion of }", Id, Prev);
15252
15253             --  Set scope of Id to avoid cascaded errors. Entity is never
15254             --  examined again, except when saving globals in generics.
15255
15256             Set_Scope (Id, Current_Scope);
15257             New_Id := Id;
15258
15259             --  If this is a repeated incomplete declaration, no further
15260             --  checks are possible.
15261
15262             if Nkind (N) = N_Incomplete_Type_Declaration then
15263                return Prev;
15264             end if;
15265
15266          --  Case of full declaration of incomplete type
15267
15268          elsif Ekind (Prev) = E_Incomplete_Type
15269            and then (Ada_Version < Ada_2012
15270                       or else No (Full_View (Prev))
15271                       or else not Is_Private_Type (Full_View (Prev)))
15272          then
15273
15274             --  Indicate that the incomplete declaration has a matching full
15275             --  declaration. The defining occurrence of the incomplete
15276             --  declaration remains the visible one, and the procedure
15277             --  Get_Full_View dereferences it whenever the type is used.
15278
15279             if Present (Full_View (Prev)) then
15280                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
15281             end if;
15282
15283             Set_Full_View (Prev, Id);
15284             Append_Entity (Id, Current_Scope);
15285             Set_Is_Public (Id, Is_Public (Prev));
15286             Set_Is_Internal (Id);
15287             New_Id := Prev;
15288
15289             --  If the incomplete view is tagged, a class_wide type has been
15290             --  created already. Use it for the private type as well, in order
15291             --  to prevent multiple incompatible class-wide types that may be
15292             --  created for self-referential anonymous access components.
15293
15294             if Is_Tagged_Type (Prev)
15295               and then Present (Class_Wide_Type (Prev))
15296             then
15297                Set_Ekind (Id, Ekind (Prev));         --  will be reset later
15298                Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
15299
15300                --  If the incomplete type is completed by a private declaration
15301                --  the class-wide type remains associated with the incomplete
15302                --  type, to prevent order-of-elaboration issues in gigi, else
15303                --  we associate the class-wide type with the known full view.
15304
15305                if Nkind (N) /= N_Private_Type_Declaration then
15306                   Set_Etype (Class_Wide_Type (Id), Id);
15307                end if;
15308             end if;
15309
15310          --  Case of full declaration of private type
15311
15312          else
15313             --  If the private type was a completion of an incomplete type then
15314             --  update Prev to reference the private type
15315
15316             if Ada_Version >= Ada_2012
15317               and then Ekind (Prev) = E_Incomplete_Type
15318               and then Present (Full_View (Prev))
15319               and then Is_Private_Type (Full_View (Prev))
15320             then
15321                Prev := Full_View (Prev);
15322                Prev_Par := Parent (Prev);
15323             end if;
15324
15325             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
15326                if Etype (Prev) /= Prev then
15327
15328                   --  Prev is a private subtype or a derived type, and needs
15329                   --  no completion.
15330
15331                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
15332                   New_Id := Id;
15333
15334                elsif Ekind (Prev) = E_Private_Type
15335                  and then Nkind_In (N, N_Task_Type_Declaration,
15336                                        N_Protected_Type_Declaration)
15337                then
15338                   Error_Msg_N
15339                    ("completion of nonlimited type cannot be limited", N);
15340
15341                elsif Ekind (Prev) = E_Record_Type_With_Private
15342                  and then Nkind_In (N, N_Task_Type_Declaration,
15343                                        N_Protected_Type_Declaration)
15344                then
15345                   if not Is_Limited_Record (Prev) then
15346                      Error_Msg_N
15347                         ("completion of nonlimited type cannot be limited", N);
15348
15349                   elsif No (Interface_List (N)) then
15350                      Error_Msg_N
15351                         ("completion of tagged private type must be tagged",
15352                          N);
15353                   end if;
15354
15355                elsif Nkind (N) = N_Full_Type_Declaration
15356                  and then
15357                    Nkind (Type_Definition (N)) = N_Record_Definition
15358                  and then Interface_Present (Type_Definition (N))
15359                then
15360                   Error_Msg_N
15361                     ("completion of private type cannot be an interface", N);
15362                end if;
15363
15364             --  Ada 2005 (AI-251): Private extension declaration of a task
15365             --  type or a protected type. This case arises when covering
15366             --  interface types.
15367
15368             elsif Nkind_In (N, N_Task_Type_Declaration,
15369                                N_Protected_Type_Declaration)
15370             then
15371                null;
15372
15373             elsif Nkind (N) /= N_Full_Type_Declaration
15374               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
15375             then
15376                Error_Msg_N
15377                  ("full view of private extension must be an extension", N);
15378
15379             elsif not (Abstract_Present (Parent (Prev)))
15380               and then Abstract_Present (Type_Definition (N))
15381             then
15382                Error_Msg_N
15383                  ("full view of non-abstract extension cannot be abstract", N);
15384             end if;
15385
15386             if not In_Private_Part (Current_Scope) then
15387                Error_Msg_N
15388                  ("declaration of full view must appear in private part", N);
15389             end if;
15390
15391             if Ada_Version >= Ada_2012 then
15392                Check_Duplicate_Aspects;
15393             end if;
15394
15395             Copy_And_Swap (Prev, Id);
15396             Set_Has_Private_Declaration (Prev);
15397             Set_Has_Private_Declaration (Id);
15398
15399             --  Preserve aspect and iterator flags that may have been set on
15400             --  the partial view.
15401
15402             Set_Has_Delayed_Aspects (Prev, Has_Delayed_Aspects (Id));
15403             Set_Has_Implicit_Dereference (Prev, Has_Implicit_Dereference (Id));
15404
15405             --  If no error, propagate freeze_node from private to full view.
15406             --  It may have been generated for an early operational item.
15407
15408             if Present (Freeze_Node (Id))
15409               and then Serious_Errors_Detected = 0
15410               and then No (Full_View (Id))
15411             then
15412                Set_Freeze_Node (Prev, Freeze_Node (Id));
15413                Set_Freeze_Node (Id, Empty);
15414                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
15415             end if;
15416
15417             Set_Full_View (Id, Prev);
15418             New_Id := Prev;
15419          end if;
15420
15421          --  Verify that full declaration conforms to partial one
15422
15423          if Is_Incomplete_Or_Private_Type (Prev)
15424            and then Present (Discriminant_Specifications (Prev_Par))
15425          then
15426             if Present (Discriminant_Specifications (N)) then
15427                if Ekind (Prev) = E_Incomplete_Type then
15428                   Check_Discriminant_Conformance (N, Prev, Prev);
15429                else
15430                   Check_Discriminant_Conformance (N, Prev, Id);
15431                end if;
15432
15433             else
15434                Error_Msg_N
15435                  ("missing discriminants in full type declaration", N);
15436
15437                --  To avoid cascaded errors on subsequent use, share the
15438                --  discriminants of the partial view.
15439
15440                Set_Discriminant_Specifications (N,
15441                  Discriminant_Specifications (Prev_Par));
15442             end if;
15443          end if;
15444
15445          --  A prior untagged partial view can have an associated class-wide
15446          --  type due to use of the class attribute, and in this case the full
15447          --  type must also be tagged. This Ada 95 usage is deprecated in favor
15448          --  of incomplete tagged declarations, but we check for it.
15449
15450          if Is_Type (Prev)
15451            and then (Is_Tagged_Type (Prev)
15452                        or else Present (Class_Wide_Type (Prev)))
15453          then
15454             --  Ada 2012 (AI05-0162): A private type may be the completion of
15455             --  an incomplete type
15456
15457             if Ada_Version >= Ada_2012
15458               and then Is_Incomplete_Type (Prev)
15459               and then Nkind_In (N, N_Private_Type_Declaration,
15460                                     N_Private_Extension_Declaration)
15461             then
15462                --  No need to check private extensions since they are tagged
15463
15464                if Nkind (N) = N_Private_Type_Declaration
15465                  and then not Tagged_Present (N)
15466                then
15467                   Tag_Mismatch;
15468                end if;
15469
15470             --  The full declaration is either a tagged type (including
15471             --  a synchronized type that implements interfaces) or a
15472             --  type extension, otherwise this is an error.
15473
15474             elsif Nkind_In (N, N_Task_Type_Declaration,
15475                                N_Protected_Type_Declaration)
15476             then
15477                if No (Interface_List (N))
15478                  and then not Error_Posted (N)
15479                then
15480                   Tag_Mismatch;
15481                end if;
15482
15483             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
15484
15485                --  Indicate that the previous declaration (tagged incomplete
15486                --  or private declaration) requires the same on the full one.
15487
15488                if not Tagged_Present (Type_Definition (N)) then
15489                   Tag_Mismatch;
15490                   Set_Is_Tagged_Type (Id);
15491                end if;
15492
15493             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
15494                if No (Record_Extension_Part (Type_Definition (N))) then
15495                   Error_Msg_NE
15496                     ("full declaration of } must be a record extension",
15497                      Prev, Id);
15498
15499                   --  Set some attributes to produce a usable full view
15500
15501                   Set_Is_Tagged_Type (Id);
15502                end if;
15503
15504             else
15505                Tag_Mismatch;
15506             end if;
15507          end if;
15508
15509          if Present (Prev)
15510            and then Nkind (Parent (Prev)) = N_Incomplete_Type_Declaration
15511            and then Present (Premature_Use (Parent (Prev)))
15512          then
15513             Error_Msg_Sloc := Sloc (N);
15514             Error_Msg_N
15515               ("\full declaration #", Premature_Use (Parent (Prev)));
15516          end if;
15517
15518          return New_Id;
15519       end if;
15520    end Find_Type_Name;
15521
15522    -------------------------
15523    -- Find_Type_Of_Object --
15524    -------------------------
15525
15526    function Find_Type_Of_Object
15527      (Obj_Def     : Node_Id;
15528       Related_Nod : Node_Id) return Entity_Id
15529    is
15530       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
15531       P        : Node_Id := Parent (Obj_Def);
15532       T        : Entity_Id;
15533       Nam      : Name_Id;
15534
15535    begin
15536       --  If the parent is a component_definition node we climb to the
15537       --  component_declaration node
15538
15539       if Nkind (P) = N_Component_Definition then
15540          P := Parent (P);
15541       end if;
15542
15543       --  Case of an anonymous array subtype
15544
15545       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
15546                              N_Unconstrained_Array_Definition)
15547       then
15548          T := Empty;
15549          Array_Type_Declaration (T, Obj_Def);
15550
15551       --  Create an explicit subtype whenever possible
15552
15553       elsif Nkind (P) /= N_Component_Declaration
15554         and then Def_Kind = N_Subtype_Indication
15555       then
15556          --  Base name of subtype on object name, which will be unique in
15557          --  the current scope.
15558
15559          --  If this is a duplicate declaration, return base type, to avoid
15560          --  generating duplicate anonymous types.
15561
15562          if Error_Posted (P) then
15563             Analyze (Subtype_Mark (Obj_Def));
15564             return Entity (Subtype_Mark (Obj_Def));
15565          end if;
15566
15567          Nam :=
15568             New_External_Name
15569              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
15570
15571          T := Make_Defining_Identifier (Sloc (P), Nam);
15572
15573          Insert_Action (Obj_Def,
15574            Make_Subtype_Declaration (Sloc (P),
15575              Defining_Identifier => T,
15576              Subtype_Indication  => Relocate_Node (Obj_Def)));
15577
15578          --  This subtype may need freezing, and this will not be done
15579          --  automatically if the object declaration is not in declarative
15580          --  part. Since this is an object declaration, the type cannot always
15581          --  be frozen here. Deferred constants do not freeze their type
15582          --  (which often enough will be private).
15583
15584          if Nkind (P) = N_Object_Declaration
15585            and then Constant_Present (P)
15586            and then No (Expression (P))
15587          then
15588             null;
15589          else
15590             Insert_Actions (Obj_Def, Freeze_Entity (T, P));
15591          end if;
15592
15593       --  Ada 2005 AI-406: the object definition in an object declaration
15594       --  can be an access definition.
15595
15596       elsif Def_Kind = N_Access_Definition then
15597          T := Access_Definition (Related_Nod, Obj_Def);
15598
15599          Set_Is_Local_Anonymous_Access
15600            (T,
15601             V => (Ada_Version < Ada_2012)
15602                    or else (Nkind (P) /= N_Object_Declaration)
15603                    or else Is_Library_Level_Entity (Defining_Identifier (P)));
15604
15605       --  Otherwise, the object definition is just a subtype_mark
15606
15607       else
15608          T := Process_Subtype (Obj_Def, Related_Nod);
15609
15610          --  If expansion is disabled an object definition that is an aggregate
15611          --  will not get expanded and may lead to scoping problems in the back
15612          --  end, if the object is referenced in an inner scope. In that case
15613          --  create an itype reference for the object definition now. This
15614          --  may be redundant in some cases, but harmless.
15615
15616          if Is_Itype (T)
15617            and then Nkind (Related_Nod) = N_Object_Declaration
15618            and then ASIS_Mode
15619          then
15620             Build_Itype_Reference (T, Related_Nod);
15621          end if;
15622       end if;
15623
15624       return T;
15625    end Find_Type_Of_Object;
15626
15627    --------------------------------
15628    -- Find_Type_Of_Subtype_Indic --
15629    --------------------------------
15630
15631    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
15632       Typ : Entity_Id;
15633
15634    begin
15635       --  Case of subtype mark with a constraint
15636
15637       if Nkind (S) = N_Subtype_Indication then
15638          Find_Type (Subtype_Mark (S));
15639          Typ := Entity (Subtype_Mark (S));
15640
15641          if not
15642            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
15643          then
15644             Error_Msg_N
15645               ("incorrect constraint for this kind of type", Constraint (S));
15646             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
15647          end if;
15648
15649       --  Otherwise we have a subtype mark without a constraint
15650
15651       elsif Error_Posted (S) then
15652          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
15653          return Any_Type;
15654
15655       else
15656          Find_Type (S);
15657          Typ := Entity (S);
15658       end if;
15659
15660       --  Check No_Wide_Characters restriction
15661
15662       Check_Wide_Character_Restriction (Typ, S);
15663
15664       return Typ;
15665    end Find_Type_Of_Subtype_Indic;
15666
15667    -------------------------------------
15668    -- Floating_Point_Type_Declaration --
15669    -------------------------------------
15670
15671    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
15672       Digs          : constant Node_Id := Digits_Expression (Def);
15673       Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
15674       Digs_Val      : Uint;
15675       Base_Typ      : Entity_Id;
15676       Implicit_Base : Entity_Id;
15677       Bound         : Node_Id;
15678
15679       function Can_Derive_From (E : Entity_Id) return Boolean;
15680       --  Find if given digits value, and possibly a specified range, allows
15681       --  derivation from specified type
15682
15683       function Find_Base_Type return Entity_Id;
15684       --  Find a predefined base type that Def can derive from, or generate
15685       --  an error and substitute Long_Long_Float if none exists.
15686
15687       ---------------------
15688       -- Can_Derive_From --
15689       ---------------------
15690
15691       function Can_Derive_From (E : Entity_Id) return Boolean is
15692          Spec : constant Entity_Id := Real_Range_Specification (Def);
15693
15694       begin
15695          --  Check specified "digits" constraint
15696
15697          if Digs_Val > Digits_Value (E) then
15698             return False;
15699          end if;
15700
15701          --  Avoid types not matching pragma Float_Representation, if present
15702
15703          if (Opt.Float_Format = 'I' and then Float_Rep (E) /= IEEE_Binary)
15704               or else
15705             (Opt.Float_Format = 'V' and then Float_Rep (E) /= VAX_Native)
15706          then
15707             return False;
15708          end if;
15709
15710          --  Check for matching range, if specified
15711
15712          if Present (Spec) then
15713             if Expr_Value_R (Type_Low_Bound (E)) >
15714                Expr_Value_R (Low_Bound (Spec))
15715             then
15716                return False;
15717             end if;
15718
15719             if Expr_Value_R (Type_High_Bound (E)) <
15720                Expr_Value_R (High_Bound (Spec))
15721             then
15722                return False;
15723             end if;
15724          end if;
15725
15726          return True;
15727       end Can_Derive_From;
15728
15729       --------------------
15730       -- Find_Base_Type --
15731       --------------------
15732
15733       function Find_Base_Type return Entity_Id is
15734          Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
15735
15736       begin
15737          --  Iterate over the predefined types in order, returning the first
15738          --  one that Def can derive from.
15739
15740          while Present (Choice) loop
15741             if Can_Derive_From (Node (Choice)) then
15742                return Node (Choice);
15743             end if;
15744
15745             Next_Elmt (Choice);
15746          end loop;
15747
15748          --  If we can't derive from any existing type, use Long_Long_Float
15749          --  and give appropriate message explaining the problem.
15750
15751          if Digs_Val > Max_Digs_Val then
15752             --  It might be the case that there is a type with the requested
15753             --  range, just not the combination of digits and range.
15754
15755             Error_Msg_N
15756               ("no predefined type has requested range and precision",
15757                Real_Range_Specification (Def));
15758
15759          else
15760             Error_Msg_N
15761               ("range too large for any predefined type",
15762                Real_Range_Specification (Def));
15763          end if;
15764
15765          return Standard_Long_Long_Float;
15766       end Find_Base_Type;
15767
15768    --  Start of processing for Floating_Point_Type_Declaration
15769
15770    begin
15771       Check_Restriction (No_Floating_Point, Def);
15772
15773       --  Create an implicit base type
15774
15775       Implicit_Base :=
15776         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
15777
15778       --  Analyze and verify digits value
15779
15780       Analyze_And_Resolve (Digs, Any_Integer);
15781       Check_Digits_Expression (Digs);
15782       Digs_Val := Expr_Value (Digs);
15783
15784       --  Process possible range spec and find correct type to derive from
15785
15786       Process_Real_Range_Specification (Def);
15787
15788       --  Check that requested number of digits is not too high.
15789
15790       if Digs_Val > Max_Digs_Val then
15791          --  The check for Max_Base_Digits may be somewhat expensive, as it
15792          --  requires reading System, so only do it when necessary.
15793
15794          declare
15795             Max_Base_Digits : constant Uint :=
15796                                 Expr_Value
15797                                   (Expression
15798                                      (Parent (RTE (RE_Max_Base_Digits))));
15799
15800          begin
15801             if Digs_Val > Max_Base_Digits then
15802                Error_Msg_Uint_1 := Max_Base_Digits;
15803                Error_Msg_N ("digits value out of range, maximum is ^", Digs);
15804
15805             elsif No (Real_Range_Specification (Def)) then
15806                Error_Msg_Uint_1 := Max_Digs_Val;
15807                Error_Msg_N ("types with more than ^ digits need range spec "
15808                  & "(RM 3.5.7(6))", Digs);
15809             end if;
15810          end;
15811       end if;
15812
15813       --  Find a suitable type to derive from or complain and use a substitute
15814
15815       Base_Typ := Find_Base_Type;
15816
15817       --  If there are bounds given in the declaration use them as the bounds
15818       --  of the type, otherwise use the bounds of the predefined base type
15819       --  that was chosen based on the Digits value.
15820
15821       if Present (Real_Range_Specification (Def)) then
15822          Set_Scalar_Range (T, Real_Range_Specification (Def));
15823          Set_Is_Constrained (T);
15824
15825          --  The bounds of this range must be converted to machine numbers
15826          --  in accordance with RM 4.9(38).
15827
15828          Bound := Type_Low_Bound (T);
15829
15830          if Nkind (Bound) = N_Real_Literal then
15831             Set_Realval
15832               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
15833             Set_Is_Machine_Number (Bound);
15834          end if;
15835
15836          Bound := Type_High_Bound (T);
15837
15838          if Nkind (Bound) = N_Real_Literal then
15839             Set_Realval
15840               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
15841             Set_Is_Machine_Number (Bound);
15842          end if;
15843
15844       else
15845          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
15846       end if;
15847
15848       --  Complete definition of implicit base and declared first subtype
15849
15850       Set_Etype          (Implicit_Base, Base_Typ);
15851
15852       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
15853       Set_Size_Info      (Implicit_Base,                (Base_Typ));
15854       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
15855       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
15856       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
15857       Set_Float_Rep      (Implicit_Base, Float_Rep      (Base_Typ));
15858
15859       Set_Ekind          (T, E_Floating_Point_Subtype);
15860       Set_Etype          (T, Implicit_Base);
15861
15862       Set_Size_Info      (T,                (Implicit_Base));
15863       Set_RM_Size        (T, RM_Size        (Implicit_Base));
15864       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
15865       Set_Digits_Value   (T, Digs_Val);
15866    end Floating_Point_Type_Declaration;
15867
15868    ----------------------------
15869    -- Get_Discriminant_Value --
15870    ----------------------------
15871
15872    --  This is the situation:
15873
15874    --  There is a non-derived type
15875
15876    --       type T0 (Dx, Dy, Dz...)
15877
15878    --  There are zero or more levels of derivation, with each derivation
15879    --  either purely inheriting the discriminants, or defining its own.
15880
15881    --       type Ti      is new Ti-1
15882    --  or
15883    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
15884    --  or
15885    --       subtype Ti is ...
15886
15887    --  The subtype issue is avoided by the use of Original_Record_Component,
15888    --  and the fact that derived subtypes also derive the constraints.
15889
15890    --  This chain leads back from
15891
15892    --       Typ_For_Constraint
15893
15894    --  Typ_For_Constraint has discriminants, and the value for each
15895    --  discriminant is given by its corresponding Elmt of Constraints.
15896
15897    --  Discriminant is some discriminant in this hierarchy
15898
15899    --  We need to return its value
15900
15901    --  We do this by recursively searching each level, and looking for
15902    --  Discriminant. Once we get to the bottom, we start backing up
15903    --  returning the value for it which may in turn be a discriminant
15904    --  further up, so on the backup we continue the substitution.
15905
15906    function Get_Discriminant_Value
15907      (Discriminant       : Entity_Id;
15908       Typ_For_Constraint : Entity_Id;
15909       Constraint         : Elist_Id) return Node_Id
15910    is
15911       function Root_Corresponding_Discriminant
15912         (Discr : Entity_Id) return Entity_Id;
15913       --  Given a discriminant, traverse the chain of inherited discriminants
15914       --  and return the topmost discriminant.
15915
15916       function Search_Derivation_Levels
15917         (Ti                    : Entity_Id;
15918          Discrim_Values        : Elist_Id;
15919          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
15920       --  This is the routine that performs the recursive search of levels
15921       --  as described above.
15922
15923       -------------------------------------
15924       -- Root_Corresponding_Discriminant --
15925       -------------------------------------
15926
15927       function Root_Corresponding_Discriminant
15928         (Discr : Entity_Id) return Entity_Id
15929       is
15930          D : Entity_Id;
15931
15932       begin
15933          D := Discr;
15934          while Present (Corresponding_Discriminant (D)) loop
15935             D := Corresponding_Discriminant (D);
15936          end loop;
15937
15938          return D;
15939       end Root_Corresponding_Discriminant;
15940
15941       ------------------------------
15942       -- Search_Derivation_Levels --
15943       ------------------------------
15944
15945       function Search_Derivation_Levels
15946         (Ti                    : Entity_Id;
15947          Discrim_Values        : Elist_Id;
15948          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
15949       is
15950          Assoc          : Elmt_Id;
15951          Disc           : Entity_Id;
15952          Result         : Node_Or_Entity_Id;
15953          Result_Entity  : Node_Id;
15954
15955       begin
15956          --  If inappropriate type, return Error, this happens only in
15957          --  cascaded error situations, and we want to avoid a blow up.
15958
15959          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
15960             return Error;
15961          end if;
15962
15963          --  Look deeper if possible. Use Stored_Constraints only for
15964          --  untagged types. For tagged types use the given constraint.
15965          --  This asymmetry needs explanation???
15966
15967          if not Stored_Discrim_Values
15968            and then Present (Stored_Constraint (Ti))
15969            and then not Is_Tagged_Type (Ti)
15970          then
15971             Result :=
15972               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
15973          else
15974             declare
15975                Td : constant Entity_Id := Etype (Ti);
15976
15977             begin
15978                if Td = Ti then
15979                   Result := Discriminant;
15980
15981                else
15982                   if Present (Stored_Constraint (Ti)) then
15983                      Result :=
15984                         Search_Derivation_Levels
15985                           (Td, Stored_Constraint (Ti), True);
15986                   else
15987                      Result :=
15988                         Search_Derivation_Levels
15989                           (Td, Discrim_Values, Stored_Discrim_Values);
15990                   end if;
15991                end if;
15992             end;
15993          end if;
15994
15995          --  Extra underlying places to search, if not found above. For
15996          --  concurrent types, the relevant discriminant appears in the
15997          --  corresponding record. For a type derived from a private type
15998          --  without discriminant, the full view inherits the discriminants
15999          --  of the full view of the parent.
16000
16001          if Result = Discriminant then
16002             if Is_Concurrent_Type (Ti)
16003               and then Present (Corresponding_Record_Type (Ti))
16004             then
16005                Result :=
16006                  Search_Derivation_Levels (
16007                    Corresponding_Record_Type (Ti),
16008                    Discrim_Values,
16009                    Stored_Discrim_Values);
16010
16011             elsif Is_Private_Type (Ti)
16012               and then not Has_Discriminants (Ti)
16013               and then Present (Full_View (Ti))
16014               and then Etype (Full_View (Ti)) /= Ti
16015             then
16016                Result :=
16017                  Search_Derivation_Levels (
16018                    Full_View (Ti),
16019                    Discrim_Values,
16020                    Stored_Discrim_Values);
16021             end if;
16022          end if;
16023
16024          --  If Result is not a (reference to a) discriminant, return it,
16025          --  otherwise set Result_Entity to the discriminant.
16026
16027          if Nkind (Result) = N_Defining_Identifier then
16028             pragma Assert (Result = Discriminant);
16029             Result_Entity := Result;
16030
16031          else
16032             if not Denotes_Discriminant (Result) then
16033                return Result;
16034             end if;
16035
16036             Result_Entity := Entity (Result);
16037          end if;
16038
16039          --  See if this level of derivation actually has discriminants
16040          --  because tagged derivations can add them, hence the lower
16041          --  levels need not have any.
16042
16043          if not Has_Discriminants (Ti) then
16044             return Result;
16045          end if;
16046
16047          --  Scan Ti's discriminants for Result_Entity,
16048          --  and return its corresponding value, if any.
16049
16050          Result_Entity := Original_Record_Component (Result_Entity);
16051
16052          Assoc := First_Elmt (Discrim_Values);
16053
16054          if Stored_Discrim_Values then
16055             Disc := First_Stored_Discriminant (Ti);
16056          else
16057             Disc := First_Discriminant (Ti);
16058          end if;
16059
16060          while Present (Disc) loop
16061             pragma Assert (Present (Assoc));
16062
16063             if Original_Record_Component (Disc) = Result_Entity then
16064                return Node (Assoc);
16065             end if;
16066
16067             Next_Elmt (Assoc);
16068
16069             if Stored_Discrim_Values then
16070                Next_Stored_Discriminant (Disc);
16071             else
16072                Next_Discriminant (Disc);
16073             end if;
16074          end loop;
16075
16076          --  Could not find it
16077          --
16078          return Result;
16079       end Search_Derivation_Levels;
16080
16081       --  Local Variables
16082
16083       Result : Node_Or_Entity_Id;
16084
16085    --  Start of processing for Get_Discriminant_Value
16086
16087    begin
16088       --  ??? This routine is a gigantic mess and will be deleted. For the
16089       --  time being just test for the trivial case before calling recurse.
16090
16091       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
16092          declare
16093             D : Entity_Id;
16094             E : Elmt_Id;
16095
16096          begin
16097             D := First_Discriminant (Typ_For_Constraint);
16098             E := First_Elmt (Constraint);
16099             while Present (D) loop
16100                if Chars (D) = Chars (Discriminant) then
16101                   return Node (E);
16102                end if;
16103
16104                Next_Discriminant (D);
16105                Next_Elmt (E);
16106             end loop;
16107          end;
16108       end if;
16109
16110       Result := Search_Derivation_Levels
16111         (Typ_For_Constraint, Constraint, False);
16112
16113       --  ??? hack to disappear when this routine is gone
16114
16115       if Nkind (Result) = N_Defining_Identifier then
16116          declare
16117             D : Entity_Id;
16118             E : Elmt_Id;
16119
16120          begin
16121             D := First_Discriminant (Typ_For_Constraint);
16122             E := First_Elmt (Constraint);
16123             while Present (D) loop
16124                if Root_Corresponding_Discriminant (D) = Discriminant then
16125                   return Node (E);
16126                end if;
16127
16128                Next_Discriminant (D);
16129                Next_Elmt (E);
16130             end loop;
16131          end;
16132       end if;
16133
16134       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
16135       return Result;
16136    end Get_Discriminant_Value;
16137
16138    --------------------------
16139    -- Has_Range_Constraint --
16140    --------------------------
16141
16142    function Has_Range_Constraint (N : Node_Id) return Boolean is
16143       C : constant Node_Id := Constraint (N);
16144
16145    begin
16146       if Nkind (C) = N_Range_Constraint then
16147          return True;
16148
16149       elsif Nkind (C) = N_Digits_Constraint then
16150          return
16151             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
16152               or else
16153             Present (Range_Constraint (C));
16154
16155       elsif Nkind (C) = N_Delta_Constraint then
16156          return Present (Range_Constraint (C));
16157
16158       else
16159          return False;
16160       end if;
16161    end Has_Range_Constraint;
16162
16163    ------------------------
16164    -- Inherit_Components --
16165    ------------------------
16166
16167    function Inherit_Components
16168      (N             : Node_Id;
16169       Parent_Base   : Entity_Id;
16170       Derived_Base  : Entity_Id;
16171       Is_Tagged     : Boolean;
16172       Inherit_Discr : Boolean;
16173       Discs         : Elist_Id) return Elist_Id
16174    is
16175       Assoc_List : constant Elist_Id := New_Elmt_List;
16176
16177       procedure Inherit_Component
16178         (Old_C          : Entity_Id;
16179          Plain_Discrim  : Boolean := False;
16180          Stored_Discrim : Boolean := False);
16181       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
16182       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
16183       --  True, Old_C is a stored discriminant. If they are both false then
16184       --  Old_C is a regular component.
16185
16186       -----------------------
16187       -- Inherit_Component --
16188       -----------------------
16189
16190       procedure Inherit_Component
16191         (Old_C          : Entity_Id;
16192          Plain_Discrim  : Boolean := False;
16193          Stored_Discrim : Boolean := False)
16194       is
16195          procedure Set_Anonymous_Type (Id : Entity_Id);
16196          --  Id denotes the entity of an access discriminant or anonymous
16197          --  access component. Set the type of Id to either the same type of
16198          --  Old_C or create a new one depending on whether the parent and
16199          --  the child types are in the same scope.
16200
16201          ------------------------
16202          -- Set_Anonymous_Type --
16203          ------------------------
16204
16205          procedure Set_Anonymous_Type (Id : Entity_Id) is
16206             Old_Typ : constant Entity_Id := Etype (Old_C);
16207
16208          begin
16209             if Scope (Parent_Base) = Scope (Derived_Base) then
16210                Set_Etype (Id, Old_Typ);
16211
16212             --  The parent and the derived type are in two different scopes.
16213             --  Reuse the type of the original discriminant / component by
16214             --  copying it in order to preserve all attributes.
16215
16216             else
16217                declare
16218                   Typ : constant Entity_Id := New_Copy (Old_Typ);
16219
16220                begin
16221                   Set_Etype (Id, Typ);
16222
16223                   --  Since we do not generate component declarations for
16224                   --  inherited components, associate the itype with the
16225                   --  derived type.
16226
16227                   Set_Associated_Node_For_Itype (Typ, Parent (Derived_Base));
16228                   Set_Scope                     (Typ, Derived_Base);
16229                end;
16230             end if;
16231          end Set_Anonymous_Type;
16232
16233          --  Local variables and constants
16234
16235          New_C : constant Entity_Id := New_Copy (Old_C);
16236
16237          Corr_Discrim : Entity_Id;
16238          Discrim      : Entity_Id;
16239
16240       --  Start of processing for Inherit_Component
16241
16242       begin
16243          pragma Assert (not Is_Tagged or else not Stored_Discrim);
16244
16245          Set_Parent (New_C, Parent (Old_C));
16246
16247          --  Regular discriminants and components must be inserted in the scope
16248          --  of the Derived_Base. Do it here.
16249
16250          if not Stored_Discrim then
16251             Enter_Name (New_C);
16252          end if;
16253
16254          --  For tagged types the Original_Record_Component must point to
16255          --  whatever this field was pointing to in the parent type. This has
16256          --  already been achieved by the call to New_Copy above.
16257
16258          if not Is_Tagged then
16259             Set_Original_Record_Component (New_C, New_C);
16260          end if;
16261
16262          --  Set the proper type of an access discriminant
16263
16264          if Ekind (New_C) = E_Discriminant
16265            and then Ekind (Etype (New_C)) = E_Anonymous_Access_Type
16266          then
16267             Set_Anonymous_Type (New_C);
16268          end if;
16269
16270          --  If we have inherited a component then see if its Etype contains
16271          --  references to Parent_Base discriminants. In this case, replace
16272          --  these references with the constraints given in Discs. We do not
16273          --  do this for the partial view of private types because this is
16274          --  not needed (only the components of the full view will be used
16275          --  for code generation) and cause problem. We also avoid this
16276          --  transformation in some error situations.
16277
16278          if Ekind (New_C) = E_Component then
16279
16280             --  Set the proper type of an anonymous access component
16281
16282             if Ekind (Etype (New_C)) = E_Anonymous_Access_Type then
16283                Set_Anonymous_Type (New_C);
16284
16285             elsif (Is_Private_Type (Derived_Base)
16286                     and then not Is_Generic_Type (Derived_Base))
16287               or else (Is_Empty_Elmt_List (Discs)
16288                          and then not Expander_Active)
16289             then
16290                Set_Etype (New_C, Etype (Old_C));
16291
16292             else
16293                --  The current component introduces a circularity of the
16294                --  following kind:
16295
16296                --     limited with Pack_2;
16297                --     package Pack_1 is
16298                --        type T_1 is tagged record
16299                --           Comp : access Pack_2.T_2;
16300                --           ...
16301                --        end record;
16302                --     end Pack_1;
16303
16304                --     with Pack_1;
16305                --     package Pack_2 is
16306                --        type T_2 is new Pack_1.T_1 with ...;
16307                --     end Pack_2;
16308
16309                Set_Etype
16310                  (New_C,
16311                   Constrain_Component_Type
16312                     (Old_C, Derived_Base, N, Parent_Base, Discs));
16313             end if;
16314          end if;
16315
16316          --  In derived tagged types it is illegal to reference a non
16317          --  discriminant component in the parent type. To catch this, mark
16318          --  these components with an Ekind of E_Void. This will be reset in
16319          --  Record_Type_Definition after processing the record extension of
16320          --  the derived type.
16321
16322          --  If the declaration is a private extension, there is no further
16323          --  record extension to process, and the components retain their
16324          --  current kind, because they are visible at this point.
16325
16326          if Is_Tagged and then Ekind (New_C) = E_Component
16327            and then Nkind (N) /= N_Private_Extension_Declaration
16328          then
16329             Set_Ekind (New_C, E_Void);
16330          end if;
16331
16332          if Plain_Discrim then
16333             Set_Corresponding_Discriminant (New_C, Old_C);
16334             Build_Discriminal (New_C);
16335
16336          --  If we are explicitly inheriting a stored discriminant it will be
16337          --  completely hidden.
16338
16339          elsif Stored_Discrim then
16340             Set_Corresponding_Discriminant (New_C, Empty);
16341             Set_Discriminal (New_C, Empty);
16342             Set_Is_Completely_Hidden (New_C);
16343
16344             --  Set the Original_Record_Component of each discriminant in the
16345             --  derived base to point to the corresponding stored that we just
16346             --  created.
16347
16348             Discrim := First_Discriminant (Derived_Base);
16349             while Present (Discrim) loop
16350                Corr_Discrim := Corresponding_Discriminant (Discrim);
16351
16352                --  Corr_Discrim could be missing in an error situation
16353
16354                if Present (Corr_Discrim)
16355                  and then Original_Record_Component (Corr_Discrim) = Old_C
16356                then
16357                   Set_Original_Record_Component (Discrim, New_C);
16358                end if;
16359
16360                Next_Discriminant (Discrim);
16361             end loop;
16362
16363             Append_Entity (New_C, Derived_Base);
16364          end if;
16365
16366          if not Is_Tagged then
16367             Append_Elmt (Old_C, Assoc_List);
16368             Append_Elmt (New_C, Assoc_List);
16369          end if;
16370       end Inherit_Component;
16371
16372       --  Variables local to Inherit_Component
16373
16374       Loc : constant Source_Ptr := Sloc (N);
16375
16376       Parent_Discrim : Entity_Id;
16377       Stored_Discrim : Entity_Id;
16378       D              : Entity_Id;
16379       Component      : Entity_Id;
16380
16381    --  Start of processing for Inherit_Components
16382
16383    begin
16384       if not Is_Tagged then
16385          Append_Elmt (Parent_Base,  Assoc_List);
16386          Append_Elmt (Derived_Base, Assoc_List);
16387       end if;
16388
16389       --  Inherit parent discriminants if needed
16390
16391       if Inherit_Discr then
16392          Parent_Discrim := First_Discriminant (Parent_Base);
16393          while Present (Parent_Discrim) loop
16394             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
16395             Next_Discriminant (Parent_Discrim);
16396          end loop;
16397       end if;
16398
16399       --  Create explicit stored discrims for untagged types when necessary
16400
16401       if not Has_Unknown_Discriminants (Derived_Base)
16402         and then Has_Discriminants (Parent_Base)
16403         and then not Is_Tagged
16404         and then
16405           (not Inherit_Discr
16406              or else First_Discriminant (Parent_Base) /=
16407                      First_Stored_Discriminant (Parent_Base))
16408       then
16409          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
16410          while Present (Stored_Discrim) loop
16411             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
16412             Next_Stored_Discriminant (Stored_Discrim);
16413          end loop;
16414       end if;
16415
16416       --  See if we can apply the second transformation for derived types, as
16417       --  explained in point 6. in the comments above Build_Derived_Record_Type
16418       --  This is achieved by appending Derived_Base discriminants into Discs,
16419       --  which has the side effect of returning a non empty Discs list to the
16420       --  caller of Inherit_Components, which is what we want. This must be
16421       --  done for private derived types if there are explicit stored
16422       --  discriminants, to ensure that we can retrieve the values of the
16423       --  constraints provided in the ancestors.
16424
16425       if Inherit_Discr
16426         and then Is_Empty_Elmt_List (Discs)
16427         and then Present (First_Discriminant (Derived_Base))
16428         and then
16429           (not Is_Private_Type (Derived_Base)
16430              or else Is_Completely_Hidden
16431                (First_Stored_Discriminant (Derived_Base))
16432              or else Is_Generic_Type (Derived_Base))
16433       then
16434          D := First_Discriminant (Derived_Base);
16435          while Present (D) loop
16436             Append_Elmt (New_Reference_To (D, Loc), Discs);
16437             Next_Discriminant (D);
16438          end loop;
16439       end if;
16440
16441       --  Finally, inherit non-discriminant components unless they are not
16442       --  visible because defined or inherited from the full view of the
16443       --  parent. Don't inherit the _parent field of the parent type.
16444
16445       Component := First_Entity (Parent_Base);
16446       while Present (Component) loop
16447
16448          --  Ada 2005 (AI-251): Do not inherit components associated with
16449          --  secondary tags of the parent.
16450
16451          if Ekind (Component) = E_Component
16452            and then Present (Related_Type (Component))
16453          then
16454             null;
16455
16456          elsif Ekind (Component) /= E_Component
16457            or else Chars (Component) = Name_uParent
16458          then
16459             null;
16460
16461          --  If the derived type is within the parent type's declarative
16462          --  region, then the components can still be inherited even though
16463          --  they aren't visible at this point. This can occur for cases
16464          --  such as within public child units where the components must
16465          --  become visible upon entering the child unit's private part.
16466
16467          elsif not Is_Visible_Component (Component)
16468            and then not In_Open_Scopes (Scope (Parent_Base))
16469          then
16470             null;
16471
16472          elsif Ekind_In (Derived_Base, E_Private_Type,
16473                                        E_Limited_Private_Type)
16474          then
16475             null;
16476
16477          else
16478             Inherit_Component (Component);
16479          end if;
16480
16481          Next_Entity (Component);
16482       end loop;
16483
16484       --  For tagged derived types, inherited discriminants cannot be used in
16485       --  component declarations of the record extension part. To achieve this
16486       --  we mark the inherited discriminants as not visible.
16487
16488       if Is_Tagged and then Inherit_Discr then
16489          D := First_Discriminant (Derived_Base);
16490          while Present (D) loop
16491             Set_Is_Immediately_Visible (D, False);
16492             Next_Discriminant (D);
16493          end loop;
16494       end if;
16495
16496       return Assoc_List;
16497    end Inherit_Components;
16498
16499    -----------------------
16500    -- Is_Null_Extension --
16501    -----------------------
16502
16503    function Is_Null_Extension (T : Entity_Id) return Boolean is
16504       Type_Decl : constant Node_Id := Parent (Base_Type (T));
16505       Comp_List : Node_Id;
16506       Comp      : Node_Id;
16507
16508    begin
16509       if Nkind (Type_Decl) /= N_Full_Type_Declaration
16510         or else not Is_Tagged_Type (T)
16511         or else Nkind (Type_Definition (Type_Decl)) /=
16512                                               N_Derived_Type_Definition
16513         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
16514       then
16515          return False;
16516       end if;
16517
16518       Comp_List :=
16519         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
16520
16521       if Present (Discriminant_Specifications (Type_Decl)) then
16522          return False;
16523
16524       elsif Present (Comp_List)
16525         and then Is_Non_Empty_List (Component_Items (Comp_List))
16526       then
16527          Comp := First (Component_Items (Comp_List));
16528
16529          --  Only user-defined components are relevant. The component list
16530          --  may also contain a parent component and internal components
16531          --  corresponding to secondary tags, but these do not determine
16532          --  whether this is a null extension.
16533
16534          while Present (Comp) loop
16535             if Comes_From_Source (Comp) then
16536                return False;
16537             end if;
16538
16539             Next (Comp);
16540          end loop;
16541
16542          return True;
16543       else
16544          return True;
16545       end if;
16546    end Is_Null_Extension;
16547
16548    ------------------------------
16549    -- Is_Valid_Constraint_Kind --
16550    ------------------------------
16551
16552    function Is_Valid_Constraint_Kind
16553      (T_Kind          : Type_Kind;
16554       Constraint_Kind : Node_Kind) return Boolean
16555    is
16556    begin
16557       case T_Kind is
16558          when Enumeration_Kind |
16559               Integer_Kind =>
16560             return Constraint_Kind = N_Range_Constraint;
16561
16562          when Decimal_Fixed_Point_Kind =>
16563             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
16564                                               N_Range_Constraint);
16565
16566          when Ordinary_Fixed_Point_Kind =>
16567             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
16568                                               N_Range_Constraint);
16569
16570          when Float_Kind =>
16571             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
16572                                               N_Range_Constraint);
16573
16574          when Access_Kind       |
16575               Array_Kind        |
16576               E_Record_Type     |
16577               E_Record_Subtype  |
16578               Class_Wide_Kind   |
16579               E_Incomplete_Type |
16580               Private_Kind      |
16581               Concurrent_Kind  =>
16582             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
16583
16584          when others =>
16585             return True; -- Error will be detected later
16586       end case;
16587    end Is_Valid_Constraint_Kind;
16588
16589    --------------------------
16590    -- Is_Visible_Component --
16591    --------------------------
16592
16593    function Is_Visible_Component
16594      (C : Entity_Id;
16595       N : Node_Id := Empty) return Boolean
16596    is
16597       Original_Comp  : Entity_Id := Empty;
16598       Original_Scope : Entity_Id;
16599       Type_Scope     : Entity_Id;
16600
16601       function Is_Local_Type (Typ : Entity_Id) return Boolean;
16602       --  Check whether parent type of inherited component is declared locally,
16603       --  possibly within a nested package or instance. The current scope is
16604       --  the derived record itself.
16605
16606       -------------------
16607       -- Is_Local_Type --
16608       -------------------
16609
16610       function Is_Local_Type (Typ : Entity_Id) return Boolean is
16611          Scop : Entity_Id;
16612
16613       begin
16614          Scop := Scope (Typ);
16615          while Present (Scop)
16616            and then Scop /= Standard_Standard
16617          loop
16618             if Scop = Scope (Current_Scope) then
16619                return True;
16620             end if;
16621
16622             Scop := Scope (Scop);
16623          end loop;
16624
16625          return False;
16626       end Is_Local_Type;
16627
16628    --  Start of processing for Is_Visible_Component
16629
16630    begin
16631       if Ekind_In (C, E_Component, E_Discriminant) then
16632          Original_Comp := Original_Record_Component (C);
16633       end if;
16634
16635       if No (Original_Comp) then
16636
16637          --  Premature usage, or previous error
16638
16639          return False;
16640
16641       else
16642          Original_Scope := Scope (Original_Comp);
16643          Type_Scope     := Scope (Base_Type (Scope (C)));
16644       end if;
16645
16646       --  For an untagged type derived from a private type, the only visible
16647       --  components are new discriminants. In an instance all components are
16648       --  visible (see Analyze_Selected_Component).
16649
16650       if not Is_Tagged_Type (Original_Scope) then
16651          return not Has_Private_Ancestor (Original_Scope)
16652            or else In_Open_Scopes (Scope (Original_Scope))
16653            or else In_Instance
16654            or else (Ekind (Original_Comp) = E_Discriminant
16655                      and then Original_Scope = Type_Scope);
16656
16657       --  If it is _Parent or _Tag, there is no visibility issue
16658
16659       elsif not Comes_From_Source (Original_Comp) then
16660          return True;
16661
16662       --  Discriminants are visible unless the (private) type has unknown
16663       --  discriminants. If the discriminant reference is inserted for a
16664       --  discriminant check on a full view it is also visible.
16665
16666       elsif Ekind (Original_Comp) = E_Discriminant
16667         and then
16668           (not Has_Unknown_Discriminants (Original_Scope)
16669             or else (Present (N)
16670                       and then Nkind (N) = N_Selected_Component
16671                       and then Nkind (Prefix (N)) = N_Type_Conversion
16672                       and then not Comes_From_Source (Prefix (N))))
16673       then
16674          return True;
16675
16676       --  In the body of an instantiation, no need to check for the visibility
16677       --  of a component.
16678
16679       elsif In_Instance_Body then
16680          return True;
16681
16682       --  If the component has been declared in an ancestor which is currently
16683       --  a private type, then it is not visible. The same applies if the
16684       --  component's containing type is not in an open scope and the original
16685       --  component's enclosing type is a visible full view of a private type
16686       --  (which can occur in cases where an attempt is being made to reference
16687       --  a component in a sibling package that is inherited from a visible
16688       --  component of a type in an ancestor package; the component in the
16689       --  sibling package should not be visible even though the component it
16690       --  inherited from is visible). This does not apply however in the case
16691       --  where the scope of the type is a private child unit, or when the
16692       --  parent comes from a local package in which the ancestor is currently
16693       --  visible. The latter suppression of visibility is needed for cases
16694       --  that are tested in B730006.
16695
16696       elsif Is_Private_Type (Original_Scope)
16697         or else
16698           (not Is_Private_Descendant (Type_Scope)
16699             and then not In_Open_Scopes (Type_Scope)
16700             and then Has_Private_Declaration (Original_Scope))
16701       then
16702          --  If the type derives from an entity in a formal package, there
16703          --  are no additional visible components.
16704
16705          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
16706             N_Formal_Package_Declaration
16707          then
16708             return False;
16709
16710          --  if we are not in the private part of the current package, there
16711          --  are no additional visible components.
16712
16713          elsif Ekind (Scope (Current_Scope)) = E_Package
16714            and then not In_Private_Part (Scope (Current_Scope))
16715          then
16716             return False;
16717          else
16718             return
16719               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
16720                 and then In_Open_Scopes (Scope (Original_Scope))
16721                 and then Is_Local_Type (Type_Scope);
16722          end if;
16723
16724       --  There is another weird way in which a component may be invisible when
16725       --  the private and the full view are not derived from the same ancestor.
16726       --  Here is an example :
16727
16728       --       type A1 is tagged      record F1 : integer; end record;
16729       --       type A2 is new A1 with record F2 : integer; end record;
16730       --       type T is new A1 with private;
16731       --     private
16732       --       type T is new A2 with null record;
16733
16734       --  In this case, the full view of T inherits F1 and F2 but the private
16735       --  view inherits only F1
16736
16737       else
16738          declare
16739             Ancestor : Entity_Id := Scope (C);
16740
16741          begin
16742             loop
16743                if Ancestor = Original_Scope then
16744                   return True;
16745                elsif Ancestor = Etype (Ancestor) then
16746                   return False;
16747                end if;
16748
16749                Ancestor := Etype (Ancestor);
16750             end loop;
16751          end;
16752       end if;
16753    end Is_Visible_Component;
16754
16755    --------------------------
16756    -- Make_Class_Wide_Type --
16757    --------------------------
16758
16759    procedure Make_Class_Wide_Type (T : Entity_Id) is
16760       CW_Type : Entity_Id;
16761       CW_Name : Name_Id;
16762       Next_E  : Entity_Id;
16763
16764    begin
16765       if Present (Class_Wide_Type (T)) then
16766
16767          --  The class-wide type is a partially decorated entity created for a
16768          --  unanalyzed tagged type referenced through a limited with clause.
16769          --  When the tagged type is analyzed, its class-wide type needs to be
16770          --  redecorated. Note that we reuse the entity created by Decorate_
16771          --  Tagged_Type in order to preserve all links.
16772
16773          if Materialize_Entity (Class_Wide_Type (T)) then
16774             CW_Type := Class_Wide_Type (T);
16775             Set_Materialize_Entity (CW_Type, False);
16776
16777          --  The class wide type can have been defined by the partial view, in
16778          --  which case everything is already done.
16779
16780          else
16781             return;
16782          end if;
16783
16784       --  Default case, we need to create a new class-wide type
16785
16786       else
16787          CW_Type :=
16788            New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
16789       end if;
16790
16791       --  Inherit root type characteristics
16792
16793       CW_Name := Chars (CW_Type);
16794       Next_E  := Next_Entity (CW_Type);
16795       Copy_Node (T, CW_Type);
16796       Set_Comes_From_Source (CW_Type, False);
16797       Set_Chars (CW_Type, CW_Name);
16798       Set_Parent (CW_Type, Parent (T));
16799       Set_Next_Entity (CW_Type, Next_E);
16800
16801       --  Ensure we have a new freeze node for the class-wide type. The partial
16802       --  view may have freeze action of its own, requiring a proper freeze
16803       --  node, and the same freeze node cannot be shared between the two
16804       --  types.
16805
16806       Set_Has_Delayed_Freeze (CW_Type);
16807       Set_Freeze_Node (CW_Type, Empty);
16808
16809       --  Customize the class-wide type: It has no prim. op., it cannot be
16810       --  abstract and its Etype points back to the specific root type.
16811
16812       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
16813       Set_Is_Tagged_Type              (CW_Type, True);
16814       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
16815       Set_Is_Abstract_Type            (CW_Type, False);
16816       Set_Is_Constrained              (CW_Type, False);
16817       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
16818
16819       if Ekind (T) = E_Class_Wide_Subtype then
16820          Set_Etype             (CW_Type, Etype (Base_Type (T)));
16821       else
16822          Set_Etype             (CW_Type, T);
16823       end if;
16824
16825       --  If this is the class_wide type of a constrained subtype, it does
16826       --  not have discriminants.
16827
16828       Set_Has_Discriminants (CW_Type,
16829         Has_Discriminants (T) and then not Is_Constrained (T));
16830
16831       Set_Has_Unknown_Discriminants (CW_Type, True);
16832       Set_Class_Wide_Type (T, CW_Type);
16833       Set_Equivalent_Type (CW_Type, Empty);
16834
16835       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
16836
16837       Set_Class_Wide_Type (CW_Type, CW_Type);
16838    end Make_Class_Wide_Type;
16839
16840    ----------------
16841    -- Make_Index --
16842    ----------------
16843
16844    procedure Make_Index
16845      (I            : Node_Id;
16846       Related_Nod  : Node_Id;
16847       Related_Id   : Entity_Id := Empty;
16848       Suffix_Index : Nat := 1;
16849       In_Iter_Schm : Boolean := False)
16850    is
16851       R      : Node_Id;
16852       T      : Entity_Id;
16853       Def_Id : Entity_Id := Empty;
16854       Found  : Boolean := False;
16855
16856    begin
16857       --  For a discrete range used in a constrained array definition and
16858       --  defined by a range, an implicit conversion to the predefined type
16859       --  INTEGER is assumed if each bound is either a numeric literal, a named
16860       --  number, or an attribute, and the type of both bounds (prior to the
16861       --  implicit conversion) is the type universal_integer. Otherwise, both
16862       --  bounds must be of the same discrete type, other than universal
16863       --  integer; this type must be determinable independently of the
16864       --  context, but using the fact that the type must be discrete and that
16865       --  both bounds must have the same type.
16866
16867       --  Character literals also have a universal type in the absence of
16868       --  of additional context,  and are resolved to Standard_Character.
16869
16870       if Nkind (I) = N_Range then
16871
16872          --  The index is given by a range constraint. The bounds are known
16873          --  to be of a consistent type.
16874
16875          if not Is_Overloaded (I) then
16876             T := Etype (I);
16877
16878             --  For universal bounds, choose the specific predefined type
16879
16880             if T = Universal_Integer then
16881                T := Standard_Integer;
16882
16883             elsif T = Any_Character then
16884                Ambiguous_Character (Low_Bound (I));
16885
16886                T := Standard_Character;
16887             end if;
16888
16889          --  The node may be overloaded because some user-defined operators
16890          --  are available, but if a universal interpretation exists it is
16891          --  also the selected one.
16892
16893          elsif Universal_Interpretation (I) = Universal_Integer then
16894             T := Standard_Integer;
16895
16896          else
16897             T := Any_Type;
16898
16899             declare
16900                Ind : Interp_Index;
16901                It  : Interp;
16902
16903             begin
16904                Get_First_Interp (I, Ind, It);
16905                while Present (It.Typ) loop
16906                   if Is_Discrete_Type (It.Typ) then
16907
16908                      if Found
16909                        and then not Covers (It.Typ, T)
16910                        and then not Covers (T, It.Typ)
16911                      then
16912                         Error_Msg_N ("ambiguous bounds in discrete range", I);
16913                         exit;
16914                      else
16915                         T := It.Typ;
16916                         Found := True;
16917                      end if;
16918                   end if;
16919
16920                   Get_Next_Interp (Ind, It);
16921                end loop;
16922
16923                if T = Any_Type then
16924                   Error_Msg_N ("discrete type required for range", I);
16925                   Set_Etype (I, Any_Type);
16926                   return;
16927
16928                elsif T = Universal_Integer then
16929                   T := Standard_Integer;
16930                end if;
16931             end;
16932          end if;
16933
16934          if not Is_Discrete_Type (T) then
16935             Error_Msg_N ("discrete type required for range", I);
16936             Set_Etype (I, Any_Type);
16937             return;
16938          end if;
16939
16940          if Nkind (Low_Bound (I)) = N_Attribute_Reference
16941            and then Attribute_Name (Low_Bound (I)) = Name_First
16942            and then Is_Entity_Name (Prefix (Low_Bound (I)))
16943            and then Is_Type (Entity (Prefix (Low_Bound (I))))
16944            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
16945          then
16946             --  The type of the index will be the type of the prefix, as long
16947             --  as the upper bound is 'Last of the same type.
16948
16949             Def_Id := Entity (Prefix (Low_Bound (I)));
16950
16951             if Nkind (High_Bound (I)) /= N_Attribute_Reference
16952               or else Attribute_Name (High_Bound (I)) /= Name_Last
16953               or else not Is_Entity_Name (Prefix (High_Bound (I)))
16954               or else Entity (Prefix (High_Bound (I))) /= Def_Id
16955             then
16956                Def_Id := Empty;
16957             end if;
16958          end if;
16959
16960          R := I;
16961          Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
16962
16963       elsif Nkind (I) = N_Subtype_Indication then
16964
16965          --  The index is given by a subtype with a range constraint
16966
16967          T :=  Base_Type (Entity (Subtype_Mark (I)));
16968
16969          if not Is_Discrete_Type (T) then
16970             Error_Msg_N ("discrete type required for range", I);
16971             Set_Etype (I, Any_Type);
16972             return;
16973          end if;
16974
16975          R := Range_Expression (Constraint (I));
16976
16977          Resolve (R, T);
16978          Process_Range_Expr_In_Decl
16979            (R, Entity (Subtype_Mark (I)), In_Iter_Schm => In_Iter_Schm);
16980
16981       elsif Nkind (I) = N_Attribute_Reference then
16982
16983          --  The parser guarantees that the attribute is a RANGE attribute
16984
16985          --  If the node denotes the range of a type mark, that is also the
16986          --  resulting type, and we do no need to create an Itype for it.
16987
16988          if Is_Entity_Name (Prefix (I))
16989            and then Comes_From_Source (I)
16990            and then Is_Type (Entity (Prefix (I)))
16991            and then Is_Discrete_Type (Entity (Prefix (I)))
16992          then
16993             Def_Id := Entity (Prefix (I));
16994          end if;
16995
16996          Analyze_And_Resolve (I);
16997          T := Etype (I);
16998          R := I;
16999
17000       --  If none of the above, must be a subtype. We convert this to a
17001       --  range attribute reference because in the case of declared first
17002       --  named subtypes, the types in the range reference can be different
17003       --  from the type of the entity. A range attribute normalizes the
17004       --  reference and obtains the correct types for the bounds.
17005
17006       --  This transformation is in the nature of an expansion, is only
17007       --  done if expansion is active. In particular, it is not done on
17008       --  formal generic types,  because we need to retain the name of the
17009       --  original index for instantiation purposes.
17010
17011       else
17012          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
17013             Error_Msg_N ("invalid subtype mark in discrete range ", I);
17014             Set_Etype (I, Any_Integer);
17015             return;
17016
17017          else
17018             --  The type mark may be that of an incomplete type. It is only
17019             --  now that we can get the full view, previous analysis does
17020             --  not look specifically for a type mark.
17021
17022             Set_Entity (I, Get_Full_View (Entity (I)));
17023             Set_Etype  (I, Entity (I));
17024             Def_Id := Entity (I);
17025
17026             if not Is_Discrete_Type (Def_Id) then
17027                Error_Msg_N ("discrete type required for index", I);
17028                Set_Etype (I, Any_Type);
17029                return;
17030             end if;
17031          end if;
17032
17033          if Expander_Active then
17034             Rewrite (I,
17035               Make_Attribute_Reference (Sloc (I),
17036                 Attribute_Name => Name_Range,
17037                 Prefix         => Relocate_Node (I)));
17038
17039             --  The original was a subtype mark that does not freeze. This
17040             --  means that the rewritten version must not freeze either.
17041
17042             Set_Must_Not_Freeze (I);
17043             Set_Must_Not_Freeze (Prefix (I));
17044             Analyze_And_Resolve (I);
17045             T := Etype (I);
17046             R := I;
17047
17048          --  If expander is inactive, type is legal, nothing else to construct
17049
17050          else
17051             return;
17052          end if;
17053       end if;
17054
17055       if not Is_Discrete_Type (T) then
17056          Error_Msg_N ("discrete type required for range", I);
17057          Set_Etype (I, Any_Type);
17058          return;
17059
17060       elsif T = Any_Type then
17061          Set_Etype (I, Any_Type);
17062          return;
17063       end if;
17064
17065       --  We will now create the appropriate Itype to describe the range, but
17066       --  first a check. If we originally had a subtype, then we just label
17067       --  the range with this subtype. Not only is there no need to construct
17068       --  a new subtype, but it is wrong to do so for two reasons:
17069
17070       --    1. A legality concern, if we have a subtype, it must not freeze,
17071       --       and the Itype would cause freezing incorrectly
17072
17073       --    2. An efficiency concern, if we created an Itype, it would not be
17074       --       recognized as the same type for the purposes of eliminating
17075       --       checks in some circumstances.
17076
17077       --  We signal this case by setting the subtype entity in Def_Id
17078
17079       if No (Def_Id) then
17080          Def_Id :=
17081            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
17082          Set_Etype (Def_Id, Base_Type (T));
17083
17084          if Is_Signed_Integer_Type (T) then
17085             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
17086
17087          elsif Is_Modular_Integer_Type (T) then
17088             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
17089
17090          else
17091             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
17092             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
17093             Set_First_Literal     (Def_Id, First_Literal (T));
17094          end if;
17095
17096          Set_Size_Info      (Def_Id,                  (T));
17097          Set_RM_Size        (Def_Id, RM_Size          (T));
17098          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
17099
17100          Set_Scalar_Range   (Def_Id, R);
17101          Conditional_Delay  (Def_Id, T);
17102
17103          --  In the subtype indication case, if the immediate parent of the
17104          --  new subtype is non-static, then the subtype we create is non-
17105          --  static, even if its bounds are static.
17106
17107          if Nkind (I) = N_Subtype_Indication
17108            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
17109          then
17110             Set_Is_Non_Static_Subtype (Def_Id);
17111          end if;
17112       end if;
17113
17114       --  Final step is to label the index with this constructed type
17115
17116       Set_Etype (I, Def_Id);
17117    end Make_Index;
17118
17119    ------------------------------
17120    -- Modular_Type_Declaration --
17121    ------------------------------
17122
17123    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
17124       Mod_Expr : constant Node_Id := Expression (Def);
17125       M_Val    : Uint;
17126
17127       procedure Set_Modular_Size (Bits : Int);
17128       --  Sets RM_Size to Bits, and Esize to normal word size above this
17129
17130       ----------------------
17131       -- Set_Modular_Size --
17132       ----------------------
17133
17134       procedure Set_Modular_Size (Bits : Int) is
17135       begin
17136          Set_RM_Size (T, UI_From_Int (Bits));
17137
17138          if Bits <= 8 then
17139             Init_Esize (T, 8);
17140
17141          elsif Bits <= 16 then
17142             Init_Esize (T, 16);
17143
17144          elsif Bits <= 32 then
17145             Init_Esize (T, 32);
17146
17147          else
17148             Init_Esize (T, System_Max_Binary_Modulus_Power);
17149          end if;
17150
17151          if not Non_Binary_Modulus (T)
17152            and then Esize (T) = RM_Size (T)
17153          then
17154             Set_Is_Known_Valid (T);
17155          end if;
17156       end Set_Modular_Size;
17157
17158    --  Start of processing for Modular_Type_Declaration
17159
17160    begin
17161       --  If the mod expression is (exactly) 2 * literal, where literal is
17162       --  64 or less,then almost certainly the * was meant to be **. Warn!
17163
17164       if Warn_On_Suspicious_Modulus_Value
17165         and then Nkind (Mod_Expr) = N_Op_Multiply
17166         and then Nkind (Left_Opnd (Mod_Expr)) = N_Integer_Literal
17167         and then Intval (Left_Opnd (Mod_Expr)) = Uint_2
17168         and then Nkind (Right_Opnd (Mod_Expr)) = N_Integer_Literal
17169         and then Intval (Right_Opnd (Mod_Expr)) <= Uint_64
17170       then
17171          Error_Msg_N
17172            ("suspicious MOD value, was '*'* intended'??M?", Mod_Expr);
17173       end if;
17174
17175       --  Proceed with analysis of mod expression
17176
17177       Analyze_And_Resolve (Mod_Expr, Any_Integer);
17178       Set_Etype (T, T);
17179       Set_Ekind (T, E_Modular_Integer_Type);
17180       Init_Alignment (T);
17181       Set_Is_Constrained (T);
17182
17183       if not Is_OK_Static_Expression (Mod_Expr) then
17184          Flag_Non_Static_Expr
17185            ("non-static expression used for modular type bound!", Mod_Expr);
17186          M_Val := 2 ** System_Max_Binary_Modulus_Power;
17187       else
17188          M_Val := Expr_Value (Mod_Expr);
17189       end if;
17190
17191       if M_Val < 1 then
17192          Error_Msg_N ("modulus value must be positive", Mod_Expr);
17193          M_Val := 2 ** System_Max_Binary_Modulus_Power;
17194       end if;
17195
17196       Set_Modulus (T, M_Val);
17197
17198       --   Create bounds for the modular type based on the modulus given in
17199       --   the type declaration and then analyze and resolve those bounds.
17200
17201       Set_Scalar_Range (T,
17202         Make_Range (Sloc (Mod_Expr),
17203           Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
17204           High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
17205
17206       --  Properly analyze the literals for the range. We do this manually
17207       --  because we can't go calling Resolve, since we are resolving these
17208       --  bounds with the type, and this type is certainly not complete yet!
17209
17210       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
17211       Set_Etype (High_Bound (Scalar_Range (T)), T);
17212       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
17213       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
17214
17215       --  Loop through powers of two to find number of bits required
17216
17217       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
17218
17219          --  Binary case
17220
17221          if M_Val = 2 ** Bits then
17222             Set_Modular_Size (Bits);
17223             return;
17224
17225          --  Non-binary case
17226
17227          elsif M_Val < 2 ** Bits then
17228             Check_SPARK_Restriction ("modulus should be a power of 2", T);
17229             Set_Non_Binary_Modulus (T);
17230
17231             if Bits > System_Max_Nonbinary_Modulus_Power then
17232                Error_Msg_Uint_1 :=
17233                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
17234                Error_Msg_F
17235                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
17236                Set_Modular_Size (System_Max_Binary_Modulus_Power);
17237                return;
17238
17239             else
17240                --  In the non-binary case, set size as per RM 13.3(55)
17241
17242                Set_Modular_Size (Bits);
17243                return;
17244             end if;
17245          end if;
17246
17247       end loop;
17248
17249       --  If we fall through, then the size exceed System.Max_Binary_Modulus
17250       --  so we just signal an error and set the maximum size.
17251
17252       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
17253       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
17254
17255       Set_Modular_Size (System_Max_Binary_Modulus_Power);
17256       Init_Alignment (T);
17257
17258    end Modular_Type_Declaration;
17259
17260    --------------------------
17261    -- New_Concatenation_Op --
17262    --------------------------
17263
17264    procedure New_Concatenation_Op (Typ : Entity_Id) is
17265       Loc : constant Source_Ptr := Sloc (Typ);
17266       Op  : Entity_Id;
17267
17268       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
17269       --  Create abbreviated declaration for the formal of a predefined
17270       --  Operator 'Op' of type 'Typ'
17271
17272       --------------------
17273       -- Make_Op_Formal --
17274       --------------------
17275
17276       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
17277          Formal : Entity_Id;
17278       begin
17279          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
17280          Set_Etype (Formal, Typ);
17281          Set_Mechanism (Formal, Default_Mechanism);
17282          return Formal;
17283       end Make_Op_Formal;
17284
17285    --  Start of processing for New_Concatenation_Op
17286
17287    begin
17288       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
17289
17290       Set_Ekind                   (Op, E_Operator);
17291       Set_Scope                   (Op, Current_Scope);
17292       Set_Etype                   (Op, Typ);
17293       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
17294       Set_Is_Immediately_Visible  (Op);
17295       Set_Is_Intrinsic_Subprogram (Op);
17296       Set_Has_Completion          (Op);
17297       Append_Entity               (Op, Current_Scope);
17298
17299       Set_Name_Entity_Id (Name_Op_Concat, Op);
17300
17301       Append_Entity (Make_Op_Formal (Typ, Op), Op);
17302       Append_Entity (Make_Op_Formal (Typ, Op), Op);
17303    end New_Concatenation_Op;
17304
17305    -------------------------
17306    -- OK_For_Limited_Init --
17307    -------------------------
17308
17309    --  ???Check all calls of this, and compare the conditions under which it's
17310    --  called.
17311
17312    function OK_For_Limited_Init
17313      (Typ : Entity_Id;
17314       Exp : Node_Id) return Boolean
17315    is
17316    begin
17317       return Is_CPP_Constructor_Call (Exp)
17318         or else (Ada_Version >= Ada_2005
17319                   and then not Debug_Flag_Dot_L
17320                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
17321    end OK_For_Limited_Init;
17322
17323    -------------------------------
17324    -- OK_For_Limited_Init_In_05 --
17325    -------------------------------
17326
17327    function OK_For_Limited_Init_In_05
17328      (Typ : Entity_Id;
17329       Exp : Node_Id) return Boolean
17330    is
17331    begin
17332       --  An object of a limited interface type can be initialized with any
17333       --  expression of a nonlimited descendant type.
17334
17335       if Is_Class_Wide_Type (Typ)
17336         and then Is_Limited_Interface (Typ)
17337         and then not Is_Limited_Type (Etype (Exp))
17338       then
17339          return True;
17340       end if;
17341
17342       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
17343       --  case of limited aggregates (including extension aggregates), and
17344       --  function calls. The function call may have been given in prefixed
17345       --  notation, in which case the original node is an indexed component.
17346       --  If the function is parameterless, the original node was an explicit
17347       --  dereference. The function may also be parameterless, in which case
17348       --  the source node is just an identifier.
17349
17350       case Nkind (Original_Node (Exp)) is
17351          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
17352             return True;
17353
17354          when N_Identifier =>
17355             return Present (Entity (Original_Node (Exp)))
17356               and then Ekind (Entity (Original_Node (Exp))) = E_Function;
17357
17358          when N_Qualified_Expression =>
17359             return
17360               OK_For_Limited_Init_In_05
17361                 (Typ, Expression (Original_Node (Exp)));
17362
17363          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
17364          --  with a function call, the expander has rewritten the call into an
17365          --  N_Type_Conversion node to force displacement of the pointer to
17366          --  reference the component containing the secondary dispatch table.
17367          --  Otherwise a type conversion is not a legal context.
17368          --  A return statement for a build-in-place function returning a
17369          --  synchronized type also introduces an unchecked conversion.
17370
17371          when N_Type_Conversion           |
17372               N_Unchecked_Type_Conversion =>
17373             return not Comes_From_Source (Exp)
17374               and then
17375                 OK_For_Limited_Init_In_05
17376                   (Typ, Expression (Original_Node (Exp)));
17377
17378          when N_Indexed_Component     |
17379               N_Selected_Component    |
17380               N_Explicit_Dereference  =>
17381             return Nkind (Exp) = N_Function_Call;
17382
17383          --  A use of 'Input is a function call, hence allowed. Normally the
17384          --  attribute will be changed to a call, but the attribute by itself
17385          --  can occur with -gnatc.
17386
17387          when N_Attribute_Reference =>
17388             return Attribute_Name (Original_Node (Exp)) = Name_Input;
17389
17390          --  For a case expression, all dependent expressions must be legal
17391
17392          when N_Case_Expression =>
17393             declare
17394                Alt : Node_Id;
17395
17396             begin
17397                Alt := First (Alternatives (Original_Node (Exp)));
17398                while Present (Alt) loop
17399                   if not OK_For_Limited_Init_In_05 (Typ, Expression (Alt)) then
17400                      return False;
17401                   end if;
17402
17403                   Next (Alt);
17404                end loop;
17405
17406                return True;
17407             end;
17408
17409          --  For an if expression, all dependent expressions must be legal
17410
17411          when N_If_Expression =>
17412             declare
17413                Then_Expr : constant Node_Id :=
17414                              Next (First (Expressions (Original_Node (Exp))));
17415                Else_Expr : constant Node_Id := Next (Then_Expr);
17416             begin
17417                return OK_For_Limited_Init_In_05 (Typ, Then_Expr)
17418                         and then
17419                       OK_For_Limited_Init_In_05 (Typ, Else_Expr);
17420             end;
17421
17422          when others =>
17423             return False;
17424       end case;
17425    end OK_For_Limited_Init_In_05;
17426
17427    -------------------------------------------
17428    -- Ordinary_Fixed_Point_Type_Declaration --
17429    -------------------------------------------
17430
17431    procedure Ordinary_Fixed_Point_Type_Declaration
17432      (T   : Entity_Id;
17433       Def : Node_Id)
17434    is
17435       Loc           : constant Source_Ptr := Sloc (Def);
17436       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
17437       RRS           : constant Node_Id    := Real_Range_Specification (Def);
17438       Implicit_Base : Entity_Id;
17439       Delta_Val     : Ureal;
17440       Small_Val     : Ureal;
17441       Low_Val       : Ureal;
17442       High_Val      : Ureal;
17443
17444    begin
17445       Check_Restriction (No_Fixed_Point, Def);
17446
17447       --  Create implicit base type
17448
17449       Implicit_Base :=
17450         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
17451       Set_Etype (Implicit_Base, Implicit_Base);
17452
17453       --  Analyze and process delta expression
17454
17455       Analyze_And_Resolve (Delta_Expr, Any_Real);
17456
17457       Check_Delta_Expression (Delta_Expr);
17458       Delta_Val := Expr_Value_R (Delta_Expr);
17459
17460       Set_Delta_Value (Implicit_Base, Delta_Val);
17461
17462       --  Compute default small from given delta, which is the largest power
17463       --  of two that does not exceed the given delta value.
17464
17465       declare
17466          Tmp   : Ureal;
17467          Scale : Int;
17468
17469       begin
17470          Tmp := Ureal_1;
17471          Scale := 0;
17472
17473          if Delta_Val < Ureal_1 then
17474             while Delta_Val < Tmp loop
17475                Tmp := Tmp / Ureal_2;
17476                Scale := Scale + 1;
17477             end loop;
17478
17479          else
17480             loop
17481                Tmp := Tmp * Ureal_2;
17482                exit when Tmp > Delta_Val;
17483                Scale := Scale - 1;
17484             end loop;
17485          end if;
17486
17487          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
17488       end;
17489
17490       Set_Small_Value (Implicit_Base, Small_Val);
17491
17492       --  If no range was given, set a dummy range
17493
17494       if RRS <= Empty_Or_Error then
17495          Low_Val  := -Small_Val;
17496          High_Val := Small_Val;
17497
17498       --  Otherwise analyze and process given range
17499
17500       else
17501          declare
17502             Low  : constant Node_Id := Low_Bound  (RRS);
17503             High : constant Node_Id := High_Bound (RRS);
17504
17505          begin
17506             Analyze_And_Resolve (Low, Any_Real);
17507             Analyze_And_Resolve (High, Any_Real);
17508             Check_Real_Bound (Low);
17509             Check_Real_Bound (High);
17510
17511             --  Obtain and set the range
17512
17513             Low_Val  := Expr_Value_R (Low);
17514             High_Val := Expr_Value_R (High);
17515
17516             if Low_Val > High_Val then
17517                Error_Msg_NE ("??fixed point type& has null range", Def, T);
17518             end if;
17519          end;
17520       end if;
17521
17522       --  The range for both the implicit base and the declared first subtype
17523       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
17524       --  set a temporary range in place. Note that the bounds of the base
17525       --  type will be widened to be symmetrical and to fill the available
17526       --  bits when the type is frozen.
17527
17528       --  We could do this with all discrete types, and probably should, but
17529       --  we absolutely have to do it for fixed-point, since the end-points
17530       --  of the range and the size are determined by the small value, which
17531       --  could be reset before the freeze point.
17532
17533       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
17534       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
17535
17536       --  Complete definition of first subtype
17537
17538       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
17539       Set_Etype          (T, Implicit_Base);
17540       Init_Size_Align    (T);
17541       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
17542       Set_Small_Value    (T, Small_Val);
17543       Set_Delta_Value    (T, Delta_Val);
17544       Set_Is_Constrained (T);
17545
17546    end Ordinary_Fixed_Point_Type_Declaration;
17547
17548    ----------------------------------------
17549    -- Prepare_Private_Subtype_Completion --
17550    ----------------------------------------
17551
17552    procedure Prepare_Private_Subtype_Completion
17553      (Id          : Entity_Id;
17554       Related_Nod : Node_Id)
17555    is
17556       Id_B   : constant Entity_Id := Base_Type (Id);
17557       Full_B : constant Entity_Id := Full_View (Id_B);
17558       Full   : Entity_Id;
17559
17560    begin
17561       if Present (Full_B) then
17562
17563          --  The Base_Type is already completed, we can complete the subtype
17564          --  now. We have to create a new entity with the same name, Thus we
17565          --  can't use Create_Itype.
17566
17567          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
17568          Set_Is_Itype (Full);
17569          Set_Associated_Node_For_Itype (Full, Related_Nod);
17570          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
17571       end if;
17572
17573       --  The parent subtype may be private, but the base might not, in some
17574       --  nested instances. In that case, the subtype does not need to be
17575       --  exchanged. It would still be nice to make private subtypes and their
17576       --  bases consistent at all times ???
17577
17578       if Is_Private_Type (Id_B) then
17579          Append_Elmt (Id, Private_Dependents (Id_B));
17580       end if;
17581    end Prepare_Private_Subtype_Completion;
17582
17583    ---------------------------
17584    -- Process_Discriminants --
17585    ---------------------------
17586
17587    procedure Process_Discriminants
17588      (N    : Node_Id;
17589       Prev : Entity_Id := Empty)
17590    is
17591       Elist               : constant Elist_Id := New_Elmt_List;
17592       Id                  : Node_Id;
17593       Discr               : Node_Id;
17594       Discr_Number        : Uint;
17595       Discr_Type          : Entity_Id;
17596       Default_Present     : Boolean := False;
17597       Default_Not_Present : Boolean := False;
17598
17599    begin
17600       --  A composite type other than an array type can have discriminants.
17601       --  On entry, the current scope is the composite type.
17602
17603       --  The discriminants are initially entered into the scope of the type
17604       --  via Enter_Name with the default Ekind of E_Void to prevent premature
17605       --  use, as explained at the end of this procedure.
17606
17607       Discr := First (Discriminant_Specifications (N));
17608       while Present (Discr) loop
17609          Enter_Name (Defining_Identifier (Discr));
17610
17611          --  For navigation purposes we add a reference to the discriminant
17612          --  in the entity for the type. If the current declaration is a
17613          --  completion, place references on the partial view. Otherwise the
17614          --  type is the current scope.
17615
17616          if Present (Prev) then
17617
17618             --  The references go on the partial view, if present. If the
17619             --  partial view has discriminants, the references have been
17620             --  generated already.
17621
17622             if not Has_Discriminants (Prev) then
17623                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
17624             end if;
17625          else
17626             Generate_Reference
17627               (Current_Scope, Defining_Identifier (Discr), 'd');
17628          end if;
17629
17630          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
17631             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
17632
17633             --  Ada 2005 (AI-254)
17634
17635             if Present (Access_To_Subprogram_Definition
17636                          (Discriminant_Type (Discr)))
17637               and then Protected_Present (Access_To_Subprogram_Definition
17638                                            (Discriminant_Type (Discr)))
17639             then
17640                Discr_Type :=
17641                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
17642             end if;
17643
17644          else
17645             Find_Type (Discriminant_Type (Discr));
17646             Discr_Type := Etype (Discriminant_Type (Discr));
17647
17648             if Error_Posted (Discriminant_Type (Discr)) then
17649                Discr_Type := Any_Type;
17650             end if;
17651          end if;
17652
17653          if Is_Access_Type (Discr_Type) then
17654
17655             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
17656             --  record types
17657
17658             if Ada_Version < Ada_2005 then
17659                Check_Access_Discriminant_Requires_Limited
17660                  (Discr, Discriminant_Type (Discr));
17661             end if;
17662
17663             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
17664                Error_Msg_N
17665                  ("(Ada 83) access discriminant not allowed", Discr);
17666             end if;
17667
17668          elsif not Is_Discrete_Type (Discr_Type) then
17669             Error_Msg_N ("discriminants must have a discrete or access type",
17670               Discriminant_Type (Discr));
17671          end if;
17672
17673          Set_Etype (Defining_Identifier (Discr), Discr_Type);
17674
17675          --  If a discriminant specification includes the assignment compound
17676          --  delimiter followed by an expression, the expression is the default
17677          --  expression of the discriminant; the default expression must be of
17678          --  the type of the discriminant. (RM 3.7.1) Since this expression is
17679          --  a default expression, we do the special preanalysis, since this
17680          --  expression does not freeze (see "Handling of Default and Per-
17681          --  Object Expressions" in spec of package Sem).
17682
17683          if Present (Expression (Discr)) then
17684             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
17685
17686             if Nkind (N) = N_Formal_Type_Declaration then
17687                Error_Msg_N
17688                  ("discriminant defaults not allowed for formal type",
17689                   Expression (Discr));
17690
17691             --  Flag an error for a tagged type with defaulted discriminants,
17692             --  excluding limited tagged types when compiling for Ada 2012
17693             --  (see AI05-0214).
17694
17695             elsif Is_Tagged_Type (Current_Scope)
17696               and then (not Is_Limited_Type (Current_Scope)
17697                          or else Ada_Version < Ada_2012)
17698               and then Comes_From_Source (N)
17699             then
17700                --  Note: see similar test in Check_Or_Process_Discriminants, to
17701                --  handle the (illegal) case of the completion of an untagged
17702                --  view with discriminants with defaults by a tagged full view.
17703                --  We skip the check if Discr does not come from source, to
17704                --  account for the case of an untagged derived type providing
17705                --  defaults for a renamed discriminant from a private untagged
17706                --  ancestor with a tagged full view (ACATS B460006).
17707
17708                if Ada_Version >= Ada_2012 then
17709                   Error_Msg_N
17710                     ("discriminants of nonlimited tagged type cannot have"
17711                        & " defaults",
17712                      Expression (Discr));
17713                else
17714                   Error_Msg_N
17715                     ("discriminants of tagged type cannot have defaults",
17716                      Expression (Discr));
17717                end if;
17718
17719             else
17720                Default_Present := True;
17721                Append_Elmt (Expression (Discr), Elist);
17722
17723                --  Tag the defining identifiers for the discriminants with
17724                --  their corresponding default expressions from the tree.
17725
17726                Set_Discriminant_Default_Value
17727                  (Defining_Identifier (Discr), Expression (Discr));
17728             end if;
17729
17730          else
17731             Default_Not_Present := True;
17732          end if;
17733
17734          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
17735          --  Discr_Type but with the null-exclusion attribute
17736
17737          if Ada_Version >= Ada_2005 then
17738
17739             --  Ada 2005 (AI-231): Static checks
17740
17741             if Can_Never_Be_Null (Discr_Type) then
17742                Null_Exclusion_Static_Checks (Discr);
17743
17744             elsif Is_Access_Type (Discr_Type)
17745               and then Null_Exclusion_Present (Discr)
17746
17747                --  No need to check itypes because in their case this check
17748                --  was done at their point of creation
17749
17750               and then not Is_Itype (Discr_Type)
17751             then
17752                if Can_Never_Be_Null (Discr_Type) then
17753                   Error_Msg_NE
17754                     ("`NOT NULL` not allowed (& already excludes null)",
17755                      Discr,
17756                      Discr_Type);
17757                end if;
17758
17759                Set_Etype (Defining_Identifier (Discr),
17760                  Create_Null_Excluding_Itype
17761                    (T           => Discr_Type,
17762                     Related_Nod => Discr));
17763
17764             --  Check for improper null exclusion if the type is otherwise
17765             --  legal for a discriminant.
17766
17767             elsif Null_Exclusion_Present (Discr)
17768               and then Is_Discrete_Type (Discr_Type)
17769             then
17770                Error_Msg_N
17771                  ("null exclusion can only apply to an access type", Discr);
17772             end if;
17773
17774             --  Ada 2005 (AI-402): access discriminants of nonlimited types
17775             --  can't have defaults. Synchronized types, or types that are
17776             --  explicitly limited are fine, but special tests apply to derived
17777             --  types in generics: in a generic body we have to assume the
17778             --  worst, and therefore defaults are not allowed if the parent is
17779             --  a generic formal private type (see ACATS B370001).
17780
17781             if Is_Access_Type (Discr_Type) and then Default_Present then
17782                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
17783                  or else Is_Limited_Record (Current_Scope)
17784                  or else Is_Concurrent_Type (Current_Scope)
17785                  or else Is_Concurrent_Record_Type (Current_Scope)
17786                  or else Ekind (Current_Scope) = E_Limited_Private_Type
17787                then
17788                   if not Is_Derived_Type (Current_Scope)
17789                     or else not Is_Generic_Type (Etype (Current_Scope))
17790                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
17791                     or else Limited_Present
17792                               (Type_Definition (Parent (Current_Scope)))
17793                   then
17794                      null;
17795
17796                   else
17797                      Error_Msg_N ("access discriminants of nonlimited types",
17798                          Expression (Discr));
17799                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
17800                   end if;
17801
17802                elsif Present (Expression (Discr)) then
17803                   Error_Msg_N
17804                     ("(Ada 2005) access discriminants of nonlimited types",
17805                      Expression (Discr));
17806                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
17807                end if;
17808             end if;
17809          end if;
17810
17811          Next (Discr);
17812       end loop;
17813
17814       --  An element list consisting of the default expressions of the
17815       --  discriminants is constructed in the above loop and used to set
17816       --  the Discriminant_Constraint attribute for the type. If an object
17817       --  is declared of this (record or task) type without any explicit
17818       --  discriminant constraint given, this element list will form the
17819       --  actual parameters for the corresponding initialization procedure
17820       --  for the type.
17821
17822       Set_Discriminant_Constraint (Current_Scope, Elist);
17823       Set_Stored_Constraint (Current_Scope, No_Elist);
17824
17825       --  Default expressions must be provided either for all or for none
17826       --  of the discriminants of a discriminant part. (RM 3.7.1)
17827
17828       if Default_Present and then Default_Not_Present then
17829          Error_Msg_N
17830            ("incomplete specification of defaults for discriminants", N);
17831       end if;
17832
17833       --  The use of the name of a discriminant is not allowed in default
17834       --  expressions of a discriminant part if the specification of the
17835       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
17836
17837       --  To detect this, the discriminant names are entered initially with an
17838       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
17839       --  attempt to use a void entity (for example in an expression that is
17840       --  type-checked) produces the error message: premature usage. Now after
17841       --  completing the semantic analysis of the discriminant part, we can set
17842       --  the Ekind of all the discriminants appropriately.
17843
17844       Discr := First (Discriminant_Specifications (N));
17845       Discr_Number := Uint_1;
17846       while Present (Discr) loop
17847          Id := Defining_Identifier (Discr);
17848          Set_Ekind (Id, E_Discriminant);
17849          Init_Component_Location (Id);
17850          Init_Esize (Id);
17851          Set_Discriminant_Number (Id, Discr_Number);
17852
17853          --  Make sure this is always set, even in illegal programs
17854
17855          Set_Corresponding_Discriminant (Id, Empty);
17856
17857          --  Initialize the Original_Record_Component to the entity itself.
17858          --  Inherit_Components will propagate the right value to
17859          --  discriminants in derived record types.
17860
17861          Set_Original_Record_Component (Id, Id);
17862
17863          --  Create the discriminal for the discriminant
17864
17865          Build_Discriminal (Id);
17866
17867          Next (Discr);
17868          Discr_Number := Discr_Number + 1;
17869       end loop;
17870
17871       Set_Has_Discriminants (Current_Scope);
17872    end Process_Discriminants;
17873
17874    -----------------------
17875    -- Process_Full_View --
17876    -----------------------
17877
17878    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
17879       Priv_Parent : Entity_Id;
17880       Full_Parent : Entity_Id;
17881       Full_Indic  : Node_Id;
17882
17883       procedure Collect_Implemented_Interfaces
17884         (Typ    : Entity_Id;
17885          Ifaces : Elist_Id);
17886       --  Ada 2005: Gather all the interfaces that Typ directly or
17887       --  inherently implements. Duplicate entries are not added to
17888       --  the list Ifaces.
17889
17890       ------------------------------------
17891       -- Collect_Implemented_Interfaces --
17892       ------------------------------------
17893
17894       procedure Collect_Implemented_Interfaces
17895         (Typ    : Entity_Id;
17896          Ifaces : Elist_Id)
17897       is
17898          Iface      : Entity_Id;
17899          Iface_Elmt : Elmt_Id;
17900
17901       begin
17902          --  Abstract interfaces are only associated with tagged record types
17903
17904          if not Is_Tagged_Type (Typ)
17905            or else not Is_Record_Type (Typ)
17906          then
17907             return;
17908          end if;
17909
17910          --  Recursively climb to the ancestors
17911
17912          if Etype (Typ) /= Typ
17913
17914             --  Protect the frontend against wrong cyclic declarations like:
17915
17916             --     type B is new A with private;
17917             --     type C is new A with private;
17918             --  private
17919             --     type B is new C with null record;
17920             --     type C is new B with null record;
17921
17922            and then Etype (Typ) /= Priv_T
17923            and then Etype (Typ) /= Full_T
17924          then
17925             --  Keep separate the management of private type declarations
17926
17927             if Ekind (Typ) = E_Record_Type_With_Private then
17928
17929                --  Handle the following erroneous case:
17930                --      type Private_Type is tagged private;
17931                --   private
17932                --      type Private_Type is new Type_Implementing_Iface;
17933
17934                if Present (Full_View (Typ))
17935                  and then Etype (Typ) /= Full_View (Typ)
17936                then
17937                   if Is_Interface (Etype (Typ)) then
17938                      Append_Unique_Elmt (Etype (Typ), Ifaces);
17939                   end if;
17940
17941                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
17942                end if;
17943
17944             --  Non-private types
17945
17946             else
17947                if Is_Interface (Etype (Typ)) then
17948                   Append_Unique_Elmt (Etype (Typ), Ifaces);
17949                end if;
17950
17951                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
17952             end if;
17953          end if;
17954
17955          --  Handle entities in the list of abstract interfaces
17956
17957          if Present (Interfaces (Typ)) then
17958             Iface_Elmt := First_Elmt (Interfaces (Typ));
17959             while Present (Iface_Elmt) loop
17960                Iface := Node (Iface_Elmt);
17961
17962                pragma Assert (Is_Interface (Iface));
17963
17964                if not Contain_Interface (Iface, Ifaces) then
17965                   Append_Elmt (Iface, Ifaces);
17966                   Collect_Implemented_Interfaces (Iface, Ifaces);
17967                end if;
17968
17969                Next_Elmt (Iface_Elmt);
17970             end loop;
17971          end if;
17972       end Collect_Implemented_Interfaces;
17973
17974    --  Start of processing for Process_Full_View
17975
17976    begin
17977       --  First some sanity checks that must be done after semantic
17978       --  decoration of the full view and thus cannot be placed with other
17979       --  similar checks in Find_Type_Name
17980
17981       if not Is_Limited_Type (Priv_T)
17982         and then (Is_Limited_Type (Full_T)
17983                    or else Is_Limited_Composite (Full_T))
17984       then
17985          if In_Instance then
17986             null;
17987          else
17988             Error_Msg_N
17989               ("completion of nonlimited type cannot be limited", Full_T);
17990             Explain_Limited_Type (Full_T, Full_T);
17991          end if;
17992
17993       elsif Is_Abstract_Type (Full_T)
17994         and then not Is_Abstract_Type (Priv_T)
17995       then
17996          Error_Msg_N
17997            ("completion of nonabstract type cannot be abstract", Full_T);
17998
17999       elsif Is_Tagged_Type (Priv_T)
18000         and then Is_Limited_Type (Priv_T)
18001         and then not Is_Limited_Type (Full_T)
18002       then
18003          --  If pragma CPP_Class was applied to the private declaration
18004          --  propagate the limitedness to the full-view
18005
18006          if Is_CPP_Class (Priv_T) then
18007             Set_Is_Limited_Record (Full_T);
18008
18009          --  GNAT allow its own definition of Limited_Controlled to disobey
18010          --  this rule in order in ease the implementation. This test is safe
18011          --  because Root_Controlled is defined in a child of System that
18012          --  normal programs are not supposed to use.
18013
18014          elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
18015             Set_Is_Limited_Composite (Full_T);
18016          else
18017             Error_Msg_N
18018               ("completion of limited tagged type must be limited", Full_T);
18019          end if;
18020
18021       elsif Is_Generic_Type (Priv_T) then
18022          Error_Msg_N ("generic type cannot have a completion", Full_T);
18023       end if;
18024
18025       --  Check that ancestor interfaces of private and full views are
18026       --  consistent. We omit this check for synchronized types because
18027       --  they are performed on the corresponding record type when frozen.
18028
18029       if Ada_Version >= Ada_2005
18030         and then Is_Tagged_Type (Priv_T)
18031         and then Is_Tagged_Type (Full_T)
18032         and then not Is_Concurrent_Type (Full_T)
18033       then
18034          declare
18035             Iface         : Entity_Id;
18036             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
18037             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
18038
18039          begin
18040             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
18041             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
18042
18043             --  Ada 2005 (AI-251): The partial view shall be a descendant of
18044             --  an interface type if and only if the full type is descendant
18045             --  of the interface type (AARM 7.3 (7.3/2)).
18046
18047             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
18048
18049             if Present (Iface) then
18050                Error_Msg_NE
18051                  ("interface & not implemented by full type " &
18052                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
18053             end if;
18054
18055             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
18056
18057             if Present (Iface) then
18058                Error_Msg_NE
18059                  ("interface & not implemented by partial view " &
18060                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
18061             end if;
18062          end;
18063       end if;
18064
18065       if Is_Tagged_Type (Priv_T)
18066         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
18067         and then Is_Derived_Type (Full_T)
18068       then
18069          Priv_Parent := Etype (Priv_T);
18070
18071          --  The full view of a private extension may have been transformed
18072          --  into an unconstrained derived type declaration and a subtype
18073          --  declaration (see build_derived_record_type for details).
18074
18075          if Nkind (N) = N_Subtype_Declaration then
18076             Full_Indic  := Subtype_Indication (N);
18077             Full_Parent := Etype (Base_Type (Full_T));
18078          else
18079             Full_Indic  := Subtype_Indication (Type_Definition (N));
18080             Full_Parent := Etype (Full_T);
18081          end if;
18082
18083          --  Check that the parent type of the full type is a descendant of
18084          --  the ancestor subtype given in the private extension. If either
18085          --  entity has an Etype equal to Any_Type then we had some previous
18086          --  error situation [7.3(8)].
18087
18088          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
18089             return;
18090
18091          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
18092          --  any order. Therefore we don't have to check that its parent must
18093          --  be a descendant of the parent of the private type declaration.
18094
18095          elsif Is_Interface (Priv_Parent)
18096            and then Is_Interface (Full_Parent)
18097          then
18098             null;
18099
18100          --  Ada 2005 (AI-251): If the parent of the private type declaration
18101          --  is an interface there is no need to check that it is an ancestor
18102          --  of the associated full type declaration. The required tests for
18103          --  this case are performed by Build_Derived_Record_Type.
18104
18105          elsif not Is_Interface (Base_Type (Priv_Parent))
18106            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
18107          then
18108             Error_Msg_N
18109               ("parent of full type must descend from parent"
18110                   & " of private extension", Full_Indic);
18111
18112          --  First check a formal restriction, and then proceed with checking
18113          --  Ada rules. Since the formal restriction is not a serious error, we
18114          --  don't prevent further error detection for this check, hence the
18115          --  ELSE.
18116
18117          else
18118
18119             --  In formal mode, when completing a private extension the type
18120             --  named in the private part must be exactly the same as that
18121             --  named in the visible part.
18122
18123             if Priv_Parent /= Full_Parent then
18124                Error_Msg_Name_1 := Chars (Priv_Parent);
18125                Check_SPARK_Restriction ("% expected", Full_Indic);
18126             end if;
18127
18128             --  Check the rules of 7.3(10): if the private extension inherits
18129             --  known discriminants, then the full type must also inherit those
18130             --  discriminants from the same (ancestor) type, and the parent
18131             --  subtype of the full type must be constrained if and only if
18132             --  the ancestor subtype of the private extension is constrained.
18133
18134             if No (Discriminant_Specifications (Parent (Priv_T)))
18135               and then not Has_Unknown_Discriminants (Priv_T)
18136               and then Has_Discriminants (Base_Type (Priv_Parent))
18137             then
18138                declare
18139                   Priv_Indic  : constant Node_Id :=
18140                                   Subtype_Indication (Parent (Priv_T));
18141
18142                   Priv_Constr : constant Boolean :=
18143                                   Is_Constrained (Priv_Parent)
18144                                     or else
18145                                       Nkind (Priv_Indic) = N_Subtype_Indication
18146                                     or else
18147                                       Is_Constrained (Entity (Priv_Indic));
18148
18149                   Full_Constr : constant Boolean :=
18150                                   Is_Constrained (Full_Parent)
18151                                     or else
18152                                       Nkind (Full_Indic) = N_Subtype_Indication
18153                                     or else
18154                                       Is_Constrained (Entity (Full_Indic));
18155
18156                   Priv_Discr : Entity_Id;
18157                   Full_Discr : Entity_Id;
18158
18159                begin
18160                   Priv_Discr := First_Discriminant (Priv_Parent);
18161                   Full_Discr := First_Discriminant (Full_Parent);
18162                   while Present (Priv_Discr) and then Present (Full_Discr) loop
18163                      if Original_Record_Component (Priv_Discr) =
18164                         Original_Record_Component (Full_Discr)
18165                        or else
18166                          Corresponding_Discriminant (Priv_Discr) =
18167                          Corresponding_Discriminant (Full_Discr)
18168                      then
18169                         null;
18170                      else
18171                         exit;
18172                      end if;
18173
18174                      Next_Discriminant (Priv_Discr);
18175                      Next_Discriminant (Full_Discr);
18176                   end loop;
18177
18178                   if Present (Priv_Discr) or else Present (Full_Discr) then
18179                      Error_Msg_N
18180                        ("full view must inherit discriminants of the parent"
18181                         & " type used in the private extension", Full_Indic);
18182
18183                   elsif Priv_Constr and then not Full_Constr then
18184                      Error_Msg_N
18185                        ("parent subtype of full type must be constrained",
18186                         Full_Indic);
18187
18188                   elsif Full_Constr and then not Priv_Constr then
18189                      Error_Msg_N
18190                        ("parent subtype of full type must be unconstrained",
18191                         Full_Indic);
18192                   end if;
18193                end;
18194
18195                --  Check the rules of 7.3(12): if a partial view has neither
18196                --  known or unknown discriminants, then the full type
18197                --  declaration shall define a definite subtype.
18198
18199             elsif      not Has_Unknown_Discriminants (Priv_T)
18200               and then not Has_Discriminants (Priv_T)
18201               and then not Is_Constrained (Full_T)
18202             then
18203                Error_Msg_N
18204                  ("full view must define a constrained type if partial view"
18205                   & " has no discriminants", Full_T);
18206             end if;
18207
18208             --  ??????? Do we implement the following properly ?????
18209             --  If the ancestor subtype of a private extension has constrained
18210             --  discriminants, then the parent subtype of the full view shall
18211             --  impose a statically matching constraint on those discriminants
18212             --  [7.3(13)].
18213          end if;
18214
18215       else
18216          --  For untagged types, verify that a type without discriminants
18217          --  is not completed with an unconstrained type.
18218
18219          if not Is_Indefinite_Subtype (Priv_T)
18220            and then Is_Indefinite_Subtype (Full_T)
18221          then
18222             Error_Msg_N ("full view of type must be definite subtype", Full_T);
18223          end if;
18224       end if;
18225
18226       --  AI-419: verify that the use of "limited" is consistent
18227
18228       declare
18229          Orig_Decl : constant Node_Id := Original_Node (N);
18230
18231       begin
18232          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
18233            and then not Limited_Present (Parent (Priv_T))
18234            and then not Synchronized_Present (Parent (Priv_T))
18235            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
18236            and then Nkind
18237              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
18238            and then Limited_Present (Type_Definition (Orig_Decl))
18239          then
18240             Error_Msg_N
18241               ("full view of non-limited extension cannot be limited", N);
18242          end if;
18243       end;
18244
18245       --  Ada 2005 (AI-443): A synchronized private extension must be
18246       --  completed by a task or protected type.
18247
18248       if Ada_Version >= Ada_2005
18249         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
18250         and then Synchronized_Present (Parent (Priv_T))
18251         and then not Is_Concurrent_Type (Full_T)
18252       then
18253          Error_Msg_N ("full view of synchronized extension must " &
18254                       "be synchronized type", N);
18255       end if;
18256
18257       --  Ada 2005 AI-363: if the full view has discriminants with
18258       --  defaults, it is illegal to declare constrained access subtypes
18259       --  whose designated type is the current type. This allows objects
18260       --  of the type that are declared in the heap to be unconstrained.
18261
18262       if not Has_Unknown_Discriminants (Priv_T)
18263         and then not Has_Discriminants (Priv_T)
18264         and then Has_Discriminants (Full_T)
18265         and then
18266           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
18267       then
18268          Set_Has_Constrained_Partial_View (Full_T);
18269          Set_Has_Constrained_Partial_View (Priv_T);
18270       end if;
18271
18272       --  Create a full declaration for all its subtypes recorded in
18273       --  Private_Dependents and swap them similarly to the base type. These
18274       --  are subtypes that have been define before the full declaration of
18275       --  the private type. We also swap the entry in Private_Dependents list
18276       --  so we can properly restore the private view on exit from the scope.
18277
18278       declare
18279          Priv_Elmt : Elmt_Id;
18280          Priv      : Entity_Id;
18281          Full      : Entity_Id;
18282
18283       begin
18284          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
18285          while Present (Priv_Elmt) loop
18286             Priv := Node (Priv_Elmt);
18287
18288             if Ekind_In (Priv, E_Private_Subtype,
18289                                E_Limited_Private_Subtype,
18290                                E_Record_Subtype_With_Private)
18291             then
18292                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
18293                Set_Is_Itype (Full);
18294                Set_Parent (Full, Parent (Priv));
18295                Set_Associated_Node_For_Itype (Full, N);
18296
18297                --  Now we need to complete the private subtype, but since the
18298                --  base type has already been swapped, we must also swap the
18299                --  subtypes (and thus, reverse the arguments in the call to
18300                --  Complete_Private_Subtype).
18301
18302                Copy_And_Swap (Priv, Full);
18303                Complete_Private_Subtype (Full, Priv, Full_T, N);
18304                Replace_Elmt (Priv_Elmt, Full);
18305             end if;
18306
18307             Next_Elmt (Priv_Elmt);
18308          end loop;
18309       end;
18310
18311       --  If the private view was tagged, copy the new primitive operations
18312       --  from the private view to the full view.
18313
18314       if Is_Tagged_Type (Full_T) then
18315          declare
18316             Disp_Typ  : Entity_Id;
18317             Full_List : Elist_Id;
18318             Prim      : Entity_Id;
18319             Prim_Elmt : Elmt_Id;
18320             Priv_List : Elist_Id;
18321
18322             function Contains
18323               (E : Entity_Id;
18324                L : Elist_Id) return Boolean;
18325             --  Determine whether list L contains element E
18326
18327             --------------
18328             -- Contains --
18329             --------------
18330
18331             function Contains
18332               (E : Entity_Id;
18333                L : Elist_Id) return Boolean
18334             is
18335                List_Elmt : Elmt_Id;
18336
18337             begin
18338                List_Elmt := First_Elmt (L);
18339                while Present (List_Elmt) loop
18340                   if Node (List_Elmt) = E then
18341                      return True;
18342                   end if;
18343
18344                   Next_Elmt (List_Elmt);
18345                end loop;
18346
18347                return False;
18348             end Contains;
18349
18350          --  Start of processing
18351
18352          begin
18353             if Is_Tagged_Type (Priv_T) then
18354                Priv_List := Primitive_Operations (Priv_T);
18355                Prim_Elmt := First_Elmt (Priv_List);
18356
18357                --  In the case of a concurrent type completing a private tagged
18358                --  type, primitives may have been declared in between the two
18359                --  views. These subprograms need to be wrapped the same way
18360                --  entries and protected procedures are handled because they
18361                --  cannot be directly shared by the two views.
18362
18363                if Is_Concurrent_Type (Full_T) then
18364                   declare
18365                      Conc_Typ  : constant Entity_Id :=
18366                                    Corresponding_Record_Type (Full_T);
18367                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
18368                      Wrap_Spec : Node_Id;
18369
18370                   begin
18371                      while Present (Prim_Elmt) loop
18372                         Prim := Node (Prim_Elmt);
18373
18374                         if Comes_From_Source (Prim)
18375                           and then not Is_Abstract_Subprogram (Prim)
18376                         then
18377                            Wrap_Spec :=
18378                              Make_Subprogram_Declaration (Sloc (Prim),
18379                                Specification =>
18380                                  Build_Wrapper_Spec
18381                                    (Subp_Id => Prim,
18382                                     Obj_Typ => Conc_Typ,
18383                                     Formals =>
18384                                       Parameter_Specifications (
18385                                         Parent (Prim))));
18386
18387                            Insert_After (Curr_Nod, Wrap_Spec);
18388                            Curr_Nod := Wrap_Spec;
18389
18390                            Analyze (Wrap_Spec);
18391                         end if;
18392
18393                         Next_Elmt (Prim_Elmt);
18394                      end loop;
18395
18396                      return;
18397                   end;
18398
18399                --  For non-concurrent types, transfer explicit primitives, but
18400                --  omit those inherited from the parent of the private view
18401                --  since they will be re-inherited later on.
18402
18403                else
18404                   Full_List := Primitive_Operations (Full_T);
18405
18406                   while Present (Prim_Elmt) loop
18407                      Prim := Node (Prim_Elmt);
18408
18409                      if Comes_From_Source (Prim)
18410                        and then not Contains (Prim, Full_List)
18411                      then
18412                         Append_Elmt (Prim, Full_List);
18413                      end if;
18414
18415                      Next_Elmt (Prim_Elmt);
18416                   end loop;
18417                end if;
18418
18419             --  Untagged private view
18420
18421             else
18422                Full_List := Primitive_Operations (Full_T);
18423
18424                --  In this case the partial view is untagged, so here we locate
18425                --  all of the earlier primitives that need to be treated as
18426                --  dispatching (those that appear between the two views). Note
18427                --  that these additional operations must all be new operations
18428                --  (any earlier operations that override inherited operations
18429                --  of the full view will already have been inserted in the
18430                --  primitives list, marked by Check_Operation_From_Private_View
18431                --  as dispatching. Note that implicit "/=" operators are
18432                --  excluded from being added to the primitives list since they
18433                --  shouldn't be treated as dispatching (tagged "/=" is handled
18434                --  specially).
18435
18436                Prim := Next_Entity (Full_T);
18437                while Present (Prim) and then Prim /= Priv_T loop
18438                   if Ekind_In (Prim, E_Procedure, E_Function) then
18439                      Disp_Typ := Find_Dispatching_Type (Prim);
18440
18441                      if Disp_Typ = Full_T
18442                        and then (Chars (Prim) /= Name_Op_Ne
18443                                   or else Comes_From_Source (Prim))
18444                      then
18445                         Check_Controlling_Formals (Full_T, Prim);
18446
18447                         if not Is_Dispatching_Operation (Prim) then
18448                            Append_Elmt (Prim, Full_List);
18449                            Set_Is_Dispatching_Operation (Prim, True);
18450                            Set_DT_Position (Prim, No_Uint);
18451                         end if;
18452
18453                      elsif Is_Dispatching_Operation (Prim)
18454                        and then Disp_Typ  /= Full_T
18455                      then
18456
18457                         --  Verify that it is not otherwise controlled by a
18458                         --  formal or a return value of type T.
18459
18460                         Check_Controlling_Formals (Disp_Typ, Prim);
18461                      end if;
18462                   end if;
18463
18464                   Next_Entity (Prim);
18465                end loop;
18466             end if;
18467
18468             --  For the tagged case, the two views can share the same primitive
18469             --  operations list and the same class-wide type. Update attributes
18470             --  of the class-wide type which depend on the full declaration.
18471
18472             if Is_Tagged_Type (Priv_T) then
18473                Set_Direct_Primitive_Operations (Priv_T, Full_List);
18474                Set_Class_Wide_Type
18475                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
18476
18477                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
18478             end if;
18479          end;
18480       end if;
18481
18482       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
18483
18484       if Known_To_Have_Preelab_Init (Priv_T) then
18485
18486          --  Case where there is a pragma Preelaborable_Initialization. We
18487          --  always allow this in predefined units, which is a bit of a kludge,
18488          --  but it means we don't have to struggle to meet the requirements in
18489          --  the RM for having Preelaborable Initialization. Otherwise we
18490          --  require that the type meets the RM rules. But we can't check that
18491          --  yet, because of the rule about overriding Initialize, so we simply
18492          --  set a flag that will be checked at freeze time.
18493
18494          if not In_Predefined_Unit (Full_T) then
18495             Set_Must_Have_Preelab_Init (Full_T);
18496          end if;
18497       end if;
18498
18499       --  If pragma CPP_Class was applied to the private type declaration,
18500       --  propagate it now to the full type declaration.
18501
18502       if Is_CPP_Class (Priv_T) then
18503          Set_Is_CPP_Class (Full_T);
18504          Set_Convention   (Full_T, Convention_CPP);
18505
18506          --  Check that components of imported CPP types do not have default
18507          --  expressions.
18508
18509          Check_CPP_Type_Has_No_Defaults (Full_T);
18510       end if;
18511
18512       --  If the private view has user specified stream attributes, then so has
18513       --  the full view.
18514
18515       --  Why the test, how could these flags be already set in Full_T ???
18516
18517       if Has_Specified_Stream_Read (Priv_T) then
18518          Set_Has_Specified_Stream_Read (Full_T);
18519       end if;
18520
18521       if Has_Specified_Stream_Write (Priv_T) then
18522          Set_Has_Specified_Stream_Write (Full_T);
18523       end if;
18524
18525       if Has_Specified_Stream_Input (Priv_T) then
18526          Set_Has_Specified_Stream_Input (Full_T);
18527       end if;
18528
18529       if Has_Specified_Stream_Output (Priv_T) then
18530          Set_Has_Specified_Stream_Output (Full_T);
18531       end if;
18532
18533       --  Propagate invariants to full type
18534
18535       if Has_Invariants (Priv_T) then
18536          Set_Has_Invariants (Full_T);
18537          Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
18538       end if;
18539
18540       if Has_Inheritable_Invariants (Priv_T) then
18541          Set_Has_Inheritable_Invariants (Full_T);
18542       end if;
18543
18544       --  Propagate predicates to full type
18545
18546       if Has_Predicates (Priv_T) then
18547          Set_Predicate_Function (Priv_T, Predicate_Function (Full_T));
18548          Set_Has_Predicates (Full_T);
18549       end if;
18550    end Process_Full_View;
18551
18552    -----------------------------------
18553    -- Process_Incomplete_Dependents --
18554    -----------------------------------
18555
18556    procedure Process_Incomplete_Dependents
18557      (N      : Node_Id;
18558       Full_T : Entity_Id;
18559       Inc_T  : Entity_Id)
18560    is
18561       Inc_Elmt : Elmt_Id;
18562       Priv_Dep : Entity_Id;
18563       New_Subt : Entity_Id;
18564
18565       Disc_Constraint : Elist_Id;
18566
18567    begin
18568       if No (Private_Dependents (Inc_T)) then
18569          return;
18570       end if;
18571
18572       --  Itypes that may be generated by the completion of an incomplete
18573       --  subtype are not used by the back-end and not attached to the tree.
18574       --  They are created only for constraint-checking purposes.
18575
18576       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
18577       while Present (Inc_Elmt) loop
18578          Priv_Dep := Node (Inc_Elmt);
18579
18580          if Ekind (Priv_Dep) = E_Subprogram_Type then
18581
18582             --  An Access_To_Subprogram type may have a return type or a
18583             --  parameter type that is incomplete. Replace with the full view.
18584
18585             if Etype (Priv_Dep) = Inc_T then
18586                Set_Etype (Priv_Dep, Full_T);
18587             end if;
18588
18589             declare
18590                Formal : Entity_Id;
18591
18592             begin
18593                Formal := First_Formal (Priv_Dep);
18594                while Present (Formal) loop
18595                   if Etype (Formal) = Inc_T then
18596                      Set_Etype (Formal, Full_T);
18597                   end if;
18598
18599                   Next_Formal (Formal);
18600                end loop;
18601             end;
18602
18603          elsif Is_Overloadable (Priv_Dep) then
18604
18605             --  If a subprogram in the incomplete dependents list is primitive
18606             --  for a tagged full type then mark it as a dispatching operation,
18607             --  check whether it overrides an inherited subprogram, and check
18608             --  restrictions on its controlling formals. Note that a protected
18609             --  operation is never dispatching: only its wrapper operation
18610             --  (which has convention Ada) is.
18611
18612             if Is_Tagged_Type (Full_T)
18613               and then Is_Primitive (Priv_Dep)
18614               and then Convention (Priv_Dep) /= Convention_Protected
18615             then
18616                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
18617                Set_Is_Dispatching_Operation (Priv_Dep);
18618                Check_Controlling_Formals (Full_T, Priv_Dep);
18619             end if;
18620
18621          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
18622
18623             --  Can happen during processing of a body before the completion
18624             --  of a TA type. Ignore, because spec is also on dependent list.
18625
18626             return;
18627
18628          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
18629          --  corresponding subtype of the full view.
18630
18631          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
18632             Set_Subtype_Indication
18633               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
18634             Set_Etype (Priv_Dep, Full_T);
18635             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
18636             Set_Analyzed (Parent (Priv_Dep), False);
18637
18638             --  Reanalyze the declaration, suppressing the call to
18639             --  Enter_Name to avoid duplicate names.
18640
18641             Analyze_Subtype_Declaration
18642               (N    => Parent (Priv_Dep),
18643                Skip => True);
18644
18645          --  Dependent is a subtype
18646
18647          else
18648             --  We build a new subtype indication using the full view of the
18649             --  incomplete parent. The discriminant constraints have been
18650             --  elaborated already at the point of the subtype declaration.
18651
18652             New_Subt := Create_Itype (E_Void, N);
18653
18654             if Has_Discriminants (Full_T) then
18655                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
18656             else
18657                Disc_Constraint := No_Elist;
18658             end if;
18659
18660             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
18661             Set_Full_View (Priv_Dep, New_Subt);
18662          end if;
18663
18664          Next_Elmt (Inc_Elmt);
18665       end loop;
18666    end Process_Incomplete_Dependents;
18667
18668    --------------------------------
18669    -- Process_Range_Expr_In_Decl --
18670    --------------------------------
18671
18672    procedure Process_Range_Expr_In_Decl
18673      (R            : Node_Id;
18674       T            : Entity_Id;
18675       Check_List   : List_Id := Empty_List;
18676       R_Check_Off  : Boolean := False;
18677       In_Iter_Schm : Boolean := False)
18678    is
18679       Lo, Hi      : Node_Id;
18680       R_Checks    : Check_Result;
18681       Insert_Node : Node_Id;
18682       Def_Id      : Entity_Id;
18683
18684    begin
18685       Analyze_And_Resolve (R, Base_Type (T));
18686
18687       if Nkind (R) = N_Range then
18688
18689          --  In SPARK, all ranges should be static, with the exception of the
18690          --  discrete type definition of a loop parameter specification.
18691
18692          if not In_Iter_Schm
18693            and then not Is_Static_Range (R)
18694          then
18695             Check_SPARK_Restriction ("range should be static", R);
18696          end if;
18697
18698          Lo := Low_Bound (R);
18699          Hi := High_Bound (R);
18700
18701          --  We need to ensure validity of the bounds here, because if we
18702          --  go ahead and do the expansion, then the expanded code will get
18703          --  analyzed with range checks suppressed and we miss the check.
18704
18705          Validity_Check_Range (R);
18706
18707          --  If there were errors in the declaration, try and patch up some
18708          --  common mistakes in the bounds. The cases handled are literals
18709          --  which are Integer where the expected type is Real and vice versa.
18710          --  These corrections allow the compilation process to proceed further
18711          --  along since some basic assumptions of the format of the bounds
18712          --  are guaranteed.
18713
18714          if Etype (R) = Any_Type then
18715
18716             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
18717                Rewrite (Lo,
18718                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
18719
18720             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
18721                Rewrite (Hi,
18722                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
18723
18724             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
18725                Rewrite (Lo,
18726                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
18727
18728             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
18729                Rewrite (Hi,
18730                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
18731             end if;
18732
18733             Set_Etype (Lo, T);
18734             Set_Etype (Hi, T);
18735          end if;
18736
18737          --  If the bounds of the range have been mistakenly given as string
18738          --  literals (perhaps in place of character literals), then an error
18739          --  has already been reported, but we rewrite the string literal as a
18740          --  bound of the range's type to avoid blowups in later processing
18741          --  that looks at static values.
18742
18743          if Nkind (Lo) = N_String_Literal then
18744             Rewrite (Lo,
18745               Make_Attribute_Reference (Sloc (Lo),
18746                 Attribute_Name => Name_First,
18747                 Prefix => New_Reference_To (T, Sloc (Lo))));
18748             Analyze_And_Resolve (Lo);
18749          end if;
18750
18751          if Nkind (Hi) = N_String_Literal then
18752             Rewrite (Hi,
18753               Make_Attribute_Reference (Sloc (Hi),
18754                 Attribute_Name => Name_First,
18755                 Prefix => New_Reference_To (T, Sloc (Hi))));
18756             Analyze_And_Resolve (Hi);
18757          end if;
18758
18759          --  If bounds aren't scalar at this point then exit, avoiding
18760          --  problems with further processing of the range in this procedure.
18761
18762          if not Is_Scalar_Type (Etype (Lo)) then
18763             return;
18764          end if;
18765
18766          --  Resolve (actually Sem_Eval) has checked that the bounds are in
18767          --  then range of the base type. Here we check whether the bounds
18768          --  are in the range of the subtype itself. Note that if the bounds
18769          --  represent the null range the Constraint_Error exception should
18770          --  not be raised.
18771
18772          --  ??? The following code should be cleaned up as follows
18773
18774          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
18775          --     is done in the call to Range_Check (R, T); below
18776
18777          --  2. The use of R_Check_Off should be investigated and possibly
18778          --     removed, this would clean up things a bit.
18779
18780          if Is_Null_Range (Lo, Hi) then
18781             null;
18782
18783          else
18784             --  Capture values of bounds and generate temporaries for them
18785             --  if needed, before applying checks, since checks may cause
18786             --  duplication of the expression without forcing evaluation.
18787
18788             --  The forced evaluation removes side effects from expressions,
18789             --  which should occur also in SPARK mode. Otherwise, we end up
18790             --  with unexpected insertions of actions at places where this is
18791             --  not supposed to occur, e.g. on default parameters of a call.
18792
18793             if Expander_Active then
18794                Force_Evaluation (Lo);
18795                Force_Evaluation (Hi);
18796             end if;
18797
18798             --  We use a flag here instead of suppressing checks on the
18799             --  type because the type we check against isn't necessarily
18800             --  the place where we put the check.
18801
18802             if not R_Check_Off then
18803                R_Checks := Get_Range_Checks (R, T);
18804
18805                --  Look up tree to find an appropriate insertion point. We
18806                --  can't just use insert_actions because later processing
18807                --  depends on the insertion node. Prior to Ada 2012 the
18808                --  insertion point could only be a declaration or a loop, but
18809                --  quantified expressions can appear within any context in an
18810                --  expression, and the insertion point can be any statement,
18811                --  pragma, or declaration.
18812
18813                Insert_Node := Parent (R);
18814                while Present (Insert_Node) loop
18815                   exit when
18816                     Nkind (Insert_Node) in N_Declaration
18817                     and then
18818                       not Nkind_In
18819                         (Insert_Node, N_Component_Declaration,
18820                                       N_Loop_Parameter_Specification,
18821                                       N_Function_Specification,
18822                                       N_Procedure_Specification);
18823
18824                   exit when Nkind (Insert_Node) in N_Later_Decl_Item
18825                     or else Nkind (Insert_Node) in
18826                               N_Statement_Other_Than_Procedure_Call
18827                     or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
18828                                                    N_Pragma);
18829
18830                   Insert_Node := Parent (Insert_Node);
18831                end loop;
18832
18833                --  Why would Type_Decl not be present???  Without this test,
18834                --  short regression tests fail.
18835
18836                if Present (Insert_Node) then
18837
18838                   --  Case of loop statement. Verify that the range is part
18839                   --  of the subtype indication of the iteration scheme.
18840
18841                   if Nkind (Insert_Node) = N_Loop_Statement then
18842                      declare
18843                         Indic : Node_Id;
18844
18845                      begin
18846                         Indic := Parent (R);
18847                         while Present (Indic)
18848                           and then Nkind (Indic) /= N_Subtype_Indication
18849                         loop
18850                            Indic := Parent (Indic);
18851                         end loop;
18852
18853                         if Present (Indic) then
18854                            Def_Id := Etype (Subtype_Mark (Indic));
18855
18856                            Insert_Range_Checks
18857                              (R_Checks,
18858                               Insert_Node,
18859                               Def_Id,
18860                               Sloc (Insert_Node),
18861                               R,
18862                               Do_Before => True);
18863                         end if;
18864                      end;
18865
18866                   --  Insertion before a declaration. If the declaration
18867                   --  includes discriminants, the list of applicable checks
18868                   --  is given by the caller.
18869
18870                   elsif Nkind (Insert_Node) in N_Declaration then
18871                      Def_Id := Defining_Identifier (Insert_Node);
18872
18873                      if (Ekind (Def_Id) = E_Record_Type
18874                           and then Depends_On_Discriminant (R))
18875                        or else
18876                         (Ekind (Def_Id) = E_Protected_Type
18877                           and then Has_Discriminants (Def_Id))
18878                      then
18879                         Append_Range_Checks
18880                           (R_Checks,
18881                             Check_List, Def_Id, Sloc (Insert_Node), R);
18882
18883                      else
18884                         Insert_Range_Checks
18885                           (R_Checks,
18886                             Insert_Node, Def_Id, Sloc (Insert_Node), R);
18887
18888                      end if;
18889
18890                   --  Insertion before a statement. Range appears in the
18891                   --  context of a quantified expression. Insertion will
18892                   --  take place when expression is expanded.
18893
18894                   else
18895                      null;
18896                   end if;
18897                end if;
18898             end if;
18899          end if;
18900
18901       --  Case of other than an explicit N_Range node
18902
18903       --  The forced evaluation removes side effects from expressions, which
18904       --  should occur also in SPARK mode. Otherwise, we end up with unexpected
18905       --  insertions of actions at places where this is not supposed to occur,
18906       --  e.g. on default parameters of a call.
18907
18908       elsif Expander_Active then
18909          Get_Index_Bounds (R, Lo, Hi);
18910          Force_Evaluation (Lo);
18911          Force_Evaluation (Hi);
18912       end if;
18913    end Process_Range_Expr_In_Decl;
18914
18915    --------------------------------------
18916    -- Process_Real_Range_Specification --
18917    --------------------------------------
18918
18919    procedure Process_Real_Range_Specification (Def : Node_Id) is
18920       Spec : constant Node_Id := Real_Range_Specification (Def);
18921       Lo   : Node_Id;
18922       Hi   : Node_Id;
18923       Err  : Boolean := False;
18924
18925       procedure Analyze_Bound (N : Node_Id);
18926       --  Analyze and check one bound
18927
18928       -------------------
18929       -- Analyze_Bound --
18930       -------------------
18931
18932       procedure Analyze_Bound (N : Node_Id) is
18933       begin
18934          Analyze_And_Resolve (N, Any_Real);
18935
18936          if not Is_OK_Static_Expression (N) then
18937             Flag_Non_Static_Expr
18938               ("bound in real type definition is not static!", N);
18939             Err := True;
18940          end if;
18941       end Analyze_Bound;
18942
18943    --  Start of processing for Process_Real_Range_Specification
18944
18945    begin
18946       if Present (Spec) then
18947          Lo := Low_Bound (Spec);
18948          Hi := High_Bound (Spec);
18949          Analyze_Bound (Lo);
18950          Analyze_Bound (Hi);
18951
18952          --  If error, clear away junk range specification
18953
18954          if Err then
18955             Set_Real_Range_Specification (Def, Empty);
18956          end if;
18957       end if;
18958    end Process_Real_Range_Specification;
18959
18960    ---------------------
18961    -- Process_Subtype --
18962    ---------------------
18963
18964    function Process_Subtype
18965      (S           : Node_Id;
18966       Related_Nod : Node_Id;
18967       Related_Id  : Entity_Id := Empty;
18968       Suffix      : Character := ' ') return Entity_Id
18969    is
18970       P               : Node_Id;
18971       Def_Id          : Entity_Id;
18972       Error_Node      : Node_Id;
18973       Full_View_Id    : Entity_Id;
18974       Subtype_Mark_Id : Entity_Id;
18975
18976       May_Have_Null_Exclusion : Boolean;
18977
18978       procedure Check_Incomplete (T : Entity_Id);
18979       --  Called to verify that an incomplete type is not used prematurely
18980
18981       ----------------------
18982       -- Check_Incomplete --
18983       ----------------------
18984
18985       procedure Check_Incomplete (T : Entity_Id) is
18986       begin
18987          --  Ada 2005 (AI-412): Incomplete subtypes are legal
18988
18989          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
18990            and then
18991              not (Ada_Version >= Ada_2005
18992                     and then
18993                        (Nkind (Parent (T)) = N_Subtype_Declaration
18994                           or else
18995                             (Nkind (Parent (T)) = N_Subtype_Indication
18996                                and then Nkind (Parent (Parent (T))) =
18997                                           N_Subtype_Declaration)))
18998          then
18999             Error_Msg_N ("invalid use of type before its full declaration", T);
19000          end if;
19001       end Check_Incomplete;
19002
19003    --  Start of processing for Process_Subtype
19004
19005    begin
19006       --  Case of no constraints present
19007
19008       if Nkind (S) /= N_Subtype_Indication then
19009          Find_Type (S);
19010          Check_Incomplete (S);
19011          P := Parent (S);
19012
19013          --  Ada 2005 (AI-231): Static check
19014
19015          if Ada_Version >= Ada_2005
19016            and then Present (P)
19017            and then Null_Exclusion_Present (P)
19018            and then Nkind (P) /= N_Access_To_Object_Definition
19019            and then not Is_Access_Type (Entity (S))
19020          then
19021             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
19022          end if;
19023
19024          --  The following is ugly, can't we have a range or even a flag???
19025
19026          May_Have_Null_Exclusion :=
19027            Nkind_In (P, N_Access_Definition,
19028                         N_Access_Function_Definition,
19029                         N_Access_Procedure_Definition,
19030                         N_Access_To_Object_Definition,
19031                         N_Allocator,
19032                         N_Component_Definition)
19033              or else
19034            Nkind_In (P, N_Derived_Type_Definition,
19035                         N_Discriminant_Specification,
19036                         N_Formal_Object_Declaration,
19037                         N_Object_Declaration,
19038                         N_Object_Renaming_Declaration,
19039                         N_Parameter_Specification,
19040                         N_Subtype_Declaration);
19041
19042          --  Create an Itype that is a duplicate of Entity (S) but with the
19043          --  null-exclusion attribute.
19044
19045          if May_Have_Null_Exclusion
19046            and then Is_Access_Type (Entity (S))
19047            and then Null_Exclusion_Present (P)
19048
19049             --  No need to check the case of an access to object definition.
19050             --  It is correct to define double not-null pointers.
19051
19052             --  Example:
19053             --     type Not_Null_Int_Ptr is not null access Integer;
19054             --     type Acc is not null access Not_Null_Int_Ptr;
19055
19056            and then Nkind (P) /= N_Access_To_Object_Definition
19057          then
19058             if Can_Never_Be_Null (Entity (S)) then
19059                case Nkind (Related_Nod) is
19060                   when N_Full_Type_Declaration =>
19061                      if Nkind (Type_Definition (Related_Nod))
19062                        in N_Array_Type_Definition
19063                      then
19064                         Error_Node :=
19065                           Subtype_Indication
19066                             (Component_Definition
19067                              (Type_Definition (Related_Nod)));
19068                      else
19069                         Error_Node :=
19070                           Subtype_Indication (Type_Definition (Related_Nod));
19071                      end if;
19072
19073                   when N_Subtype_Declaration =>
19074                      Error_Node := Subtype_Indication (Related_Nod);
19075
19076                   when N_Object_Declaration =>
19077                      Error_Node := Object_Definition (Related_Nod);
19078
19079                   when N_Component_Declaration =>
19080                      Error_Node :=
19081                        Subtype_Indication (Component_Definition (Related_Nod));
19082
19083                   when N_Allocator =>
19084                      Error_Node := Expression (Related_Nod);
19085
19086                   when others =>
19087                      pragma Assert (False);
19088                      Error_Node := Related_Nod;
19089                end case;
19090
19091                Error_Msg_NE
19092                  ("`NOT NULL` not allowed (& already excludes null)",
19093                   Error_Node,
19094                   Entity (S));
19095             end if;
19096
19097             Set_Etype  (S,
19098               Create_Null_Excluding_Itype
19099                 (T           => Entity (S),
19100                  Related_Nod => P));
19101             Set_Entity (S, Etype (S));
19102          end if;
19103
19104          return Entity (S);
19105
19106       --  Case of constraint present, so that we have an N_Subtype_Indication
19107       --  node (this node is created only if constraints are present).
19108
19109       else
19110          Find_Type (Subtype_Mark (S));
19111
19112          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
19113            and then not
19114             (Nkind (Parent (S)) = N_Subtype_Declaration
19115               and then Is_Itype (Defining_Identifier (Parent (S))))
19116          then
19117             Check_Incomplete (Subtype_Mark (S));
19118          end if;
19119
19120          P := Parent (S);
19121          Subtype_Mark_Id := Entity (Subtype_Mark (S));
19122
19123          --  Explicit subtype declaration case
19124
19125          if Nkind (P) = N_Subtype_Declaration then
19126             Def_Id := Defining_Identifier (P);
19127
19128          --  Explicit derived type definition case
19129
19130          elsif Nkind (P) = N_Derived_Type_Definition then
19131             Def_Id := Defining_Identifier (Parent (P));
19132
19133          --  Implicit case, the Def_Id must be created as an implicit type.
19134          --  The one exception arises in the case of concurrent types, array
19135          --  and access types, where other subsidiary implicit types may be
19136          --  created and must appear before the main implicit type. In these
19137          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
19138          --  has not yet been called to create Def_Id.
19139
19140          else
19141             if Is_Array_Type (Subtype_Mark_Id)
19142               or else Is_Concurrent_Type (Subtype_Mark_Id)
19143               or else Is_Access_Type (Subtype_Mark_Id)
19144             then
19145                Def_Id := Empty;
19146
19147             --  For the other cases, we create a new unattached Itype,
19148             --  and set the indication to ensure it gets attached later.
19149
19150             else
19151                Def_Id :=
19152                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
19153             end if;
19154          end if;
19155
19156          --  If the kind of constraint is invalid for this kind of type,
19157          --  then give an error, and then pretend no constraint was given.
19158
19159          if not Is_Valid_Constraint_Kind
19160                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
19161          then
19162             Error_Msg_N
19163               ("incorrect constraint for this kind of type", Constraint (S));
19164
19165             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
19166
19167             --  Set Ekind of orphan itype, to prevent cascaded errors
19168
19169             if Present (Def_Id) then
19170                Set_Ekind (Def_Id, Ekind (Any_Type));
19171             end if;
19172
19173             --  Make recursive call, having got rid of the bogus constraint
19174
19175             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
19176          end if;
19177
19178          --  Remaining processing depends on type. Select on Base_Type kind to
19179          --  ensure getting to the concrete type kind in the case of a private
19180          --  subtype (needed when only doing semantic analysis).
19181
19182          case Ekind (Base_Type (Subtype_Mark_Id)) is
19183             when Access_Kind =>
19184
19185                --  If this is a constraint on a class-wide type, discard it.
19186                --  There is currently no way to express a partial discriminant
19187                --  constraint on a type with unknown discriminants. This is
19188                --  a pathology that the ACATS wisely decides not to test.
19189
19190                if Is_Class_Wide_Type (Designated_Type (Subtype_Mark_Id)) then
19191                   if Comes_From_Source (S) then
19192                      Error_Msg_N
19193                        ("constraint on class-wide type ignored?",
19194                         Constraint (S));
19195                   end if;
19196
19197                   if Nkind (P) = N_Subtype_Declaration then
19198                      Set_Subtype_Indication (P,
19199                         New_Occurrence_Of (Subtype_Mark_Id, Sloc (S)));
19200                   end if;
19201
19202                   return Subtype_Mark_Id;
19203                end if;
19204
19205                Constrain_Access (Def_Id, S, Related_Nod);
19206
19207                if Expander_Active
19208                  and then  Is_Itype (Designated_Type (Def_Id))
19209                  and then Nkind (Related_Nod) = N_Subtype_Declaration
19210                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
19211                then
19212                   Build_Itype_Reference
19213                     (Designated_Type (Def_Id), Related_Nod);
19214                end if;
19215
19216             when Array_Kind =>
19217                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
19218
19219             when Decimal_Fixed_Point_Kind =>
19220                Constrain_Decimal (Def_Id, S);
19221
19222             when Enumeration_Kind =>
19223                Constrain_Enumeration (Def_Id, S);
19224
19225             when Ordinary_Fixed_Point_Kind =>
19226                Constrain_Ordinary_Fixed (Def_Id, S);
19227
19228             when Float_Kind =>
19229                Constrain_Float (Def_Id, S);
19230
19231             when Integer_Kind =>
19232                Constrain_Integer (Def_Id, S);
19233
19234             when E_Record_Type     |
19235                  E_Record_Subtype  |
19236                  Class_Wide_Kind   |
19237                  E_Incomplete_Type =>
19238                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
19239
19240                if Ekind (Def_Id) = E_Incomplete_Type then
19241                   Set_Private_Dependents (Def_Id, New_Elmt_List);
19242                end if;
19243
19244             when Private_Kind =>
19245                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
19246                Set_Private_Dependents (Def_Id, New_Elmt_List);
19247
19248                --  In case of an invalid constraint prevent further processing
19249                --  since the type constructed is missing expected fields.
19250
19251                if Etype (Def_Id) = Any_Type then
19252                   return Def_Id;
19253                end if;
19254
19255                --  If the full view is that of a task with discriminants,
19256                --  we must constrain both the concurrent type and its
19257                --  corresponding record type. Otherwise we will just propagate
19258                --  the constraint to the full view, if available.
19259
19260                if Present (Full_View (Subtype_Mark_Id))
19261                  and then Has_Discriminants (Subtype_Mark_Id)
19262                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
19263                then
19264                   Full_View_Id :=
19265                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
19266
19267                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
19268                   Constrain_Concurrent (Full_View_Id, S,
19269                     Related_Nod, Related_Id, Suffix);
19270                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
19271                   Set_Full_View (Def_Id, Full_View_Id);
19272
19273                   --  Introduce an explicit reference to the private subtype,
19274                   --  to prevent scope anomalies in gigi if first use appears
19275                   --  in a nested context, e.g. a later function body.
19276                   --  Should this be generated in other contexts than a full
19277                   --  type declaration?
19278
19279                   if Is_Itype (Def_Id)
19280                     and then
19281                       Nkind (Parent (P)) = N_Full_Type_Declaration
19282                   then
19283                      Build_Itype_Reference (Def_Id, Parent (P));
19284                   end if;
19285
19286                else
19287                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
19288                end if;
19289
19290             when Concurrent_Kind  =>
19291                Constrain_Concurrent (Def_Id, S,
19292                  Related_Nod, Related_Id, Suffix);
19293
19294             when others =>
19295                Error_Msg_N ("invalid subtype mark in subtype indication", S);
19296          end case;
19297
19298          --  Size and Convention are always inherited from the base type
19299
19300          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
19301          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
19302
19303          return Def_Id;
19304       end if;
19305    end Process_Subtype;
19306
19307    ---------------------------------------
19308    -- Check_Anonymous_Access_Components --
19309    ---------------------------------------
19310
19311    procedure Check_Anonymous_Access_Components
19312       (Typ_Decl  : Node_Id;
19313        Typ       : Entity_Id;
19314        Prev      : Entity_Id;
19315        Comp_List : Node_Id)
19316    is
19317       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
19318       Anon_Access : Entity_Id;
19319       Acc_Def     : Node_Id;
19320       Comp        : Node_Id;
19321       Comp_Def    : Node_Id;
19322       Decl        : Node_Id;
19323       Type_Def    : Node_Id;
19324
19325       procedure Build_Incomplete_Type_Declaration;
19326       --  If the record type contains components that include an access to the
19327       --  current record, then create an incomplete type declaration for the
19328       --  record, to be used as the designated type of the anonymous access.
19329       --  This is done only once, and only if there is no previous partial
19330       --  view of the type.
19331
19332       function Designates_T (Subt : Node_Id) return Boolean;
19333       --  Check whether a node designates the enclosing record type, or 'Class
19334       --  of that type
19335
19336       function Mentions_T (Acc_Def : Node_Id) return Boolean;
19337       --  Check whether an access definition includes a reference to
19338       --  the enclosing record type. The reference can be a subtype mark
19339       --  in the access definition itself, a 'Class attribute reference, or
19340       --  recursively a reference appearing in a parameter specification
19341       --  or result definition of an access_to_subprogram definition.
19342
19343       --------------------------------------
19344       -- Build_Incomplete_Type_Declaration --
19345       --------------------------------------
19346
19347       procedure Build_Incomplete_Type_Declaration is
19348          Decl  : Node_Id;
19349          Inc_T : Entity_Id;
19350          H     : Entity_Id;
19351
19352          --  Is_Tagged indicates whether the type is tagged. It is tagged if
19353          --  it's "is new ... with record" or else "is tagged record ...".
19354
19355          Is_Tagged : constant Boolean :=
19356              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
19357                  and then
19358                    Present
19359                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
19360            or else
19361              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
19362                  and then Tagged_Present (Type_Definition (Typ_Decl)));
19363
19364       begin
19365          --  If there is a previous partial view, no need to create a new one
19366          --  If the partial view, given by Prev, is incomplete,  If Prev is
19367          --  a private declaration, full declaration is flagged accordingly.
19368
19369          if Prev /= Typ then
19370             if Is_Tagged then
19371                Make_Class_Wide_Type (Prev);
19372                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
19373                Set_Etype (Class_Wide_Type (Typ), Typ);
19374             end if;
19375
19376             return;
19377
19378          elsif Has_Private_Declaration (Typ) then
19379
19380             --  If we refer to T'Class inside T, and T is the completion of a
19381             --  private type, then we need to make sure the class-wide type
19382             --  exists.
19383
19384             if Is_Tagged then
19385                Make_Class_Wide_Type (Typ);
19386             end if;
19387
19388             return;
19389
19390          --  If there was a previous anonymous access type, the incomplete
19391          --  type declaration will have been created already.
19392
19393          elsif Present (Current_Entity (Typ))
19394            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
19395            and then Full_View (Current_Entity (Typ)) = Typ
19396          then
19397             if Is_Tagged
19398               and then Comes_From_Source (Current_Entity (Typ))
19399               and then not Is_Tagged_Type (Current_Entity (Typ))
19400             then
19401                Make_Class_Wide_Type (Typ);
19402                Error_Msg_N
19403                  ("incomplete view of tagged type should be declared tagged??",
19404                   Parent (Current_Entity (Typ)));
19405             end if;
19406             return;
19407
19408          else
19409             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
19410             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
19411
19412             --  Type has already been inserted into the current scope. Remove
19413             --  it, and add incomplete declaration for type, so that subsequent
19414             --  anonymous access types can use it. The entity is unchained from
19415             --  the homonym list and from immediate visibility. After analysis,
19416             --  the entity in the incomplete declaration becomes immediately
19417             --  visible in the record declaration that follows.
19418
19419             H := Current_Entity (Typ);
19420
19421             if H = Typ then
19422                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
19423             else
19424                while Present (H)
19425                  and then Homonym (H) /= Typ
19426                loop
19427                   H := Homonym (Typ);
19428                end loop;
19429
19430                Set_Homonym (H, Homonym (Typ));
19431             end if;
19432
19433             Insert_Before (Typ_Decl, Decl);
19434             Analyze (Decl);
19435             Set_Full_View (Inc_T, Typ);
19436
19437             if Is_Tagged then
19438
19439                --  Create a common class-wide type for both views, and set the
19440                --  Etype of the class-wide type to the full view.
19441
19442                Make_Class_Wide_Type (Inc_T);
19443                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
19444                Set_Etype (Class_Wide_Type (Typ), Typ);
19445             end if;
19446          end if;
19447       end Build_Incomplete_Type_Declaration;
19448
19449       ------------------
19450       -- Designates_T --
19451       ------------------
19452
19453       function Designates_T (Subt : Node_Id) return Boolean is
19454          Type_Id : constant Name_Id := Chars (Typ);
19455
19456          function Names_T (Nam : Node_Id) return Boolean;
19457          --  The record type has not been introduced in the current scope
19458          --  yet, so we must examine the name of the type itself, either
19459          --  an identifier T, or an expanded name of the form P.T, where
19460          --  P denotes the current scope.
19461
19462          -------------
19463          -- Names_T --
19464          -------------
19465
19466          function Names_T (Nam : Node_Id) return Boolean is
19467          begin
19468             if Nkind (Nam) = N_Identifier then
19469                return Chars (Nam) = Type_Id;
19470
19471             elsif Nkind (Nam) = N_Selected_Component then
19472                if Chars (Selector_Name (Nam)) = Type_Id then
19473                   if Nkind (Prefix (Nam)) = N_Identifier then
19474                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
19475
19476                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
19477                      return Chars (Selector_Name (Prefix (Nam))) =
19478                             Chars (Current_Scope);
19479                   else
19480                      return False;
19481                   end if;
19482
19483                else
19484                   return False;
19485                end if;
19486
19487             else
19488                return False;
19489             end if;
19490          end Names_T;
19491
19492       --  Start of processing for Designates_T
19493
19494       begin
19495          if Nkind (Subt) = N_Identifier then
19496             return Chars (Subt) = Type_Id;
19497
19498             --  Reference can be through an expanded name which has not been
19499             --  analyzed yet, and which designates enclosing scopes.
19500
19501          elsif Nkind (Subt) = N_Selected_Component then
19502             if Names_T (Subt) then
19503                return True;
19504
19505             --  Otherwise it must denote an entity that is already visible.
19506             --  The access definition may name a subtype of the enclosing
19507             --  type, if there is a previous incomplete declaration for it.
19508
19509             else
19510                Find_Selected_Component (Subt);
19511                return
19512                  Is_Entity_Name (Subt)
19513                    and then Scope (Entity (Subt)) = Current_Scope
19514                    and then
19515                      (Chars (Base_Type (Entity (Subt))) = Type_Id
19516                        or else
19517                          (Is_Class_Wide_Type (Entity (Subt))
19518                            and then
19519                              Chars (Etype (Base_Type (Entity (Subt)))) =
19520                                                                   Type_Id));
19521             end if;
19522
19523          --  A reference to the current type may appear as the prefix of
19524          --  a 'Class attribute.
19525
19526          elsif Nkind (Subt) = N_Attribute_Reference
19527            and then Attribute_Name (Subt) = Name_Class
19528          then
19529             return Names_T (Prefix (Subt));
19530
19531          else
19532             return False;
19533          end if;
19534       end Designates_T;
19535
19536       ----------------
19537       -- Mentions_T --
19538       ----------------
19539
19540       function Mentions_T (Acc_Def : Node_Id) return Boolean is
19541          Param_Spec : Node_Id;
19542
19543          Acc_Subprg : constant Node_Id :=
19544                         Access_To_Subprogram_Definition (Acc_Def);
19545
19546       begin
19547          if No (Acc_Subprg) then
19548             return Designates_T (Subtype_Mark (Acc_Def));
19549          end if;
19550
19551          --  Component is an access_to_subprogram: examine its formals,
19552          --  and result definition in the case of an access_to_function.
19553
19554          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
19555          while Present (Param_Spec) loop
19556             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
19557               and then Mentions_T (Parameter_Type (Param_Spec))
19558             then
19559                return True;
19560
19561             elsif Designates_T (Parameter_Type (Param_Spec)) then
19562                return True;
19563             end if;
19564
19565             Next (Param_Spec);
19566          end loop;
19567
19568          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
19569             if Nkind (Result_Definition (Acc_Subprg)) =
19570                  N_Access_Definition
19571             then
19572                return Mentions_T (Result_Definition (Acc_Subprg));
19573             else
19574                return Designates_T (Result_Definition (Acc_Subprg));
19575             end if;
19576          end if;
19577
19578          return False;
19579       end Mentions_T;
19580
19581    --  Start of processing for Check_Anonymous_Access_Components
19582
19583    begin
19584       if No (Comp_List) then
19585          return;
19586       end if;
19587
19588       Comp := First (Component_Items (Comp_List));
19589       while Present (Comp) loop
19590          if Nkind (Comp) = N_Component_Declaration
19591            and then Present
19592              (Access_Definition (Component_Definition (Comp)))
19593            and then
19594              Mentions_T (Access_Definition (Component_Definition (Comp)))
19595          then
19596             Comp_Def := Component_Definition (Comp);
19597             Acc_Def :=
19598               Access_To_Subprogram_Definition
19599                 (Access_Definition (Comp_Def));
19600
19601             Build_Incomplete_Type_Declaration;
19602             Anon_Access := Make_Temporary (Loc, 'S');
19603
19604             --  Create a declaration for the anonymous access type: either
19605             --  an access_to_object or an access_to_subprogram.
19606
19607             if Present (Acc_Def) then
19608                if Nkind (Acc_Def) = N_Access_Function_Definition then
19609                   Type_Def :=
19610                     Make_Access_Function_Definition (Loc,
19611                       Parameter_Specifications =>
19612                         Parameter_Specifications (Acc_Def),
19613                       Result_Definition => Result_Definition (Acc_Def));
19614                else
19615                   Type_Def :=
19616                     Make_Access_Procedure_Definition (Loc,
19617                       Parameter_Specifications =>
19618                         Parameter_Specifications (Acc_Def));
19619                end if;
19620
19621             else
19622                Type_Def :=
19623                  Make_Access_To_Object_Definition (Loc,
19624                    Subtype_Indication =>
19625                       Relocate_Node
19626                         (Subtype_Mark
19627                           (Access_Definition (Comp_Def))));
19628
19629                Set_Constant_Present
19630                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
19631                Set_All_Present
19632                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
19633             end if;
19634
19635             Set_Null_Exclusion_Present
19636               (Type_Def,
19637                Null_Exclusion_Present (Access_Definition (Comp_Def)));
19638
19639             Decl :=
19640               Make_Full_Type_Declaration (Loc,
19641                 Defining_Identifier => Anon_Access,
19642                 Type_Definition     => Type_Def);
19643
19644             Insert_Before (Typ_Decl, Decl);
19645             Analyze (Decl);
19646
19647             --  If an access to subprogram, create the extra formals
19648
19649             if Present (Acc_Def) then
19650                Create_Extra_Formals (Designated_Type (Anon_Access));
19651
19652             --  If an access to object, preserve entity of designated type,
19653             --  for ASIS use, before rewriting the component definition.
19654
19655             else
19656                declare
19657                   Desig : Entity_Id;
19658
19659                begin
19660                   Desig := Entity (Subtype_Indication (Type_Def));
19661
19662                   --  If the access definition is to the current  record,
19663                   --  the visible entity at this point is an  incomplete
19664                   --  type. Retrieve the full view to simplify  ASIS queries
19665
19666                   if Ekind (Desig) = E_Incomplete_Type then
19667                      Desig := Full_View (Desig);
19668                   end if;
19669
19670                   Set_Entity
19671                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
19672                end;
19673             end if;
19674
19675             Rewrite (Comp_Def,
19676               Make_Component_Definition (Loc,
19677                 Subtype_Indication =>
19678                New_Occurrence_Of (Anon_Access, Loc)));
19679
19680             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
19681                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
19682             else
19683                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
19684             end if;
19685
19686             Set_Is_Local_Anonymous_Access (Anon_Access);
19687          end if;
19688
19689          Next (Comp);
19690       end loop;
19691
19692       if Present (Variant_Part (Comp_List)) then
19693          declare
19694             V : Node_Id;
19695          begin
19696             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
19697             while Present (V) loop
19698                Check_Anonymous_Access_Components
19699                  (Typ_Decl, Typ, Prev, Component_List (V));
19700                Next_Non_Pragma (V);
19701             end loop;
19702          end;
19703       end if;
19704    end Check_Anonymous_Access_Components;
19705
19706    ----------------------------------
19707    -- Preanalyze_Assert_Expression --
19708    ----------------------------------
19709
19710    procedure Preanalyze_Assert_Expression (N : Node_Id; T : Entity_Id) is
19711    begin
19712       In_Assertion_Expr := In_Assertion_Expr + 1;
19713       Preanalyze_Spec_Expression (N, T);
19714       In_Assertion_Expr := In_Assertion_Expr - 1;
19715    end Preanalyze_Assert_Expression;
19716
19717    --------------------------------
19718    -- Preanalyze_Spec_Expression --
19719    --------------------------------
19720
19721    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
19722       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
19723    begin
19724       In_Spec_Expression := True;
19725       Preanalyze_And_Resolve (N, T);
19726       In_Spec_Expression := Save_In_Spec_Expression;
19727    end Preanalyze_Spec_Expression;
19728
19729    -----------------------------
19730    -- Record_Type_Declaration --
19731    -----------------------------
19732
19733    procedure Record_Type_Declaration
19734      (T    : Entity_Id;
19735       N    : Node_Id;
19736       Prev : Entity_Id)
19737    is
19738       Def       : constant Node_Id := Type_Definition (N);
19739       Is_Tagged : Boolean;
19740       Tag_Comp  : Entity_Id;
19741
19742    begin
19743       --  These flags must be initialized before calling Process_Discriminants
19744       --  because this routine makes use of them.
19745
19746       Set_Ekind             (T, E_Record_Type);
19747       Set_Etype             (T, T);
19748       Init_Size_Align       (T);
19749       Set_Interfaces        (T, No_Elist);
19750       Set_Stored_Constraint (T, No_Elist);
19751
19752       --  Normal case
19753
19754       if Ada_Version < Ada_2005
19755         or else not Interface_Present (Def)
19756       then
19757          if Limited_Present (Def) then
19758             Check_SPARK_Restriction ("limited is not allowed", N);
19759          end if;
19760
19761          if Abstract_Present (Def) then
19762             Check_SPARK_Restriction ("abstract is not allowed", N);
19763          end if;
19764
19765          --  The flag Is_Tagged_Type might have already been set by
19766          --  Find_Type_Name if it detected an error for declaration T. This
19767          --  arises in the case of private tagged types where the full view
19768          --  omits the word tagged.
19769
19770          Is_Tagged :=
19771            Tagged_Present (Def)
19772              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
19773
19774          Set_Is_Tagged_Type      (T, Is_Tagged);
19775          Set_Is_Limited_Record   (T, Limited_Present (Def));
19776
19777          --  Type is abstract if full declaration carries keyword, or if
19778          --  previous partial view did.
19779
19780          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
19781                                       or else Abstract_Present (Def));
19782
19783       else
19784          Check_SPARK_Restriction ("interface is not allowed", N);
19785
19786          Is_Tagged := True;
19787          Analyze_Interface_Declaration (T, Def);
19788
19789          if Present (Discriminant_Specifications (N)) then
19790             Error_Msg_N
19791               ("interface types cannot have discriminants",
19792                 Defining_Identifier
19793                   (First (Discriminant_Specifications (N))));
19794          end if;
19795       end if;
19796
19797       --  First pass: if there are self-referential access components,
19798       --  create the required anonymous access type declarations, and if
19799       --  need be an incomplete type declaration for T itself.
19800
19801       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
19802
19803       if Ada_Version >= Ada_2005
19804         and then Present (Interface_List (Def))
19805       then
19806          Check_Interfaces (N, Def);
19807
19808          declare
19809             Ifaces_List : Elist_Id;
19810
19811          begin
19812             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
19813             --  already in the parents.
19814
19815             Collect_Interfaces
19816               (T               => T,
19817                Ifaces_List     => Ifaces_List,
19818                Exclude_Parents => True);
19819
19820             Set_Interfaces (T, Ifaces_List);
19821          end;
19822       end if;
19823
19824       --  Records constitute a scope for the component declarations within.
19825       --  The scope is created prior to the processing of these declarations.
19826       --  Discriminants are processed first, so that they are visible when
19827       --  processing the other components. The Ekind of the record type itself
19828       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
19829
19830       --  Enter record scope
19831
19832       Push_Scope (T);
19833
19834       --  If an incomplete or private type declaration was already given for
19835       --  the type, then this scope already exists, and the discriminants have
19836       --  been declared within. We must verify that the full declaration
19837       --  matches the incomplete one.
19838
19839       Check_Or_Process_Discriminants (N, T, Prev);
19840
19841       Set_Is_Constrained     (T, not Has_Discriminants (T));
19842       Set_Has_Delayed_Freeze (T, True);
19843
19844       --  For tagged types add a manually analyzed component corresponding
19845       --  to the component _tag, the corresponding piece of tree will be
19846       --  expanded as part of the freezing actions if it is not a CPP_Class.
19847
19848       if Is_Tagged then
19849
19850          --  Do not add the tag unless we are in expansion mode
19851
19852          if Expander_Active then
19853             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
19854             Enter_Name (Tag_Comp);
19855
19856             Set_Ekind                     (Tag_Comp, E_Component);
19857             Set_Is_Tag                    (Tag_Comp);
19858             Set_Is_Aliased                (Tag_Comp);
19859             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
19860             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
19861             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
19862             Init_Component_Location       (Tag_Comp);
19863
19864             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
19865             --  implemented interfaces.
19866
19867             if Has_Interfaces (T) then
19868                Add_Interface_Tag_Components (N, T);
19869             end if;
19870          end if;
19871
19872          Make_Class_Wide_Type (T);
19873          Set_Direct_Primitive_Operations (T, New_Elmt_List);
19874       end if;
19875
19876       --  We must suppress range checks when processing record components in
19877       --  the presence of discriminants, since we don't want spurious checks to
19878       --  be generated during their analysis, but Suppress_Range_Checks flags
19879       --  must be reset the after processing the record definition.
19880
19881       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
19882       --  couldn't we just use the normal range check suppression method here.
19883       --  That would seem cleaner ???
19884
19885       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
19886          Set_Kill_Range_Checks (T, True);
19887          Record_Type_Definition (Def, Prev);
19888          Set_Kill_Range_Checks (T, False);
19889       else
19890          Record_Type_Definition (Def, Prev);
19891       end if;
19892
19893       --  Exit from record scope
19894
19895       End_Scope;
19896
19897       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
19898       --  the implemented interfaces and associate them an aliased entity.
19899
19900       if Is_Tagged
19901         and then not Is_Empty_List (Interface_List (Def))
19902       then
19903          Derive_Progenitor_Subprograms (T, T);
19904       end if;
19905
19906       Check_Function_Writable_Actuals (N);
19907    end Record_Type_Declaration;
19908
19909    ----------------------------
19910    -- Record_Type_Definition --
19911    ----------------------------
19912
19913    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
19914       Component          : Entity_Id;
19915       Ctrl_Components    : Boolean := False;
19916       Final_Storage_Only : Boolean;
19917       T                  : Entity_Id;
19918
19919    begin
19920       if Ekind (Prev_T) = E_Incomplete_Type then
19921          T := Full_View (Prev_T);
19922       else
19923          T := Prev_T;
19924       end if;
19925
19926       --  In SPARK, tagged types and type extensions may only be declared in
19927       --  the specification of library unit packages.
19928
19929       if Present (Def) and then Is_Tagged_Type (T) then
19930          declare
19931             Typ  : Node_Id;
19932             Ctxt : Node_Id;
19933
19934          begin
19935             if Nkind (Parent (Def)) = N_Full_Type_Declaration then
19936                Typ := Parent (Def);
19937             else
19938                pragma Assert
19939                  (Nkind (Parent (Def)) = N_Derived_Type_Definition);
19940                Typ := Parent (Parent (Def));
19941             end if;
19942
19943             Ctxt := Parent (Typ);
19944
19945             if Nkind (Ctxt) = N_Package_Body
19946               and then Nkind (Parent (Ctxt)) = N_Compilation_Unit
19947             then
19948                Check_SPARK_Restriction
19949                  ("type should be defined in package specification", Typ);
19950
19951             elsif Nkind (Ctxt) /= N_Package_Specification
19952               or else Nkind (Parent (Parent (Ctxt))) /= N_Compilation_Unit
19953             then
19954                Check_SPARK_Restriction
19955                  ("type should be defined in library unit package", Typ);
19956             end if;
19957          end;
19958       end if;
19959
19960       Final_Storage_Only := not Is_Controlled (T);
19961
19962       --  Ada 2005: check whether an explicit Limited is present in a derived
19963       --  type declaration.
19964
19965       if Nkind (Parent (Def)) = N_Derived_Type_Definition
19966         and then Limited_Present (Parent (Def))
19967       then
19968          Set_Is_Limited_Record (T);
19969       end if;
19970
19971       --  If the component list of a record type is defined by the reserved
19972       --  word null and there is no discriminant part, then the record type has
19973       --  no components and all records of the type are null records (RM 3.7)
19974       --  This procedure is also called to process the extension part of a
19975       --  record extension, in which case the current scope may have inherited
19976       --  components.
19977
19978       if No (Def)
19979         or else No (Component_List (Def))
19980         or else Null_Present (Component_List (Def))
19981       then
19982          if not Is_Tagged_Type (T) then
19983             Check_SPARK_Restriction ("non-tagged record cannot be null", Def);
19984          end if;
19985
19986       else
19987          Analyze_Declarations (Component_Items (Component_List (Def)));
19988
19989          if Present (Variant_Part (Component_List (Def))) then
19990             Check_SPARK_Restriction ("variant part is not allowed", Def);
19991             Analyze (Variant_Part (Component_List (Def)));
19992          end if;
19993       end if;
19994
19995       --  After completing the semantic analysis of the record definition,
19996       --  record components, both new and inherited, are accessible. Set their
19997       --  kind accordingly. Exclude malformed itypes from illegal declarations,
19998       --  whose Ekind may be void.
19999
20000       Component := First_Entity (Current_Scope);
20001       while Present (Component) loop
20002          if Ekind (Component) = E_Void
20003            and then not Is_Itype (Component)
20004          then
20005             Set_Ekind (Component, E_Component);
20006             Init_Component_Location (Component);
20007          end if;
20008
20009          if Has_Task (Etype (Component)) then
20010             Set_Has_Task (T);
20011          end if;
20012
20013          if Ekind (Component) /= E_Component then
20014             null;
20015
20016          --  Do not set Has_Controlled_Component on a class-wide equivalent
20017          --  type. See Make_CW_Equivalent_Type.
20018
20019          elsif not Is_Class_Wide_Equivalent_Type (T)
20020            and then (Has_Controlled_Component (Etype (Component))
20021                       or else (Chars (Component) /= Name_uParent
20022                                 and then Is_Controlled (Etype (Component))))
20023          then
20024             Set_Has_Controlled_Component (T, True);
20025             Final_Storage_Only :=
20026               Final_Storage_Only
20027                 and then Finalize_Storage_Only (Etype (Component));
20028             Ctrl_Components := True;
20029          end if;
20030
20031          Next_Entity (Component);
20032       end loop;
20033
20034       --  A Type is Finalize_Storage_Only only if all its controlled components
20035       --  are also.
20036
20037       if Ctrl_Components then
20038          Set_Finalize_Storage_Only (T, Final_Storage_Only);
20039       end if;
20040
20041       --  Place reference to end record on the proper entity, which may
20042       --  be a partial view.
20043
20044       if Present (Def) then
20045          Process_End_Label (Def, 'e', Prev_T);
20046       end if;
20047    end Record_Type_Definition;
20048
20049    ------------------------
20050    -- Replace_Components --
20051    ------------------------
20052
20053    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
20054       function Process (N : Node_Id) return Traverse_Result;
20055
20056       -------------
20057       -- Process --
20058       -------------
20059
20060       function Process (N : Node_Id) return Traverse_Result is
20061          Comp : Entity_Id;
20062
20063       begin
20064          if Nkind (N) = N_Discriminant_Specification then
20065             Comp := First_Discriminant (Typ);
20066             while Present (Comp) loop
20067                if Chars (Comp) = Chars (Defining_Identifier (N)) then
20068                   Set_Defining_Identifier (N, Comp);
20069                   exit;
20070                end if;
20071
20072                Next_Discriminant (Comp);
20073             end loop;
20074
20075          elsif Nkind (N) = N_Component_Declaration then
20076             Comp := First_Component (Typ);
20077             while Present (Comp) loop
20078                if Chars (Comp) = Chars (Defining_Identifier (N)) then
20079                   Set_Defining_Identifier (N, Comp);
20080                   exit;
20081                end if;
20082
20083                Next_Component (Comp);
20084             end loop;
20085          end if;
20086
20087          return OK;
20088       end Process;
20089
20090       procedure Replace is new Traverse_Proc (Process);
20091
20092    --  Start of processing for Replace_Components
20093
20094    begin
20095       Replace (Decl);
20096    end Replace_Components;
20097
20098    -------------------------------
20099    -- Set_Completion_Referenced --
20100    -------------------------------
20101
20102    procedure Set_Completion_Referenced (E : Entity_Id) is
20103    begin
20104       --  If in main unit, mark entity that is a completion as referenced,
20105       --  warnings go on the partial view when needed.
20106
20107       if In_Extended_Main_Source_Unit (E) then
20108          Set_Referenced (E);
20109       end if;
20110    end Set_Completion_Referenced;
20111
20112    ---------------------
20113    -- Set_Fixed_Range --
20114    ---------------------
20115
20116    --  The range for fixed-point types is complicated by the fact that we
20117    --  do not know the exact end points at the time of the declaration. This
20118    --  is true for three reasons:
20119
20120    --     A size clause may affect the fudging of the end-points.
20121    --     A small clause may affect the values of the end-points.
20122    --     We try to include the end-points if it does not affect the size.
20123
20124    --  This means that the actual end-points must be established at the
20125    --  point when the type is frozen. Meanwhile, we first narrow the range
20126    --  as permitted (so that it will fit if necessary in a small specified
20127    --  size), and then build a range subtree with these narrowed bounds.
20128    --  Set_Fixed_Range constructs the range from real literal values, and
20129    --  sets the range as the Scalar_Range of the given fixed-point type entity.
20130
20131    --  The parent of this range is set to point to the entity so that it is
20132    --  properly hooked into the tree (unlike normal Scalar_Range entries for
20133    --  other scalar types, which are just pointers to the range in the
20134    --  original tree, this would otherwise be an orphan).
20135
20136    --  The tree is left unanalyzed. When the type is frozen, the processing
20137    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
20138    --  analyzed, and uses this as an indication that it should complete
20139    --  work on the range (it will know the final small and size values).
20140
20141    procedure Set_Fixed_Range
20142      (E   : Entity_Id;
20143       Loc : Source_Ptr;
20144       Lo  : Ureal;
20145       Hi  : Ureal)
20146    is
20147       S : constant Node_Id :=
20148             Make_Range (Loc,
20149               Low_Bound  => Make_Real_Literal (Loc, Lo),
20150               High_Bound => Make_Real_Literal (Loc, Hi));
20151    begin
20152       Set_Scalar_Range (E, S);
20153       Set_Parent (S, E);
20154
20155       --  Before the freeze point, the bounds of a fixed point are universal
20156       --  and carry the corresponding type.
20157
20158       Set_Etype (Low_Bound (S),  Universal_Real);
20159       Set_Etype (High_Bound (S), Universal_Real);
20160    end Set_Fixed_Range;
20161
20162    ----------------------------------
20163    -- Set_Scalar_Range_For_Subtype --
20164    ----------------------------------
20165
20166    procedure Set_Scalar_Range_For_Subtype
20167      (Def_Id : Entity_Id;
20168       R      : Node_Id;
20169       Subt   : Entity_Id)
20170    is
20171       Kind : constant Entity_Kind :=  Ekind (Def_Id);
20172
20173    begin
20174       --  Defend against previous error
20175
20176       if Nkind (R) = N_Error then
20177          return;
20178       end if;
20179
20180       Set_Scalar_Range (Def_Id, R);
20181
20182       --  We need to link the range into the tree before resolving it so
20183       --  that types that are referenced, including importantly the subtype
20184       --  itself, are properly frozen (Freeze_Expression requires that the
20185       --  expression be properly linked into the tree). Of course if it is
20186       --  already linked in, then we do not disturb the current link.
20187
20188       if No (Parent (R)) then
20189          Set_Parent (R, Def_Id);
20190       end if;
20191
20192       --  Reset the kind of the subtype during analysis of the range, to
20193       --  catch possible premature use in the bounds themselves.
20194
20195       Set_Ekind (Def_Id, E_Void);
20196       Process_Range_Expr_In_Decl (R, Subt);
20197       Set_Ekind (Def_Id, Kind);
20198    end Set_Scalar_Range_For_Subtype;
20199
20200    --------------------------------------------------------
20201    -- Set_Stored_Constraint_From_Discriminant_Constraint --
20202    --------------------------------------------------------
20203
20204    procedure Set_Stored_Constraint_From_Discriminant_Constraint
20205      (E : Entity_Id)
20206    is
20207    begin
20208       --  Make sure set if encountered during Expand_To_Stored_Constraint
20209
20210       Set_Stored_Constraint (E, No_Elist);
20211
20212       --  Give it the right value
20213
20214       if Is_Constrained (E) and then Has_Discriminants (E) then
20215          Set_Stored_Constraint (E,
20216            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
20217       end if;
20218    end Set_Stored_Constraint_From_Discriminant_Constraint;
20219
20220    -------------------------------------
20221    -- Signed_Integer_Type_Declaration --
20222    -------------------------------------
20223
20224    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
20225       Implicit_Base : Entity_Id;
20226       Base_Typ      : Entity_Id;
20227       Lo_Val        : Uint;
20228       Hi_Val        : Uint;
20229       Errs          : Boolean := False;
20230       Lo            : Node_Id;
20231       Hi            : Node_Id;
20232
20233       function Can_Derive_From (E : Entity_Id) return Boolean;
20234       --  Determine whether given bounds allow derivation from specified type
20235
20236       procedure Check_Bound (Expr : Node_Id);
20237       --  Check bound to make sure it is integral and static. If not, post
20238       --  appropriate error message and set Errs flag
20239
20240       ---------------------
20241       -- Can_Derive_From --
20242       ---------------------
20243
20244       --  Note we check both bounds against both end values, to deal with
20245       --  strange types like ones with a range of 0 .. -12341234.
20246
20247       function Can_Derive_From (E : Entity_Id) return Boolean is
20248          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
20249          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
20250       begin
20251          return Lo <= Lo_Val and then Lo_Val <= Hi
20252                   and then
20253                 Lo <= Hi_Val and then Hi_Val <= Hi;
20254       end Can_Derive_From;
20255
20256       -----------------
20257       -- Check_Bound --
20258       -----------------
20259
20260       procedure Check_Bound (Expr : Node_Id) is
20261       begin
20262          --  If a range constraint is used as an integer type definition, each
20263          --  bound of the range must be defined by a static expression of some
20264          --  integer type, but the two bounds need not have the same integer
20265          --  type (Negative bounds are allowed.) (RM 3.5.4)
20266
20267          if not Is_Integer_Type (Etype (Expr)) then
20268             Error_Msg_N
20269               ("integer type definition bounds must be of integer type", Expr);
20270             Errs := True;
20271
20272          elsif not Is_OK_Static_Expression (Expr) then
20273             Flag_Non_Static_Expr
20274               ("non-static expression used for integer type bound!", Expr);
20275             Errs := True;
20276
20277          --  The bounds are folded into literals, and we set their type to be
20278          --  universal, to avoid typing difficulties: we cannot set the type
20279          --  of the literal to the new type, because this would be a forward
20280          --  reference for the back end,  and if the original type is user-
20281          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
20282
20283          else
20284             if Is_Entity_Name (Expr) then
20285                Fold_Uint (Expr, Expr_Value (Expr), True);
20286             end if;
20287
20288             Set_Etype (Expr, Universal_Integer);
20289          end if;
20290       end Check_Bound;
20291
20292    --  Start of processing for Signed_Integer_Type_Declaration
20293
20294    begin
20295       --  Create an anonymous base type
20296
20297       Implicit_Base :=
20298         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
20299
20300       --  Analyze and check the bounds, they can be of any integer type
20301
20302       Lo := Low_Bound (Def);
20303       Hi := High_Bound (Def);
20304
20305       --  Arbitrarily use Integer as the type if either bound had an error
20306
20307       if Hi = Error or else Lo = Error then
20308          Base_Typ := Any_Integer;
20309          Set_Error_Posted (T, True);
20310
20311       --  Here both bounds are OK expressions
20312
20313       else
20314          Analyze_And_Resolve (Lo, Any_Integer);
20315          Analyze_And_Resolve (Hi, Any_Integer);
20316
20317          Check_Bound (Lo);
20318          Check_Bound (Hi);
20319
20320          if Errs then
20321             Hi := Type_High_Bound (Standard_Long_Long_Integer);
20322             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
20323          end if;
20324
20325          --  Find type to derive from
20326
20327          Lo_Val := Expr_Value (Lo);
20328          Hi_Val := Expr_Value (Hi);
20329
20330          if Can_Derive_From (Standard_Short_Short_Integer) then
20331             Base_Typ := Base_Type (Standard_Short_Short_Integer);
20332
20333          elsif Can_Derive_From (Standard_Short_Integer) then
20334             Base_Typ := Base_Type (Standard_Short_Integer);
20335
20336          elsif Can_Derive_From (Standard_Integer) then
20337             Base_Typ := Base_Type (Standard_Integer);
20338
20339          elsif Can_Derive_From (Standard_Long_Integer) then
20340             Base_Typ := Base_Type (Standard_Long_Integer);
20341
20342          elsif Can_Derive_From (Standard_Long_Long_Integer) then
20343             Base_Typ := Base_Type (Standard_Long_Long_Integer);
20344
20345          else
20346             Base_Typ := Base_Type (Standard_Long_Long_Integer);
20347             Error_Msg_N ("integer type definition bounds out of range", Def);
20348             Hi := Type_High_Bound (Standard_Long_Long_Integer);
20349             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
20350          end if;
20351       end if;
20352
20353       --  Complete both implicit base and declared first subtype entities
20354
20355       Set_Etype          (Implicit_Base,                 Base_Typ);
20356       Set_Size_Info      (Implicit_Base,                (Base_Typ));
20357       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
20358       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
20359
20360       Set_Ekind          (T, E_Signed_Integer_Subtype);
20361       Set_Etype          (T, Implicit_Base);
20362
20363       --  In formal verification mode, restrict the base type's range to the
20364       --  minimum allowed by RM 3.5.4, namely the smallest symmetric range
20365       --  around zero with a possible extra negative value that contains the
20366       --  subtype range. Keep Size, RM_Size and First_Rep_Item info, which
20367       --  should not be relied upon in formal verification.
20368
20369       if SPARK_Strict_Mode then
20370          declare
20371             Sym_Hi_Val : Uint;
20372             Sym_Lo_Val : Uint;
20373             Dloc       : constant Source_Ptr := Sloc (Def);
20374             Lbound     : Node_Id;
20375             Ubound     : Node_Id;
20376             Bounds     : Node_Id;
20377
20378          begin
20379             --  If the subtype range is empty, the smallest base type range
20380             --  is the symmetric range around zero containing Lo_Val and
20381             --  Hi_Val.
20382
20383             if UI_Gt (Lo_Val, Hi_Val) then
20384                Sym_Hi_Val := UI_Max (UI_Abs (Lo_Val), UI_Abs (Hi_Val));
20385                Sym_Lo_Val := UI_Negate (Sym_Hi_Val);
20386
20387                --  Otherwise, if the subtype range is not empty and Hi_Val has
20388                --  the largest absolute value, Hi_Val is non negative and the
20389                --  smallest base type range is the symmetric range around zero
20390                --  containing Hi_Val.
20391
20392             elsif UI_Le (UI_Abs (Lo_Val), UI_Abs (Hi_Val)) then
20393                Sym_Hi_Val := Hi_Val;
20394                Sym_Lo_Val := UI_Negate (Hi_Val);
20395
20396                --  Otherwise, the subtype range is not empty, Lo_Val has the
20397                --  strictly largest absolute value, Lo_Val is negative and the
20398                --  smallest base type range is the symmetric range around zero
20399                --  with an extra negative value Lo_Val.
20400
20401             else
20402                Sym_Lo_Val := Lo_Val;
20403                Sym_Hi_Val := UI_Sub (UI_Negate (Lo_Val), Uint_1);
20404             end if;
20405
20406             Lbound := Make_Integer_Literal (Dloc, Sym_Lo_Val);
20407             Ubound := Make_Integer_Literal (Dloc, Sym_Hi_Val);
20408             Set_Is_Static_Expression (Lbound);
20409             Set_Is_Static_Expression (Ubound);
20410             Analyze_And_Resolve (Lbound, Any_Integer);
20411             Analyze_And_Resolve (Ubound, Any_Integer);
20412
20413             Bounds := Make_Range (Dloc, Lbound, Ubound);
20414             Set_Etype (Bounds, Base_Typ);
20415
20416             Set_Scalar_Range (Implicit_Base, Bounds);
20417          end;
20418
20419       else
20420          Set_Scalar_Range (Implicit_Base, Scalar_Range (Base_Typ));
20421       end if;
20422
20423       Set_Size_Info      (T,                (Implicit_Base));
20424       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
20425       Set_Scalar_Range   (T, Def);
20426       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
20427       Set_Is_Constrained (T);
20428    end Signed_Integer_Type_Declaration;
20429
20430 end Sem_Ch3;