OSDN Git Service

2011-08-01 Yannick Moy <moy@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch3.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 3                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Elists;   use Elists;
31 with Einfo;    use Einfo;
32 with Errout;   use Errout;
33 with Eval_Fat; use Eval_Fat;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Disp; use Exp_Disp;
37 with Exp_Dist; use Exp_Dist;
38 with Exp_Tss;  use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Fname;    use Fname;
41 with Freeze;   use Freeze;
42 with Itypes;   use Itypes;
43 with Layout;   use Layout;
44 with Lib;      use Lib;
45 with Lib.Xref; use Lib.Xref;
46 with Namet;    use Namet;
47 with Nmake;    use Nmake;
48 with Opt;      use Opt;
49 with Restrict; use Restrict;
50 with Rident;   use Rident;
51 with Rtsfind;  use Rtsfind;
52 with Sem;      use Sem;
53 with Sem_Aux;  use Sem_Aux;
54 with Sem_Case; use Sem_Case;
55 with Sem_Cat;  use Sem_Cat;
56 with Sem_Ch6;  use Sem_Ch6;
57 with Sem_Ch7;  use Sem_Ch7;
58 with Sem_Ch8;  use Sem_Ch8;
59 with Sem_Ch13; use Sem_Ch13;
60 with Sem_Disp; use Sem_Disp;
61 with Sem_Dist; use Sem_Dist;
62 with Sem_Elim; use Sem_Elim;
63 with Sem_Eval; use Sem_Eval;
64 with Sem_Mech; use Sem_Mech;
65 with Sem_Prag; use Sem_Prag;
66 with Sem_Res;  use Sem_Res;
67 with Sem_Smem; use Sem_Smem;
68 with Sem_Type; use Sem_Type;
69 with Sem_Util; use Sem_Util;
70 with Sem_Warn; use Sem_Warn;
71 with Stand;    use Stand;
72 with Sinfo;    use Sinfo;
73 with Sinput;   use Sinput;
74 with Snames;   use Snames;
75 with Targparm; use Targparm;
76 with Tbuild;   use Tbuild;
77 with Ttypes;   use Ttypes;
78 with Uintp;    use Uintp;
79 with Urealp;   use Urealp;
80
81 package body Sem_Ch3 is
82
83    -----------------------
84    -- Local Subprograms --
85    -----------------------
86
87    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
88    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
89    --  abstract interface types implemented by a record type or a derived
90    --  record type.
91
92    procedure Build_Derived_Type
93      (N             : Node_Id;
94       Parent_Type   : Entity_Id;
95       Derived_Type  : Entity_Id;
96       Is_Completion : Boolean;
97       Derive_Subps  : Boolean := True);
98    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
99    --  the N_Full_Type_Declaration node containing the derived type definition.
100    --  Parent_Type is the entity for the parent type in the derived type
101    --  definition and Derived_Type the actual derived type. Is_Completion must
102    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
103    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
104    --  completion of a private type declaration. If Is_Completion is set to
105    --  True, N is the completion of a private type declaration and Derived_Type
106    --  is different from the defining identifier inside N (i.e. Derived_Type /=
107    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
108    --  subprograms should be derived. The only case where this parameter is
109    --  False is when Build_Derived_Type is recursively called to process an
110    --  implicit derived full type for a type derived from a private type (in
111    --  that case the subprograms must only be derived for the private view of
112    --  the type).
113    --
114    --  ??? These flags need a bit of re-examination and re-documentation:
115    --  ???  are they both necessary (both seem related to the recursion)?
116
117    procedure Build_Derived_Access_Type
118      (N            : Node_Id;
119       Parent_Type  : Entity_Id;
120       Derived_Type : Entity_Id);
121    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
122    --  create an implicit base if the parent type is constrained or if the
123    --  subtype indication has a constraint.
124
125    procedure Build_Derived_Array_Type
126      (N            : Node_Id;
127       Parent_Type  : Entity_Id;
128       Derived_Type : Entity_Id);
129    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
130    --  create an implicit base if the parent type is constrained or if the
131    --  subtype indication has a constraint.
132
133    procedure Build_Derived_Concurrent_Type
134      (N            : Node_Id;
135       Parent_Type  : Entity_Id;
136       Derived_Type : Entity_Id);
137    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
138    --  protected type, inherit entries and protected subprograms, check
139    --  legality of discriminant constraints if any.
140
141    procedure Build_Derived_Enumeration_Type
142      (N            : Node_Id;
143       Parent_Type  : Entity_Id;
144       Derived_Type : Entity_Id);
145    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
146    --  type, we must create a new list of literals. Types derived from
147    --  Character and [Wide_]Wide_Character are special-cased.
148
149    procedure Build_Derived_Numeric_Type
150      (N            : Node_Id;
151       Parent_Type  : Entity_Id;
152       Derived_Type : Entity_Id);
153    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
154    --  an anonymous base type, and propagate constraint to subtype if needed.
155
156    procedure Build_Derived_Private_Type
157      (N             : Node_Id;
158       Parent_Type   : Entity_Id;
159       Derived_Type  : Entity_Id;
160       Is_Completion : Boolean;
161       Derive_Subps  : Boolean := True);
162    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
163    --  because the parent may or may not have a completion, and the derivation
164    --  may itself be a completion.
165
166    procedure Build_Derived_Record_Type
167      (N            : Node_Id;
168       Parent_Type  : Entity_Id;
169       Derived_Type : Entity_Id;
170       Derive_Subps : Boolean := True);
171    --  Subsidiary procedure for Build_Derived_Type and
172    --  Analyze_Private_Extension_Declaration used for tagged and untagged
173    --  record types. All parameters are as in Build_Derived_Type except that
174    --  N, in addition to being an N_Full_Type_Declaration node, can also be an
175    --  N_Private_Extension_Declaration node. See the definition of this routine
176    --  for much more info. Derive_Subps indicates whether subprograms should
177    --  be derived from the parent type. The only case where Derive_Subps is
178    --  False is for an implicit derived full type for a type derived from a
179    --  private type (see Build_Derived_Type).
180
181    procedure Build_Discriminal (Discrim : Entity_Id);
182    --  Create the discriminal corresponding to discriminant Discrim, that is
183    --  the parameter corresponding to Discrim to be used in initialization
184    --  procedures for the type where Discrim is a discriminant. Discriminals
185    --  are not used during semantic analysis, and are not fully defined
186    --  entities until expansion. Thus they are not given a scope until
187    --  initialization procedures are built.
188
189    function Build_Discriminant_Constraints
190      (T           : Entity_Id;
191       Def         : Node_Id;
192       Derived_Def : Boolean := False) return Elist_Id;
193    --  Validate discriminant constraints and return the list of the constraints
194    --  in order of discriminant declarations, where T is the discriminated
195    --  unconstrained type. Def is the N_Subtype_Indication node where the
196    --  discriminants constraints for T are specified. Derived_Def is True
197    --  when building the discriminant constraints in a derived type definition
198    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
199    --  type and Def is the constraint "(xxx)" on T and this routine sets the
200    --  Corresponding_Discriminant field of the discriminants in the derived
201    --  type D to point to the corresponding discriminants in the parent type T.
202
203    procedure Build_Discriminated_Subtype
204      (T           : Entity_Id;
205       Def_Id      : Entity_Id;
206       Elist       : Elist_Id;
207       Related_Nod : Node_Id;
208       For_Access  : Boolean := False);
209    --  Subsidiary procedure to Constrain_Discriminated_Type and to
210    --  Process_Incomplete_Dependents. Given
211    --
212    --     T (a possibly discriminated base type)
213    --     Def_Id (a very partially built subtype for T),
214    --
215    --  the call completes Def_Id to be the appropriate E_*_Subtype.
216    --
217    --  The Elist is the list of discriminant constraints if any (it is set
218    --  to No_Elist if T is not a discriminated type, and to an empty list if
219    --  T has discriminants but there are no discriminant constraints). The
220    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
221    --  The For_Access says whether or not this subtype is really constraining
222    --  an access type. That is its sole purpose is the designated type of an
223    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
224    --  is built to avoid freezing T when the access subtype is frozen.
225
226    function Build_Scalar_Bound
227      (Bound : Node_Id;
228       Par_T : Entity_Id;
229       Der_T : Entity_Id) return Node_Id;
230    --  The bounds of a derived scalar type are conversions of the bounds of
231    --  the parent type. Optimize the representation if the bounds are literals.
232    --  Needs a more complete spec--what are the parameters exactly, and what
233    --  exactly is the returned value, and how is Bound affected???
234
235    procedure Build_Underlying_Full_View
236      (N   : Node_Id;
237       Typ : Entity_Id;
238       Par : Entity_Id);
239    --  If the completion of a private type is itself derived from a private
240    --  type, or if the full view of a private subtype is itself private, the
241    --  back-end has no way to compute the actual size of this type. We build
242    --  an internal subtype declaration of the proper parent type to convey
243    --  this information. This extra mechanism is needed because a full
244    --  view cannot itself have a full view (it would get clobbered during
245    --  view exchanges).
246
247    procedure Check_Access_Discriminant_Requires_Limited
248      (D   : Node_Id;
249       Loc : Node_Id);
250    --  Check the restriction that the type to which an access discriminant
251    --  belongs must be a concurrent type or a descendant of a type with
252    --  the reserved word 'limited' in its declaration.
253
254    procedure Check_Anonymous_Access_Components
255       (Typ_Decl  : Node_Id;
256        Typ       : Entity_Id;
257        Prev      : Entity_Id;
258        Comp_List : Node_Id);
259    --  Ada 2005 AI-382: an access component in a record definition can refer to
260    --  the enclosing record, in which case it denotes the type itself, and not
261    --  the current instance of the type. We create an anonymous access type for
262    --  the component, and flag it as an access to a component, so accessibility
263    --  checks are properly performed on it. The declaration of the access type
264    --  is placed ahead of that of the record to prevent order-of-elaboration
265    --  circularity issues in Gigi. We create an incomplete type for the record
266    --  declaration, which is the designated type of the anonymous access.
267
268    procedure Check_Delta_Expression (E : Node_Id);
269    --  Check that the expression represented by E is suitable for use as a
270    --  delta expression, i.e. it is of real type and is static.
271
272    procedure Check_Digits_Expression (E : Node_Id);
273    --  Check that the expression represented by E is suitable for use as a
274    --  digits expression, i.e. it is of integer type, positive and static.
275
276    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
277    --  Validate the initialization of an object declaration. T is the required
278    --  type, and Exp is the initialization expression.
279
280    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
281    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
282
283    procedure Check_Or_Process_Discriminants
284      (N    : Node_Id;
285       T    : Entity_Id;
286       Prev : Entity_Id := Empty);
287    --  If N is the full declaration of the completion T of an incomplete or
288    --  private type, check its discriminants (which are already known to be
289    --  conformant with those of the partial view, see Find_Type_Name),
290    --  otherwise process them. Prev is the entity of the partial declaration,
291    --  if any.
292
293    procedure Check_Real_Bound (Bound : Node_Id);
294    --  Check given bound for being of real type and static. If not, post an
295    --  appropriate message, and rewrite the bound with the real literal zero.
296
297    procedure Constant_Redeclaration
298      (Id : Entity_Id;
299       N  : Node_Id;
300       T  : out Entity_Id);
301    --  Various checks on legality of full declaration of deferred constant.
302    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
303    --  node. The caller has not yet set any attributes of this entity.
304
305    function Contain_Interface
306      (Iface  : Entity_Id;
307       Ifaces : Elist_Id) return Boolean;
308    --  Ada 2005: Determine whether Iface is present in the list Ifaces
309
310    procedure Convert_Scalar_Bounds
311      (N            : Node_Id;
312       Parent_Type  : Entity_Id;
313       Derived_Type : Entity_Id;
314       Loc          : Source_Ptr);
315    --  For derived scalar types, convert the bounds in the type definition to
316    --  the derived type, and complete their analysis. Given a constraint of the
317    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
318    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
319    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
320    --  subtype are conversions of those bounds to the derived_type, so that
321    --  their typing is consistent.
322
323    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
324    --  Copies attributes from array base type T2 to array base type T1. Copies
325    --  only attributes that apply to base types, but not subtypes.
326
327    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
328    --  Copies attributes from array subtype T2 to array subtype T1. Copies
329    --  attributes that apply to both subtypes and base types.
330
331    procedure Create_Constrained_Components
332      (Subt        : Entity_Id;
333       Decl_Node   : Node_Id;
334       Typ         : Entity_Id;
335       Constraints : Elist_Id);
336    --  Build the list of entities for a constrained discriminated record
337    --  subtype. If a component depends on a discriminant, replace its subtype
338    --  using the discriminant values in the discriminant constraint. Subt
339    --  is the defining identifier for the subtype whose list of constrained
340    --  entities we will create. Decl_Node is the type declaration node where
341    --  we will attach all the itypes created. Typ is the base discriminated
342    --  type for the subtype Subt. Constraints is the list of discriminant
343    --  constraints for Typ.
344
345    function Constrain_Component_Type
346      (Comp            : Entity_Id;
347       Constrained_Typ : Entity_Id;
348       Related_Node    : Node_Id;
349       Typ             : Entity_Id;
350       Constraints     : Elist_Id) return Entity_Id;
351    --  Given a discriminated base type Typ, a list of discriminant constraint
352    --  Constraints for Typ and a component of Typ, with type Compon_Type,
353    --  create and return the type corresponding to Compon_type where all
354    --  discriminant references are replaced with the corresponding constraint.
355    --  If no discriminant references occur in Compon_Typ then return it as is.
356    --  Constrained_Typ is the final constrained subtype to which the
357    --  constrained Compon_Type belongs. Related_Node is the node where we will
358    --  attach all the itypes created.
359    --
360    --  Above description is confused, what is Compon_Type???
361
362    procedure Constrain_Access
363      (Def_Id      : in out Entity_Id;
364       S           : Node_Id;
365       Related_Nod : Node_Id);
366    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
367    --  an anonymous type created for a subtype indication. In that case it is
368    --  created in the procedure and attached to Related_Nod.
369
370    procedure Constrain_Array
371      (Def_Id      : in out Entity_Id;
372       SI          : Node_Id;
373       Related_Nod : Node_Id;
374       Related_Id  : Entity_Id;
375       Suffix      : Character);
376    --  Apply a list of index constraints to an unconstrained array type. The
377    --  first parameter is the entity for the resulting subtype. A value of
378    --  Empty for Def_Id indicates that an implicit type must be created, but
379    --  creation is delayed (and must be done by this procedure) because other
380    --  subsidiary implicit types must be created first (which is why Def_Id
381    --  is an in/out parameter). The second parameter is a subtype indication
382    --  node for the constrained array to be created (e.g. something of the
383    --  form string (1 .. 10)). Related_Nod gives the place where this type
384    --  has to be inserted in the tree. The Related_Id and Suffix parameters
385    --  are used to build the associated Implicit type name.
386
387    procedure Constrain_Concurrent
388      (Def_Id      : in out Entity_Id;
389       SI          : Node_Id;
390       Related_Nod : Node_Id;
391       Related_Id  : Entity_Id;
392       Suffix      : Character);
393    --  Apply list of discriminant constraints to an unconstrained concurrent
394    --  type.
395    --
396    --    SI is the N_Subtype_Indication node containing the constraint and
397    --    the unconstrained type to constrain.
398    --
399    --    Def_Id is the entity for the resulting constrained subtype. A value
400    --    of Empty for Def_Id indicates that an implicit type must be created,
401    --    but creation is delayed (and must be done by this procedure) because
402    --    other subsidiary implicit types must be created first (which is why
403    --    Def_Id is an in/out parameter).
404    --
405    --    Related_Nod gives the place where this type has to be inserted
406    --    in the tree
407    --
408    --  The last two arguments are used to create its external name if needed.
409
410    function Constrain_Corresponding_Record
411      (Prot_Subt   : Entity_Id;
412       Corr_Rec    : Entity_Id;
413       Related_Nod : Node_Id;
414       Related_Id  : Entity_Id) return Entity_Id;
415    --  When constraining a protected type or task type with discriminants,
416    --  constrain the corresponding record with the same discriminant values.
417
418    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
419    --  Constrain a decimal fixed point type with a digits constraint and/or a
420    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
421
422    procedure Constrain_Discriminated_Type
423      (Def_Id      : Entity_Id;
424       S           : Node_Id;
425       Related_Nod : Node_Id;
426       For_Access  : Boolean := False);
427    --  Process discriminant constraints of composite type. Verify that values
428    --  have been provided for all discriminants, that the original type is
429    --  unconstrained, and that the types of the supplied expressions match
430    --  the discriminant types. The first three parameters are like in routine
431    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
432    --  of For_Access.
433
434    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
435    --  Constrain an enumeration type with a range constraint. This is identical
436    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
437
438    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
439    --  Constrain a floating point type with either a digits constraint
440    --  and/or a range constraint, building a E_Floating_Point_Subtype.
441
442    procedure Constrain_Index
443      (Index        : Node_Id;
444       S            : Node_Id;
445       Related_Nod  : Node_Id;
446       Related_Id   : Entity_Id;
447       Suffix       : Character;
448       Suffix_Index : Nat);
449    --  Process an index constraint S in a constrained array declaration. The
450    --  constraint can be a subtype name, or a range with or without an explicit
451    --  subtype mark. The index is the corresponding index of the unconstrained
452    --  array. The Related_Id and Suffix parameters are used to build the
453    --  associated Implicit type name.
454
455    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
456    --  Build subtype of a signed or modular integer type
457
458    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
459    --  Constrain an ordinary fixed point type with a range constraint, and
460    --  build an E_Ordinary_Fixed_Point_Subtype entity.
461
462    procedure Copy_And_Swap (Priv, Full : Entity_Id);
463    --  Copy the Priv entity into the entity of its full declaration then swap
464    --  the two entities in such a manner that the former private type is now
465    --  seen as a full type.
466
467    procedure Decimal_Fixed_Point_Type_Declaration
468      (T   : Entity_Id;
469       Def : Node_Id);
470    --  Create a new decimal fixed point type, and apply the constraint to
471    --  obtain a subtype of this new type.
472
473    procedure Complete_Private_Subtype
474      (Priv        : Entity_Id;
475       Full        : Entity_Id;
476       Full_Base   : Entity_Id;
477       Related_Nod : Node_Id);
478    --  Complete the implicit full view of a private subtype by setting the
479    --  appropriate semantic fields. If the full view of the parent is a record
480    --  type, build constrained components of subtype.
481
482    procedure Derive_Progenitor_Subprograms
483      (Parent_Type : Entity_Id;
484       Tagged_Type : Entity_Id);
485    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
486    --  operations of progenitors of Tagged_Type, and replace the subsidiary
487    --  subtypes with Tagged_Type, to build the specs of the inherited interface
488    --  primitives. The derived primitives are aliased to those of the
489    --  interface. This routine takes care also of transferring to the full view
490    --  subprograms associated with the partial view of Tagged_Type that cover
491    --  interface primitives.
492
493    procedure Derived_Standard_Character
494      (N             : Node_Id;
495       Parent_Type   : Entity_Id;
496       Derived_Type  : Entity_Id);
497    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
498    --  derivations from types Standard.Character and Standard.Wide_Character.
499
500    procedure Derived_Type_Declaration
501      (T             : Entity_Id;
502       N             : Node_Id;
503       Is_Completion : Boolean);
504    --  Process a derived type declaration. Build_Derived_Type is invoked
505    --  to process the actual derived type definition. Parameters N and
506    --  Is_Completion have the same meaning as in Build_Derived_Type.
507    --  T is the N_Defining_Identifier for the entity defined in the
508    --  N_Full_Type_Declaration node N, that is T is the derived type.
509
510    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
511    --  Insert each literal in symbol table, as an overloadable identifier. Each
512    --  enumeration type is mapped into a sequence of integers, and each literal
513    --  is defined as a constant with integer value. If any of the literals are
514    --  character literals, the type is a character type, which means that
515    --  strings are legal aggregates for arrays of components of the type.
516
517    function Expand_To_Stored_Constraint
518      (Typ        : Entity_Id;
519       Constraint : Elist_Id) return Elist_Id;
520    --  Given a constraint (i.e. a list of expressions) on the discriminants of
521    --  Typ, expand it into a constraint on the stored discriminants and return
522    --  the new list of expressions constraining the stored discriminants.
523
524    function Find_Type_Of_Object
525      (Obj_Def     : Node_Id;
526       Related_Nod : Node_Id) return Entity_Id;
527    --  Get type entity for object referenced by Obj_Def, attaching the
528    --  implicit types generated to Related_Nod
529
530    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
531    --  Create a new float and apply the constraint to obtain subtype of it
532
533    function Has_Range_Constraint (N : Node_Id) return Boolean;
534    --  Given an N_Subtype_Indication node N, return True if a range constraint
535    --  is present, either directly, or as part of a digits or delta constraint.
536    --  In addition, a digits constraint in the decimal case returns True, since
537    --  it establishes a default range if no explicit range is present.
538
539    function Inherit_Components
540      (N             : Node_Id;
541       Parent_Base   : Entity_Id;
542       Derived_Base  : Entity_Id;
543       Is_Tagged     : Boolean;
544       Inherit_Discr : Boolean;
545       Discs         : Elist_Id) return Elist_Id;
546    --  Called from Build_Derived_Record_Type to inherit the components of
547    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
548    --  For more information on derived types and component inheritance please
549    --  consult the comment above the body of Build_Derived_Record_Type.
550    --
551    --    N is the original derived type declaration
552    --
553    --    Is_Tagged is set if we are dealing with tagged types
554    --
555    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
556    --    Parent_Base, otherwise no discriminants are inherited.
557    --
558    --    Discs gives the list of constraints that apply to Parent_Base in the
559    --    derived type declaration. If Discs is set to No_Elist, then we have
560    --    the following situation:
561    --
562    --      type Parent (D1..Dn : ..) is [tagged] record ...;
563    --      type Derived is new Parent [with ...];
564    --
565    --    which gets treated as
566    --
567    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
568    --
569    --  For untagged types the returned value is an association list. The list
570    --  starts from the association (Parent_Base => Derived_Base), and then it
571    --  contains a sequence of the associations of the form
572    --
573    --    (Old_Component => New_Component),
574    --
575    --  where Old_Component is the Entity_Id of a component in Parent_Base and
576    --  New_Component is the Entity_Id of the corresponding component in
577    --  Derived_Base. For untagged records, this association list is needed when
578    --  copying the record declaration for the derived base. In the tagged case
579    --  the value returned is irrelevant.
580
581    function Is_Valid_Constraint_Kind
582      (T_Kind          : Type_Kind;
583       Constraint_Kind : Node_Kind) return Boolean;
584    --  Returns True if it is legal to apply the given kind of constraint to the
585    --  given kind of type (index constraint to an array type, for example).
586
587    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
588    --  Create new modular type. Verify that modulus is in bounds and is
589    --  a power of two (implementation restriction).
590
591    procedure New_Concatenation_Op (Typ : Entity_Id);
592    --  Create an abbreviated declaration for an operator in order to
593    --  materialize concatenation on array types.
594
595    procedure Ordinary_Fixed_Point_Type_Declaration
596      (T   : Entity_Id;
597       Def : Node_Id);
598    --  Create a new ordinary fixed point type, and apply the constraint to
599    --  obtain subtype of it.
600
601    procedure Prepare_Private_Subtype_Completion
602      (Id          : Entity_Id;
603       Related_Nod : Node_Id);
604    --  Id is a subtype of some private type. Creates the full declaration
605    --  associated with Id whenever possible, i.e. when the full declaration
606    --  of the base type is already known. Records each subtype into
607    --  Private_Dependents of the base type.
608
609    procedure Process_Incomplete_Dependents
610      (N      : Node_Id;
611       Full_T : Entity_Id;
612       Inc_T  : Entity_Id);
613    --  Process all entities that depend on an incomplete type. There include
614    --  subtypes, subprogram types that mention the incomplete type in their
615    --  profiles, and subprogram with access parameters that designate the
616    --  incomplete type.
617
618    --  Inc_T is the defining identifier of an incomplete type declaration, its
619    --  Ekind is E_Incomplete_Type.
620    --
621    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
622    --
623    --    Full_T is N's defining identifier.
624    --
625    --  Subtypes of incomplete types with discriminants are completed when the
626    --  parent type is. This is simpler than private subtypes, because they can
627    --  only appear in the same scope, and there is no need to exchange views.
628    --  Similarly, access_to_subprogram types may have a parameter or a return
629    --  type that is an incomplete type, and that must be replaced with the
630    --  full type.
631    --
632    --  If the full type is tagged, subprogram with access parameters that
633    --  designated the incomplete may be primitive operations of the full type,
634    --  and have to be processed accordingly.
635
636    procedure Process_Real_Range_Specification (Def : Node_Id);
637    --  Given the type definition for a real type, this procedure processes and
638    --  checks the real range specification of this type definition if one is
639    --  present. If errors are found, error messages are posted, and the
640    --  Real_Range_Specification of Def is reset to Empty.
641
642    procedure Record_Type_Declaration
643      (T    : Entity_Id;
644       N    : Node_Id;
645       Prev : Entity_Id);
646    --  Process a record type declaration (for both untagged and tagged
647    --  records). Parameters T and N are exactly like in procedure
648    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
649    --  for this routine. If this is the completion of an incomplete type
650    --  declaration, Prev is the entity of the incomplete declaration, used for
651    --  cross-referencing. Otherwise Prev = T.
652
653    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
654    --  This routine is used to process the actual record type definition (both
655    --  for untagged and tagged records). Def is a record type definition node.
656    --  This procedure analyzes the components in this record type definition.
657    --  Prev_T is the entity for the enclosing record type. It is provided so
658    --  that its Has_Task flag can be set if any of the component have Has_Task
659    --  set. If the declaration is the completion of an incomplete type
660    --  declaration, Prev_T is the original incomplete type, whose full view is
661    --  the record type.
662
663    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
664    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
665    --  build a copy of the declaration tree of the parent, and we create
666    --  independently the list of components for the derived type. Semantic
667    --  information uses the component entities, but record representation
668    --  clauses are validated on the declaration tree. This procedure replaces
669    --  discriminants and components in the declaration with those that have
670    --  been created by Inherit_Components.
671
672    procedure Set_Fixed_Range
673      (E   : Entity_Id;
674       Loc : Source_Ptr;
675       Lo  : Ureal;
676       Hi  : Ureal);
677    --  Build a range node with the given bounds and set it as the Scalar_Range
678    --  of the given fixed-point type entity. Loc is the source location used
679    --  for the constructed range. See body for further details.
680
681    procedure Set_Scalar_Range_For_Subtype
682      (Def_Id : Entity_Id;
683       R      : Node_Id;
684       Subt   : Entity_Id);
685    --  This routine is used to set the scalar range field for a subtype given
686    --  Def_Id, the entity for the subtype, and R, the range expression for the
687    --  scalar range. Subt provides the parent subtype to be used to analyze,
688    --  resolve, and check the given range.
689
690    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
691    --  Create a new signed integer entity, and apply the constraint to obtain
692    --  the required first named subtype of this type.
693
694    procedure Set_Stored_Constraint_From_Discriminant_Constraint
695      (E : Entity_Id);
696    --  E is some record type. This routine computes E's Stored_Constraint
697    --  from its Discriminant_Constraint.
698
699    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
700    --  Check that an entity in a list of progenitors is an interface,
701    --  emit error otherwise.
702
703    -----------------------
704    -- Access_Definition --
705    -----------------------
706
707    function Access_Definition
708      (Related_Nod : Node_Id;
709       N           : Node_Id) return Entity_Id
710    is
711       Loc                 : constant Source_Ptr := Sloc (Related_Nod);
712       Anon_Type           : Entity_Id;
713       Anon_Scope          : Entity_Id;
714       Desig_Type          : Entity_Id;
715       Decl                : Entity_Id;
716       Enclosing_Prot_Type : Entity_Id := Empty;
717
718    begin
719       if Is_Entry (Current_Scope)
720         and then Is_Task_Type (Etype (Scope (Current_Scope)))
721       then
722          Error_Msg_N ("task entries cannot have access parameters", N);
723          return Empty;
724       end if;
725
726       --  Ada 2005: for an object declaration the corresponding anonymous
727       --  type is declared in the current scope.
728
729       --  If the access definition is the return type of another access to
730       --  function, scope is the current one, because it is the one of the
731       --  current type declaration.
732
733       if Nkind_In (Related_Nod, N_Object_Declaration,
734                                 N_Access_Function_Definition)
735       then
736          Anon_Scope := Current_Scope;
737
738       --  For the anonymous function result case, retrieve the scope of the
739       --  function specification's associated entity rather than using the
740       --  current scope. The current scope will be the function itself if the
741       --  formal part is currently being analyzed, but will be the parent scope
742       --  in the case of a parameterless function, and we always want to use
743       --  the function's parent scope. Finally, if the function is a child
744       --  unit, we must traverse the tree to retrieve the proper entity.
745
746       elsif Nkind (Related_Nod) = N_Function_Specification
747         and then Nkind (Parent (N)) /= N_Parameter_Specification
748       then
749          --  If the current scope is a protected type, the anonymous access
750          --  is associated with one of the protected operations, and must
751          --  be available in the scope that encloses the protected declaration.
752          --  Otherwise the type is in the scope enclosing the subprogram.
753
754          --  If the function has formals, The return type of a subprogram
755          --  declaration is analyzed in the scope of the subprogram (see
756          --  Process_Formals) and thus the protected type, if present, is
757          --  the scope of the current function scope.
758
759          if Ekind (Current_Scope) = E_Protected_Type then
760             Enclosing_Prot_Type := Current_Scope;
761
762          elsif Ekind (Current_Scope) = E_Function
763            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
764          then
765             Enclosing_Prot_Type := Scope (Current_Scope);
766          end if;
767
768          if Present (Enclosing_Prot_Type) then
769             Anon_Scope := Scope (Enclosing_Prot_Type);
770
771          else
772             Anon_Scope := Scope (Defining_Entity (Related_Nod));
773          end if;
774
775       else
776          --  For access formals, access components, and access discriminants,
777          --  the scope is that of the enclosing declaration,
778
779          Anon_Scope := Scope (Current_Scope);
780       end if;
781
782       Anon_Type :=
783         Create_Itype
784          (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
785
786       if All_Present (N)
787         and then Ada_Version >= Ada_2005
788       then
789          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
790       end if;
791
792       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
793       --  the corresponding semantic routine
794
795       if Present (Access_To_Subprogram_Definition (N)) then
796          Access_Subprogram_Declaration
797            (T_Name => Anon_Type,
798             T_Def  => Access_To_Subprogram_Definition (N));
799
800          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
801             Set_Ekind
802               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
803          else
804             Set_Ekind
805               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
806          end if;
807
808          Set_Can_Use_Internal_Rep
809            (Anon_Type, not Always_Compatible_Rep_On_Target);
810
811          --  If the anonymous access is associated with a protected operation
812          --  create a reference to it after the enclosing protected definition
813          --  because the itype will be used in the subsequent bodies.
814
815          if Ekind (Current_Scope) = E_Protected_Type then
816             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
817          end if;
818
819          return Anon_Type;
820       end if;
821
822       Find_Type (Subtype_Mark (N));
823       Desig_Type := Entity (Subtype_Mark (N));
824
825       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
826       Set_Etype (Anon_Type, Anon_Type);
827
828       --  Make sure the anonymous access type has size and alignment fields
829       --  set, as required by gigi. This is necessary in the case of the
830       --  Task_Body_Procedure.
831
832       if not Has_Private_Component (Desig_Type) then
833          Layout_Type (Anon_Type);
834       end if;
835
836       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
837       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
838       --  the null value is allowed. In Ada 95 the null value is never allowed.
839
840       if Ada_Version >= Ada_2005 then
841          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
842       else
843          Set_Can_Never_Be_Null (Anon_Type, True);
844       end if;
845
846       --  The anonymous access type is as public as the discriminated type or
847       --  subprogram that defines it. It is imported (for back-end purposes)
848       --  if the designated type is.
849
850       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
851
852       --  Ada 2005 (AI-231): Propagate the access-constant attribute
853
854       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
855
856       --  The context is either a subprogram declaration, object declaration,
857       --  or an access discriminant, in a private or a full type declaration.
858       --  In the case of a subprogram, if the designated type is incomplete,
859       --  the operation will be a primitive operation of the full type, to be
860       --  updated subsequently. If the type is imported through a limited_with
861       --  clause, the subprogram is not a primitive operation of the type
862       --  (which is declared elsewhere in some other scope).
863
864       if Ekind (Desig_Type) = E_Incomplete_Type
865         and then not From_With_Type (Desig_Type)
866         and then Is_Overloadable (Current_Scope)
867       then
868          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
869          Set_Has_Delayed_Freeze (Current_Scope);
870       end if;
871
872       --  Ada 2005: if the designated type is an interface that may contain
873       --  tasks, create a Master entity for the declaration. This must be done
874       --  before expansion of the full declaration, because the declaration may
875       --  include an expression that is an allocator, whose expansion needs the
876       --  proper Master for the created tasks.
877
878       if Nkind (Related_Nod) = N_Object_Declaration
879          and then Expander_Active
880       then
881          if Is_Interface (Desig_Type)
882            and then Is_Limited_Record (Desig_Type)
883          then
884             Build_Class_Wide_Master (Anon_Type);
885
886          --  Similarly, if the type is an anonymous access that designates
887          --  tasks, create a master entity for it in the current context.
888
889          elsif Has_Task (Desig_Type)
890            and then Comes_From_Source (Related_Nod)
891            and then not Restriction_Active (No_Task_Hierarchy)
892          then
893             if not Has_Master_Entity (Current_Scope) then
894                Decl :=
895                  Make_Object_Declaration (Loc,
896                    Defining_Identifier =>
897                      Make_Defining_Identifier (Loc, Name_uMaster),
898                    Constant_Present => True,
899                    Object_Definition =>
900                      New_Reference_To (RTE (RE_Master_Id), Loc),
901                    Expression =>
902                      Make_Explicit_Dereference (Loc,
903                        New_Reference_To (RTE (RE_Current_Master), Loc)));
904
905                Insert_Before (Related_Nod, Decl);
906                Analyze (Decl);
907
908                Set_Master_Id (Anon_Type, Defining_Identifier (Decl));
909                Set_Has_Master_Entity (Current_Scope);
910             else
911                Build_Master_Renaming (Related_Nod, Anon_Type);
912             end if;
913          end if;
914       end if;
915
916       --  For a private component of a protected type, it is imperative that
917       --  the back-end elaborate the type immediately after the protected
918       --  declaration, because this type will be used in the declarations
919       --  created for the component within each protected body, so we must
920       --  create an itype reference for it now.
921
922       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
923          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
924
925       --  Similarly, if the access definition is the return result of a
926       --  function, create an itype reference for it because it will be used
927       --  within the function body. For a regular function that is not a
928       --  compilation unit, insert reference after the declaration. For a
929       --  protected operation, insert it after the enclosing protected type
930       --  declaration. In either case, do not create a reference for a type
931       --  obtained through a limited_with clause, because this would introduce
932       --  semantic dependencies.
933
934       --  Similarly, do not create a reference if the designated type is a
935       --  generic formal, because no use of it will reach the backend.
936
937       elsif Nkind (Related_Nod) = N_Function_Specification
938         and then not From_With_Type (Desig_Type)
939         and then not Is_Generic_Type (Desig_Type)
940       then
941          if Present (Enclosing_Prot_Type) then
942             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
943
944          elsif Is_List_Member (Parent (Related_Nod))
945            and then Nkind (Parent (N)) /= N_Parameter_Specification
946          then
947             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
948          end if;
949
950       --  Finally, create an itype reference for an object declaration of an
951       --  anonymous access type. This is strictly necessary only for deferred
952       --  constants, but in any case will avoid out-of-scope problems in the
953       --  back-end.
954
955       elsif Nkind (Related_Nod) = N_Object_Declaration then
956          Build_Itype_Reference (Anon_Type, Related_Nod);
957       end if;
958
959       return Anon_Type;
960    end Access_Definition;
961
962    -----------------------------------
963    -- Access_Subprogram_Declaration --
964    -----------------------------------
965
966    procedure Access_Subprogram_Declaration
967      (T_Name : Entity_Id;
968       T_Def  : Node_Id)
969    is
970
971       procedure Check_For_Premature_Usage (Def : Node_Id);
972       --  Check that type T_Name is not used, directly or recursively, as a
973       --  parameter or a return type in Def. Def is either a subtype, an
974       --  access_definition, or an access_to_subprogram_definition.
975
976       -------------------------------
977       -- Check_For_Premature_Usage --
978       -------------------------------
979
980       procedure Check_For_Premature_Usage (Def : Node_Id) is
981          Param : Node_Id;
982
983       begin
984          --  Check for a subtype mark
985
986          if Nkind (Def) in N_Has_Etype then
987             if Etype (Def) = T_Name then
988                Error_Msg_N
989                  ("type& cannot be used before end of its declaration", Def);
990             end if;
991
992          --  If this is not a subtype, then this is an access_definition
993
994          elsif Nkind (Def) = N_Access_Definition then
995             if Present (Access_To_Subprogram_Definition (Def)) then
996                Check_For_Premature_Usage
997                  (Access_To_Subprogram_Definition (Def));
998             else
999                Check_For_Premature_Usage (Subtype_Mark (Def));
1000             end if;
1001
1002          --  The only cases left are N_Access_Function_Definition and
1003          --  N_Access_Procedure_Definition.
1004
1005          else
1006             if Present (Parameter_Specifications (Def)) then
1007                Param := First (Parameter_Specifications (Def));
1008                while Present (Param) loop
1009                   Check_For_Premature_Usage (Parameter_Type (Param));
1010                   Param := Next (Param);
1011                end loop;
1012             end if;
1013
1014             if Nkind (Def) = N_Access_Function_Definition then
1015                Check_For_Premature_Usage (Result_Definition (Def));
1016             end if;
1017          end if;
1018       end Check_For_Premature_Usage;
1019
1020       --  Local variables
1021
1022       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1023       Formal     : Entity_Id;
1024       D_Ityp     : Node_Id;
1025       Desig_Type : constant Entity_Id :=
1026                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1027
1028    --  Start of processing for Access_Subprogram_Declaration
1029
1030    begin
1031       --  Associate the Itype node with the inner full-type declaration or
1032       --  subprogram spec or entry body. This is required to handle nested
1033       --  anonymous declarations. For example:
1034
1035       --      procedure P
1036       --       (X : access procedure
1037       --                     (Y : access procedure
1038       --                                   (Z : access T)))
1039
1040       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1041       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1042                                    N_Private_Type_Declaration,
1043                                    N_Private_Extension_Declaration,
1044                                    N_Procedure_Specification,
1045                                    N_Function_Specification,
1046                                    N_Entry_Body)
1047
1048                    or else
1049                  Nkind_In (D_Ityp, N_Object_Declaration,
1050                                    N_Object_Renaming_Declaration,
1051                                    N_Formal_Object_Declaration,
1052                                    N_Formal_Type_Declaration,
1053                                    N_Task_Type_Declaration,
1054                                    N_Protected_Type_Declaration))
1055       loop
1056          D_Ityp := Parent (D_Ityp);
1057          pragma Assert (D_Ityp /= Empty);
1058       end loop;
1059
1060       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1061
1062       if Nkind_In (D_Ityp, N_Procedure_Specification,
1063                            N_Function_Specification)
1064       then
1065          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1066
1067       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1068                               N_Object_Declaration,
1069                               N_Object_Renaming_Declaration,
1070                               N_Formal_Type_Declaration)
1071       then
1072          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1073       end if;
1074
1075       if Nkind (T_Def) = N_Access_Function_Definition then
1076          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1077             declare
1078                Acc : constant Node_Id := Result_Definition (T_Def);
1079
1080             begin
1081                if Present (Access_To_Subprogram_Definition (Acc))
1082                  and then
1083                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1084                then
1085                   Set_Etype
1086                     (Desig_Type,
1087                        Replace_Anonymous_Access_To_Protected_Subprogram
1088                          (T_Def));
1089
1090                else
1091                   Set_Etype
1092                     (Desig_Type,
1093                        Access_Definition (T_Def, Result_Definition (T_Def)));
1094                end if;
1095             end;
1096
1097          else
1098             Analyze (Result_Definition (T_Def));
1099
1100             declare
1101                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1102
1103             begin
1104                --  If a null exclusion is imposed on the result type, then
1105                --  create a null-excluding itype (an access subtype) and use
1106                --  it as the function's Etype.
1107
1108                if Is_Access_Type (Typ)
1109                  and then Null_Exclusion_In_Return_Present (T_Def)
1110                then
1111                   Set_Etype  (Desig_Type,
1112                     Create_Null_Excluding_Itype
1113                       (T           => Typ,
1114                        Related_Nod => T_Def,
1115                        Scope_Id    => Current_Scope));
1116
1117                else
1118                   if From_With_Type (Typ) then
1119
1120                      --  AI05-151: Incomplete types are allowed in all basic
1121                      --  declarations, including access to subprograms.
1122
1123                      if Ada_Version >= Ada_2012 then
1124                         null;
1125
1126                      else
1127                         Error_Msg_NE
1128                          ("illegal use of incomplete type&",
1129                             Result_Definition (T_Def), Typ);
1130                      end if;
1131
1132                   elsif Ekind (Current_Scope) = E_Package
1133                     and then In_Private_Part (Current_Scope)
1134                   then
1135                      if Ekind (Typ) = E_Incomplete_Type then
1136                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1137
1138                      elsif Is_Class_Wide_Type (Typ)
1139                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1140                      then
1141                         Append_Elmt
1142                           (Desig_Type, Private_Dependents (Etype (Typ)));
1143                      end if;
1144                   end if;
1145
1146                   Set_Etype (Desig_Type, Typ);
1147                end if;
1148             end;
1149          end if;
1150
1151          if not (Is_Type (Etype (Desig_Type))) then
1152             Error_Msg_N
1153               ("expect type in function specification",
1154                Result_Definition (T_Def));
1155          end if;
1156
1157       else
1158          Set_Etype (Desig_Type, Standard_Void_Type);
1159       end if;
1160
1161       if Present (Formals) then
1162          Push_Scope (Desig_Type);
1163
1164          --  A bit of a kludge here. These kludges will be removed when Itypes
1165          --  have proper parent pointers to their declarations???
1166
1167          --  Kludge 1) Link defining_identifier of formals. Required by
1168          --  First_Formal to provide its functionality.
1169
1170          declare
1171             F : Node_Id;
1172
1173          begin
1174             F := First (Formals);
1175
1176             --  In ASIS mode, the access_to_subprogram may be analyzed twice,
1177             --  when it is part of an unconstrained type and subtype expansion
1178             --  is disabled. To avoid back-end problems with shared profiles,
1179             --  use previous subprogram type as the designated type.
1180
1181             if ASIS_Mode
1182               and then Present (Scope (Defining_Identifier (F)))
1183             then
1184                Set_Etype                    (T_Name, T_Name);
1185                Init_Size_Align              (T_Name);
1186                Set_Directly_Designated_Type (T_Name,
1187                  Scope (Defining_Identifier (F)));
1188                return;
1189             end if;
1190
1191             while Present (F) loop
1192                if No (Parent (Defining_Identifier (F))) then
1193                   Set_Parent (Defining_Identifier (F), F);
1194                end if;
1195
1196                Next (F);
1197             end loop;
1198          end;
1199
1200          Process_Formals (Formals, Parent (T_Def));
1201
1202          --  Kludge 2) End_Scope requires that the parent pointer be set to
1203          --  something reasonable, but Itypes don't have parent pointers. So
1204          --  we set it and then unset it ???
1205
1206          Set_Parent (Desig_Type, T_Name);
1207          End_Scope;
1208          Set_Parent (Desig_Type, Empty);
1209       end if;
1210
1211       --  Check for premature usage of the type being defined
1212
1213       Check_For_Premature_Usage (T_Def);
1214
1215       --  The return type and/or any parameter type may be incomplete. Mark
1216       --  the subprogram_type as depending on the incomplete type, so that
1217       --  it can be updated when the full type declaration is seen. This
1218       --  only applies to incomplete types declared in some enclosing scope,
1219       --  not to limited views from other packages.
1220
1221       if Present (Formals) then
1222          Formal := First_Formal (Desig_Type);
1223          while Present (Formal) loop
1224             if Ekind (Formal) /= E_In_Parameter
1225               and then Nkind (T_Def) = N_Access_Function_Definition
1226             then
1227                Error_Msg_N ("functions can only have IN parameters", Formal);
1228             end if;
1229
1230             if Ekind (Etype (Formal)) = E_Incomplete_Type
1231               and then In_Open_Scopes (Scope (Etype (Formal)))
1232             then
1233                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1234                Set_Has_Delayed_Freeze (Desig_Type);
1235             end if;
1236
1237             Next_Formal (Formal);
1238          end loop;
1239       end if;
1240
1241       --  If the return type is incomplete, this is legal as long as the
1242       --  type is declared in the current scope and will be completed in
1243       --  it (rather than being part of limited view).
1244
1245       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1246         and then not Has_Delayed_Freeze (Desig_Type)
1247         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1248       then
1249          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1250          Set_Has_Delayed_Freeze (Desig_Type);
1251       end if;
1252
1253       Check_Delayed_Subprogram (Desig_Type);
1254
1255       if Protected_Present (T_Def) then
1256          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1257          Set_Convention (Desig_Type, Convention_Protected);
1258       else
1259          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1260       end if;
1261
1262       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1263
1264       Set_Etype                    (T_Name, T_Name);
1265       Init_Size_Align              (T_Name);
1266       Set_Directly_Designated_Type (T_Name, Desig_Type);
1267
1268       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1269
1270       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1271
1272       Check_Restriction (No_Access_Subprograms, T_Def);
1273    end Access_Subprogram_Declaration;
1274
1275    ----------------------------
1276    -- Access_Type_Declaration --
1277    ----------------------------
1278
1279    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1280       S : constant Node_Id := Subtype_Indication (Def);
1281       P : constant Node_Id := Parent (Def);
1282    begin
1283       --  Check for permissible use of incomplete type
1284
1285       if Nkind (S) /= N_Subtype_Indication then
1286          Analyze (S);
1287
1288          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1289             Set_Directly_Designated_Type (T, Entity (S));
1290          else
1291             Set_Directly_Designated_Type (T,
1292               Process_Subtype (S, P, T, 'P'));
1293          end if;
1294
1295       else
1296          Set_Directly_Designated_Type (T,
1297            Process_Subtype (S, P, T, 'P'));
1298       end if;
1299
1300       if All_Present (Def) or Constant_Present (Def) then
1301          Set_Ekind (T, E_General_Access_Type);
1302       else
1303          Set_Ekind (T, E_Access_Type);
1304       end if;
1305
1306       if Base_Type (Designated_Type (T)) = T then
1307          Error_Msg_N ("access type cannot designate itself", S);
1308
1309       --  In Ada 2005, the type may have a limited view through some unit
1310       --  in its own context, allowing the following circularity that cannot
1311       --  be detected earlier
1312
1313       elsif Is_Class_Wide_Type (Designated_Type (T))
1314         and then Etype (Designated_Type (T)) = T
1315       then
1316          Error_Msg_N
1317            ("access type cannot designate its own classwide type", S);
1318
1319          --  Clean up indication of tagged status to prevent cascaded errors
1320
1321          Set_Is_Tagged_Type (T, False);
1322       end if;
1323
1324       Set_Etype (T, T);
1325
1326       --  If the type has appeared already in a with_type clause, it is
1327       --  frozen and the pointer size is already set. Else, initialize.
1328
1329       if not From_With_Type (T) then
1330          Init_Size_Align (T);
1331       end if;
1332
1333       --  Note that Has_Task is always false, since the access type itself
1334       --  is not a task type. See Einfo for more description on this point.
1335       --  Exactly the same consideration applies to Has_Controlled_Component.
1336
1337       Set_Has_Task (T, False);
1338       Set_Has_Controlled_Component (T, False);
1339
1340       --  Initialize Associated_Final_Chain explicitly to Empty, to avoid
1341       --  problems where an incomplete view of this entity has been previously
1342       --  established by a limited with and an overlaid version of this field
1343       --  (Stored_Constraint) was initialized for the incomplete view.
1344
1345       Set_Associated_Final_Chain (T, Empty);
1346
1347       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1348       --  attributes
1349
1350       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1351       Set_Is_Access_Constant (T, Constant_Present (Def));
1352    end Access_Type_Declaration;
1353
1354    ----------------------------------
1355    -- Add_Interface_Tag_Components --
1356    ----------------------------------
1357
1358    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1359       Loc      : constant Source_Ptr := Sloc (N);
1360       L        : List_Id;
1361       Last_Tag : Node_Id;
1362
1363       procedure Add_Tag (Iface : Entity_Id);
1364       --  Add tag for one of the progenitor interfaces
1365
1366       -------------
1367       -- Add_Tag --
1368       -------------
1369
1370       procedure Add_Tag (Iface : Entity_Id) is
1371          Decl   : Node_Id;
1372          Def    : Node_Id;
1373          Tag    : Entity_Id;
1374          Offset : Entity_Id;
1375
1376       begin
1377          pragma Assert (Is_Tagged_Type (Iface)
1378            and then Is_Interface (Iface));
1379
1380          --  This is a reasonable place to propagate predicates
1381
1382          if Has_Predicates (Iface) then
1383             Set_Has_Predicates (Typ);
1384          end if;
1385
1386          Def :=
1387            Make_Component_Definition (Loc,
1388              Aliased_Present    => True,
1389              Subtype_Indication =>
1390                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1391
1392          Tag := Make_Temporary (Loc, 'V');
1393
1394          Decl :=
1395            Make_Component_Declaration (Loc,
1396              Defining_Identifier  => Tag,
1397              Component_Definition => Def);
1398
1399          Analyze_Component_Declaration (Decl);
1400
1401          Set_Analyzed (Decl);
1402          Set_Ekind               (Tag, E_Component);
1403          Set_Is_Tag              (Tag);
1404          Set_Is_Aliased          (Tag);
1405          Set_Related_Type        (Tag, Iface);
1406          Init_Component_Location (Tag);
1407
1408          pragma Assert (Is_Frozen (Iface));
1409
1410          Set_DT_Entry_Count    (Tag,
1411            DT_Entry_Count (First_Entity (Iface)));
1412
1413          if No (Last_Tag) then
1414             Prepend (Decl, L);
1415          else
1416             Insert_After (Last_Tag, Decl);
1417          end if;
1418
1419          Last_Tag := Decl;
1420
1421          --  If the ancestor has discriminants we need to give special support
1422          --  to store the offset_to_top value of the secondary dispatch tables.
1423          --  For this purpose we add a supplementary component just after the
1424          --  field that contains the tag associated with each secondary DT.
1425
1426          if Typ /= Etype (Typ)
1427            and then Has_Discriminants (Etype (Typ))
1428          then
1429             Def :=
1430               Make_Component_Definition (Loc,
1431                 Subtype_Indication =>
1432                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1433
1434             Offset := Make_Temporary (Loc, 'V');
1435
1436             Decl :=
1437               Make_Component_Declaration (Loc,
1438                 Defining_Identifier  => Offset,
1439                 Component_Definition => Def);
1440
1441             Analyze_Component_Declaration (Decl);
1442
1443             Set_Analyzed (Decl);
1444             Set_Ekind               (Offset, E_Component);
1445             Set_Is_Aliased          (Offset);
1446             Set_Related_Type        (Offset, Iface);
1447             Init_Component_Location (Offset);
1448             Insert_After (Last_Tag, Decl);
1449             Last_Tag := Decl;
1450          end if;
1451       end Add_Tag;
1452
1453       --  Local variables
1454
1455       Elmt : Elmt_Id;
1456       Ext  : Node_Id;
1457       Comp : Node_Id;
1458
1459    --  Start of processing for Add_Interface_Tag_Components
1460
1461    begin
1462       if not RTE_Available (RE_Interface_Tag) then
1463          Error_Msg
1464            ("(Ada 2005) interface types not supported by this run-time!",
1465             Sloc (N));
1466          return;
1467       end if;
1468
1469       if Ekind (Typ) /= E_Record_Type
1470         or else (Is_Concurrent_Record_Type (Typ)
1471                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1472         or else (not Is_Concurrent_Record_Type (Typ)
1473                   and then No (Interfaces (Typ))
1474                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1475       then
1476          return;
1477       end if;
1478
1479       --  Find the current last tag
1480
1481       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1482          Ext := Record_Extension_Part (Type_Definition (N));
1483       else
1484          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1485          Ext := Type_Definition (N);
1486       end if;
1487
1488       Last_Tag := Empty;
1489
1490       if not (Present (Component_List (Ext))) then
1491          Set_Null_Present (Ext, False);
1492          L := New_List;
1493          Set_Component_List (Ext,
1494            Make_Component_List (Loc,
1495              Component_Items => L,
1496              Null_Present => False));
1497       else
1498          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1499             L := Component_Items
1500                    (Component_List
1501                      (Record_Extension_Part
1502                        (Type_Definition (N))));
1503          else
1504             L := Component_Items
1505                    (Component_List
1506                      (Type_Definition (N)));
1507          end if;
1508
1509          --  Find the last tag component
1510
1511          Comp := First (L);
1512          while Present (Comp) loop
1513             if Nkind (Comp) = N_Component_Declaration
1514               and then Is_Tag (Defining_Identifier (Comp))
1515             then
1516                Last_Tag := Comp;
1517             end if;
1518
1519             Next (Comp);
1520          end loop;
1521       end if;
1522
1523       --  At this point L references the list of components and Last_Tag
1524       --  references the current last tag (if any). Now we add the tag
1525       --  corresponding with all the interfaces that are not implemented
1526       --  by the parent.
1527
1528       if Present (Interfaces (Typ)) then
1529          Elmt := First_Elmt (Interfaces (Typ));
1530          while Present (Elmt) loop
1531             Add_Tag (Node (Elmt));
1532             Next_Elmt (Elmt);
1533          end loop;
1534       end if;
1535    end Add_Interface_Tag_Components;
1536
1537    -------------------------------------
1538    -- Add_Internal_Interface_Entities --
1539    -------------------------------------
1540
1541    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1542       Elmt          : Elmt_Id;
1543       Iface         : Entity_Id;
1544       Iface_Elmt    : Elmt_Id;
1545       Iface_Prim    : Entity_Id;
1546       Ifaces_List   : Elist_Id;
1547       New_Subp      : Entity_Id := Empty;
1548       Prim          : Entity_Id;
1549       Restore_Scope : Boolean := False;
1550
1551    begin
1552       pragma Assert (Ada_Version >= Ada_2005
1553         and then Is_Record_Type (Tagged_Type)
1554         and then Is_Tagged_Type (Tagged_Type)
1555         and then Has_Interfaces (Tagged_Type)
1556         and then not Is_Interface (Tagged_Type));
1557
1558       --  Ensure that the internal entities are added to the scope of the type
1559
1560       if Scope (Tagged_Type) /= Current_Scope then
1561          Push_Scope (Scope (Tagged_Type));
1562          Restore_Scope := True;
1563       end if;
1564
1565       Collect_Interfaces (Tagged_Type, Ifaces_List);
1566
1567       Iface_Elmt := First_Elmt (Ifaces_List);
1568       while Present (Iface_Elmt) loop
1569          Iface := Node (Iface_Elmt);
1570
1571          --  Originally we excluded here from this processing interfaces that
1572          --  are parents of Tagged_Type because their primitives are located
1573          --  in the primary dispatch table (and hence no auxiliary internal
1574          --  entities are required to handle secondary dispatch tables in such
1575          --  case). However, these auxiliary entities are also required to
1576          --  handle derivations of interfaces in formals of generics (see
1577          --  Derive_Subprograms).
1578
1579          Elmt := First_Elmt (Primitive_Operations (Iface));
1580          while Present (Elmt) loop
1581             Iface_Prim := Node (Elmt);
1582
1583             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1584                Prim :=
1585                  Find_Primitive_Covering_Interface
1586                    (Tagged_Type => Tagged_Type,
1587                     Iface_Prim  => Iface_Prim);
1588
1589                pragma Assert (Present (Prim));
1590
1591                --  Ada 2012 (AI05-0197): If the name of the covering primitive
1592                --  differs from the name of the interface primitive then it is
1593                --  a private primitive inherited from a parent type. In such
1594                --  case, given that Tagged_Type covers the interface, the
1595                --  inherited private primitive becomes visible. For such
1596                --  purpose we add a new entity that renames the inherited
1597                --  private primitive.
1598
1599                if Chars (Prim) /= Chars (Iface_Prim) then
1600                   pragma Assert (Has_Suffix (Prim, 'P'));
1601                   Derive_Subprogram
1602                     (New_Subp     => New_Subp,
1603                      Parent_Subp  => Iface_Prim,
1604                      Derived_Type => Tagged_Type,
1605                      Parent_Type  => Iface);
1606                   Set_Alias (New_Subp, Prim);
1607                   Set_Is_Abstract_Subprogram
1608                     (New_Subp, Is_Abstract_Subprogram (Prim));
1609                end if;
1610
1611                Derive_Subprogram
1612                  (New_Subp     => New_Subp,
1613                   Parent_Subp  => Iface_Prim,
1614                   Derived_Type => Tagged_Type,
1615                   Parent_Type  => Iface);
1616
1617                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1618                --  associated with interface types. These entities are
1619                --  only registered in the list of primitives of its
1620                --  corresponding tagged type because they are only used
1621                --  to fill the contents of the secondary dispatch tables.
1622                --  Therefore they are removed from the homonym chains.
1623
1624                Set_Is_Hidden (New_Subp);
1625                Set_Is_Internal (New_Subp);
1626                Set_Alias (New_Subp, Prim);
1627                Set_Is_Abstract_Subprogram
1628                  (New_Subp, Is_Abstract_Subprogram (Prim));
1629                Set_Interface_Alias (New_Subp, Iface_Prim);
1630
1631                --  Internal entities associated with interface types are
1632                --  only registered in the list of primitives of the tagged
1633                --  type. They are only used to fill the contents of the
1634                --  secondary dispatch tables. Therefore they are not needed
1635                --  in the homonym chains.
1636
1637                Remove_Homonym (New_Subp);
1638
1639                --  Hidden entities associated with interfaces must have set
1640                --  the Has_Delay_Freeze attribute to ensure that, in case of
1641                --  locally defined tagged types (or compiling with static
1642                --  dispatch tables generation disabled) the corresponding
1643                --  entry of the secondary dispatch table is filled when
1644                --  such an entity is frozen.
1645
1646                Set_Has_Delayed_Freeze (New_Subp);
1647             end if;
1648
1649             Next_Elmt (Elmt);
1650          end loop;
1651
1652          Next_Elmt (Iface_Elmt);
1653       end loop;
1654
1655       if Restore_Scope then
1656          Pop_Scope;
1657       end if;
1658    end Add_Internal_Interface_Entities;
1659
1660    -----------------------------------
1661    -- Analyze_Component_Declaration --
1662    -----------------------------------
1663
1664    procedure Analyze_Component_Declaration (N : Node_Id) is
1665       Id : constant Entity_Id := Defining_Identifier (N);
1666       E  : constant Node_Id   := Expression (N);
1667       T  : Entity_Id;
1668       P  : Entity_Id;
1669
1670       function Contains_POC (Constr : Node_Id) return Boolean;
1671       --  Determines whether a constraint uses the discriminant of a record
1672       --  type thus becoming a per-object constraint (POC).
1673
1674       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1675       --  Typ is the type of the current component, check whether this type is
1676       --  a limited type. Used to validate declaration against that of
1677       --  enclosing record.
1678
1679       ------------------
1680       -- Contains_POC --
1681       ------------------
1682
1683       function Contains_POC (Constr : Node_Id) return Boolean is
1684       begin
1685          --  Prevent cascaded errors
1686
1687          if Error_Posted (Constr) then
1688             return False;
1689          end if;
1690
1691          case Nkind (Constr) is
1692             when N_Attribute_Reference =>
1693                return
1694                  Attribute_Name (Constr) = Name_Access
1695                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1696
1697             when N_Discriminant_Association =>
1698                return Denotes_Discriminant (Expression (Constr));
1699
1700             when N_Identifier =>
1701                return Denotes_Discriminant (Constr);
1702
1703             when N_Index_Or_Discriminant_Constraint =>
1704                declare
1705                   IDC : Node_Id;
1706
1707                begin
1708                   IDC := First (Constraints (Constr));
1709                   while Present (IDC) loop
1710
1711                      --  One per-object constraint is sufficient
1712
1713                      if Contains_POC (IDC) then
1714                         return True;
1715                      end if;
1716
1717                      Next (IDC);
1718                   end loop;
1719
1720                   return False;
1721                end;
1722
1723             when N_Range =>
1724                return Denotes_Discriminant (Low_Bound (Constr))
1725                         or else
1726                       Denotes_Discriminant (High_Bound (Constr));
1727
1728             when N_Range_Constraint =>
1729                return Denotes_Discriminant (Range_Expression (Constr));
1730
1731             when others =>
1732                return False;
1733
1734          end case;
1735       end Contains_POC;
1736
1737       ----------------------
1738       -- Is_Known_Limited --
1739       ----------------------
1740
1741       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1742          P : constant Entity_Id := Etype (Typ);
1743          R : constant Entity_Id := Root_Type (Typ);
1744
1745       begin
1746          if Is_Limited_Record (Typ) then
1747             return True;
1748
1749          --  If the root type is limited (and not a limited interface)
1750          --  so is the current type
1751
1752          elsif Is_Limited_Record (R)
1753            and then
1754              (not Is_Interface (R)
1755                or else not Is_Limited_Interface (R))
1756          then
1757             return True;
1758
1759          --  Else the type may have a limited interface progenitor, but a
1760          --  limited record parent.
1761
1762          elsif R /= P
1763            and then Is_Limited_Record (P)
1764          then
1765             return True;
1766
1767          else
1768             return False;
1769          end if;
1770       end Is_Known_Limited;
1771
1772    --  Start of processing for Analyze_Component_Declaration
1773
1774    begin
1775       Generate_Definition (Id);
1776       Enter_Name (Id);
1777
1778       if Present (Subtype_Indication (Component_Definition (N))) then
1779          T := Find_Type_Of_Object
1780                 (Subtype_Indication (Component_Definition (N)), N);
1781
1782       --  Ada 2005 (AI-230): Access Definition case
1783
1784       else
1785          pragma Assert (Present
1786                           (Access_Definition (Component_Definition (N))));
1787
1788          T := Access_Definition
1789                 (Related_Nod => N,
1790                  N => Access_Definition (Component_Definition (N)));
1791          Set_Is_Local_Anonymous_Access (T);
1792
1793          --  Ada 2005 (AI-254)
1794
1795          if Present (Access_To_Subprogram_Definition
1796                       (Access_Definition (Component_Definition (N))))
1797            and then Protected_Present (Access_To_Subprogram_Definition
1798                                         (Access_Definition
1799                                           (Component_Definition (N))))
1800          then
1801             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1802          end if;
1803       end if;
1804
1805       --  If the subtype is a constrained subtype of the enclosing record,
1806       --  (which must have a partial view) the back-end does not properly
1807       --  handle the recursion. Rewrite the component declaration with an
1808       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1809       --  the tree directly because side effects have already been removed from
1810       --  discriminant constraints.
1811
1812       if Ekind (T) = E_Access_Subtype
1813         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1814         and then Comes_From_Source (T)
1815         and then Nkind (Parent (T)) = N_Subtype_Declaration
1816         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1817       then
1818          Rewrite
1819            (Subtype_Indication (Component_Definition (N)),
1820              New_Copy_Tree (Subtype_Indication (Parent (T))));
1821          T := Find_Type_Of_Object
1822                  (Subtype_Indication (Component_Definition (N)), N);
1823       end if;
1824
1825       --  If the component declaration includes a default expression, then we
1826       --  check that the component is not of a limited type (RM 3.7(5)),
1827       --  and do the special preanalysis of the expression (see section on
1828       --  "Handling of Default and Per-Object Expressions" in the spec of
1829       --  package Sem).
1830
1831       if Present (E) then
1832          Preanalyze_Spec_Expression (E, T);
1833          Check_Initialization (T, E);
1834
1835          if Ada_Version >= Ada_2005
1836            and then Ekind (T) = E_Anonymous_Access_Type
1837            and then Etype (E) /= Any_Type
1838          then
1839             --  Check RM 3.9.2(9): "if the expected type for an expression is
1840             --  an anonymous access-to-specific tagged type, then the object
1841             --  designated by the expression shall not be dynamically tagged
1842             --  unless it is a controlling operand in a call on a dispatching
1843             --  operation"
1844
1845             if Is_Tagged_Type (Directly_Designated_Type (T))
1846               and then
1847                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1848               and then
1849                 Ekind (Directly_Designated_Type (Etype (E))) =
1850                   E_Class_Wide_Type
1851             then
1852                Error_Msg_N
1853                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1854             end if;
1855
1856             --  (Ada 2005: AI-230): Accessibility check for anonymous
1857             --  components
1858
1859             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1860                Error_Msg_N
1861                  ("expression has deeper access level than component " &
1862                   "(RM 3.10.2 (12.2))", E);
1863             end if;
1864
1865             --  The initialization expression is a reference to an access
1866             --  discriminant. The type of the discriminant is always deeper
1867             --  than any access type.
1868
1869             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1870               and then Is_Entity_Name (E)
1871               and then Ekind (Entity (E)) = E_In_Parameter
1872               and then Present (Discriminal_Link (Entity (E)))
1873             then
1874                Error_Msg_N
1875                  ("discriminant has deeper accessibility level than target",
1876                   E);
1877             end if;
1878          end if;
1879       end if;
1880
1881       --  The parent type may be a private view with unknown discriminants,
1882       --  and thus unconstrained. Regular components must be constrained.
1883
1884       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1885          if Is_Class_Wide_Type (T) then
1886             Error_Msg_N
1887                ("class-wide subtype with unknown discriminants" &
1888                  " in component declaration",
1889                  Subtype_Indication (Component_Definition (N)));
1890          else
1891             Error_Msg_N
1892               ("unconstrained subtype in component declaration",
1893                Subtype_Indication (Component_Definition (N)));
1894          end if;
1895
1896       --  Components cannot be abstract, except for the special case of
1897       --  the _Parent field (case of extending an abstract tagged type)
1898
1899       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1900          Error_Msg_N ("type of a component cannot be abstract", N);
1901       end if;
1902
1903       Set_Etype (Id, T);
1904       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1905
1906       --  The component declaration may have a per-object constraint, set
1907       --  the appropriate flag in the defining identifier of the subtype.
1908
1909       if Present (Subtype_Indication (Component_Definition (N))) then
1910          declare
1911             Sindic : constant Node_Id :=
1912                        Subtype_Indication (Component_Definition (N));
1913          begin
1914             if Nkind (Sindic) = N_Subtype_Indication
1915               and then Present (Constraint (Sindic))
1916               and then Contains_POC (Constraint (Sindic))
1917             then
1918                Set_Has_Per_Object_Constraint (Id);
1919             end if;
1920          end;
1921       end if;
1922
1923       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1924       --  out some static checks.
1925
1926       if Ada_Version >= Ada_2005
1927         and then Can_Never_Be_Null (T)
1928       then
1929          Null_Exclusion_Static_Checks (N);
1930       end if;
1931
1932       --  If this component is private (or depends on a private type), flag the
1933       --  record type to indicate that some operations are not available.
1934
1935       P := Private_Component (T);
1936
1937       if Present (P) then
1938
1939          --  Check for circular definitions
1940
1941          if P = Any_Type then
1942             Set_Etype (Id, Any_Type);
1943
1944          --  There is a gap in the visibility of operations only if the
1945          --  component type is not defined in the scope of the record type.
1946
1947          elsif Scope (P) = Scope (Current_Scope) then
1948             null;
1949
1950          elsif Is_Limited_Type (P) then
1951             Set_Is_Limited_Composite (Current_Scope);
1952
1953          else
1954             Set_Is_Private_Composite (Current_Scope);
1955          end if;
1956       end if;
1957
1958       if P /= Any_Type
1959         and then Is_Limited_Type (T)
1960         and then Chars (Id) /= Name_uParent
1961         and then Is_Tagged_Type (Current_Scope)
1962       then
1963          if Is_Derived_Type (Current_Scope)
1964            and then not Is_Known_Limited (Current_Scope)
1965          then
1966             Error_Msg_N
1967               ("extension of nonlimited type cannot have limited components",
1968                N);
1969
1970             if Is_Interface (Root_Type (Current_Scope)) then
1971                Error_Msg_N
1972                  ("\limitedness is not inherited from limited interface", N);
1973                Error_Msg_N ("\add LIMITED to type indication", N);
1974             end if;
1975
1976             Explain_Limited_Type (T, N);
1977             Set_Etype (Id, Any_Type);
1978             Set_Is_Limited_Composite (Current_Scope, False);
1979
1980          elsif not Is_Derived_Type (Current_Scope)
1981            and then not Is_Limited_Record (Current_Scope)
1982            and then not Is_Concurrent_Type (Current_Scope)
1983          then
1984             Error_Msg_N
1985               ("nonlimited tagged type cannot have limited components", N);
1986             Explain_Limited_Type (T, N);
1987             Set_Etype (Id, Any_Type);
1988             Set_Is_Limited_Composite (Current_Scope, False);
1989          end if;
1990       end if;
1991
1992       Set_Original_Record_Component (Id, Id);
1993       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
1994    end Analyze_Component_Declaration;
1995
1996    --------------------------
1997    -- Analyze_Declarations --
1998    --------------------------
1999
2000    procedure Analyze_Declarations (L : List_Id) is
2001       D           : Node_Id;
2002       Freeze_From : Entity_Id := Empty;
2003       Next_Node   : Node_Id;
2004
2005       procedure Adjust_D;
2006       --  Adjust D not to include implicit label declarations, since these
2007       --  have strange Sloc values that result in elaboration check problems.
2008       --  (They have the sloc of the label as found in the source, and that
2009       --  is ahead of the current declarative part).
2010
2011       --------------
2012       -- Adjust_D --
2013       --------------
2014
2015       procedure Adjust_D is
2016       begin
2017          while Present (Prev (D))
2018            and then Nkind (D) = N_Implicit_Label_Declaration
2019          loop
2020             Prev (D);
2021          end loop;
2022       end Adjust_D;
2023
2024    --  Start of processing for Analyze_Declarations
2025
2026    begin
2027       D := First (L);
2028       while Present (D) loop
2029
2030          --  Package specification cannot contain a package declaration in
2031          --  SPARK or ALFA
2032
2033          if Formal_Verification_Mode
2034            and then Nkind (D) = N_Package_Declaration
2035            and then Nkind (Parent (L)) = N_Package_Specification
2036          then
2037             Formal_Error_Msg_N ("package specification cannot contain "
2038                                 & "a package declaration", D);
2039          end if;
2040
2041          --  Complete analysis of declaration
2042
2043          Analyze (D);
2044          Next_Node := Next (D);
2045
2046          if No (Freeze_From) then
2047             Freeze_From := First_Entity (Current_Scope);
2048          end if;
2049
2050          --  At the end of a declarative part, freeze remaining entities
2051          --  declared in it. The end of the visible declarations of package
2052          --  specification is not the end of a declarative part if private
2053          --  declarations are present. The end of a package declaration is a
2054          --  freezing point only if it a library package. A task definition or
2055          --  protected type definition is not a freeze point either. Finally,
2056          --  we do not freeze entities in generic scopes, because there is no
2057          --  code generated for them and freeze nodes will be generated for
2058          --  the instance.
2059
2060          --  The end of a package instantiation is not a freeze point, but
2061          --  for now we make it one, because the generic body is inserted
2062          --  (currently) immediately after. Generic instantiations will not
2063          --  be a freeze point once delayed freezing of bodies is implemented.
2064          --  (This is needed in any case for early instantiations ???).
2065
2066          if No (Next_Node) then
2067             if Nkind_In (Parent (L), N_Component_List,
2068                                      N_Task_Definition,
2069                                      N_Protected_Definition)
2070             then
2071                null;
2072
2073             elsif Nkind (Parent (L)) /= N_Package_Specification then
2074                if Nkind (Parent (L)) = N_Package_Body then
2075                   Freeze_From := First_Entity (Current_Scope);
2076                end if;
2077
2078                Adjust_D;
2079                Freeze_All (Freeze_From, D);
2080                Freeze_From := Last_Entity (Current_Scope);
2081
2082             elsif Scope (Current_Scope) /= Standard_Standard
2083               and then not Is_Child_Unit (Current_Scope)
2084               and then No (Generic_Parent (Parent (L)))
2085             then
2086                null;
2087
2088             elsif L /= Visible_Declarations (Parent (L))
2089                or else No (Private_Declarations (Parent (L)))
2090                or else Is_Empty_List (Private_Declarations (Parent (L)))
2091             then
2092                Adjust_D;
2093                Freeze_All (Freeze_From, D);
2094                Freeze_From := Last_Entity (Current_Scope);
2095             end if;
2096
2097          --  If next node is a body then freeze all types before the body.
2098          --  An exception occurs for some expander-generated bodies. If these
2099          --  are generated at places where in general language rules would not
2100          --  allow a freeze point, then we assume that the expander has
2101          --  explicitly checked that all required types are properly frozen,
2102          --  and we do not cause general freezing here. This special circuit
2103          --  is used when the encountered body is marked as having already
2104          --  been analyzed.
2105
2106          --  In all other cases (bodies that come from source, and expander
2107          --  generated bodies that have not been analyzed yet), freeze all
2108          --  types now. Note that in the latter case, the expander must take
2109          --  care to attach the bodies at a proper place in the tree so as to
2110          --  not cause unwanted freezing at that point.
2111
2112          elsif not Analyzed (Next_Node)
2113            and then (Nkind_In (Next_Node, N_Subprogram_Body,
2114                                           N_Entry_Body,
2115                                           N_Package_Body,
2116                                           N_Protected_Body,
2117                                           N_Task_Body)
2118                        or else
2119                      Nkind (Next_Node) in N_Body_Stub)
2120          then
2121             Adjust_D;
2122             Freeze_All (Freeze_From, D);
2123             Freeze_From := Last_Entity (Current_Scope);
2124          end if;
2125
2126          D := Next_Node;
2127       end loop;
2128
2129       --  One more thing to do, we need to scan the declarations to check
2130       --  for any precondition/postcondition pragmas (Pre/Post aspects have
2131       --  by this stage been converted into corresponding pragmas). It is
2132       --  at this point that we analyze the expressions in such pragmas,
2133       --  to implement the delayed visibility requirement.
2134
2135       declare
2136          Decl : Node_Id;
2137          Spec : Node_Id;
2138          Sent : Entity_Id;
2139          Prag : Node_Id;
2140
2141       begin
2142          Decl := First (L);
2143          while Present (Decl) loop
2144             if Nkind (Original_Node (Decl)) = N_Subprogram_Declaration then
2145                Spec := Specification (Original_Node (Decl));
2146                Sent := Defining_Unit_Name (Spec);
2147                Prag := Spec_PPC_List (Sent);
2148                while Present (Prag) loop
2149                   Analyze_PPC_In_Decl_Part (Prag, Sent);
2150                   Prag := Next_Pragma (Prag);
2151                end loop;
2152             end if;
2153
2154             Next (Decl);
2155          end loop;
2156       end;
2157    end Analyze_Declarations;
2158
2159    -----------------------------------
2160    -- Analyze_Full_Type_Declaration --
2161    -----------------------------------
2162
2163    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2164       Def    : constant Node_Id   := Type_Definition (N);
2165       Def_Id : constant Entity_Id := Defining_Identifier (N);
2166       T      : Entity_Id;
2167       Prev   : Entity_Id;
2168
2169       Is_Remote : constant Boolean :=
2170                     (Is_Remote_Types (Current_Scope)
2171                        or else Is_Remote_Call_Interface (Current_Scope))
2172                     and then not (In_Private_Part (Current_Scope)
2173                                     or else In_Package_Body (Current_Scope));
2174
2175       procedure Check_Ops_From_Incomplete_Type;
2176       --  If there is a tagged incomplete partial view of the type, transfer
2177       --  its operations to the full view, and indicate that the type of the
2178       --  controlling parameter (s) is this full view.
2179
2180       ------------------------------------
2181       -- Check_Ops_From_Incomplete_Type --
2182       ------------------------------------
2183
2184       procedure Check_Ops_From_Incomplete_Type is
2185          Elmt   : Elmt_Id;
2186          Formal : Entity_Id;
2187          Op     : Entity_Id;
2188
2189       begin
2190          if Prev /= T
2191            and then Ekind (Prev) = E_Incomplete_Type
2192            and then Is_Tagged_Type (Prev)
2193            and then Is_Tagged_Type (T)
2194          then
2195             Elmt := First_Elmt (Primitive_Operations (Prev));
2196             while Present (Elmt) loop
2197                Op := Node (Elmt);
2198                Prepend_Elmt (Op, Primitive_Operations (T));
2199
2200                Formal := First_Formal (Op);
2201                while Present (Formal) loop
2202                   if Etype (Formal) = Prev then
2203                      Set_Etype (Formal, T);
2204                   end if;
2205
2206                   Next_Formal (Formal);
2207                end loop;
2208
2209                if Etype (Op) = Prev then
2210                   Set_Etype (Op, T);
2211                end if;
2212
2213                Next_Elmt (Elmt);
2214             end loop;
2215          end if;
2216       end Check_Ops_From_Incomplete_Type;
2217
2218    --  Start of processing for Analyze_Full_Type_Declaration
2219
2220    begin
2221       Prev := Find_Type_Name (N);
2222
2223       --  The full view, if present, now points to the current type
2224
2225       --  Ada 2005 (AI-50217): If the type was previously decorated when
2226       --  imported through a LIMITED WITH clause, it appears as incomplete
2227       --  but has no full view.
2228
2229       if Ekind (Prev) = E_Incomplete_Type
2230         and then Present (Full_View (Prev))
2231       then
2232          T := Full_View (Prev);
2233       else
2234          T := Prev;
2235       end if;
2236
2237       Set_Is_Pure (T, Is_Pure (Current_Scope));
2238
2239       --  We set the flag Is_First_Subtype here. It is needed to set the
2240       --  corresponding flag for the Implicit class-wide-type created
2241       --  during tagged types processing.
2242
2243       Set_Is_First_Subtype (T, True);
2244
2245       --  Only composite types other than array types are allowed to have
2246       --  discriminants.
2247
2248       case Nkind (Def) is
2249
2250          --  For derived types, the rule will be checked once we've figured
2251          --  out the parent type.
2252
2253          when N_Derived_Type_Definition =>
2254             null;
2255
2256          --  For record types, discriminants are allowed
2257
2258          when N_Record_Definition =>
2259             null;
2260
2261          when others =>
2262             if Present (Discriminant_Specifications (N)) then
2263                Error_Msg_N
2264                  ("elementary or array type cannot have discriminants",
2265                   Defining_Identifier
2266                   (First (Discriminant_Specifications (N))));
2267             end if;
2268       end case;
2269
2270       --  Elaborate the type definition according to kind, and generate
2271       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2272       --  already done (this happens during the reanalysis that follows a call
2273       --  to the high level optimizer).
2274
2275       if not Analyzed (T) then
2276          Set_Analyzed (T);
2277
2278          case Nkind (Def) is
2279
2280             when N_Access_To_Subprogram_Definition =>
2281                Access_Subprogram_Declaration (T, Def);
2282
2283                --  If this is a remote access to subprogram, we must create the
2284                --  equivalent fat pointer type, and related subprograms.
2285
2286                if Is_Remote then
2287                   Process_Remote_AST_Declaration (N);
2288                end if;
2289
2290                --  Validate categorization rule against access type declaration
2291                --  usually a violation in Pure unit, Shared_Passive unit.
2292
2293                Validate_Access_Type_Declaration (T, N);
2294
2295             when N_Access_To_Object_Definition =>
2296                Access_Type_Declaration (T, Def);
2297
2298                --  Validate categorization rule against access type declaration
2299                --  usually a violation in Pure unit, Shared_Passive unit.
2300
2301                Validate_Access_Type_Declaration (T, N);
2302
2303                --  If we are in a Remote_Call_Interface package and define a
2304                --  RACW, then calling stubs and specific stream attributes
2305                --  must be added.
2306
2307                if Is_Remote
2308                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2309                then
2310                   Add_RACW_Features (Def_Id);
2311                end if;
2312
2313                --  Set no strict aliasing flag if config pragma seen
2314
2315                if Opt.No_Strict_Aliasing then
2316                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
2317                end if;
2318
2319             when N_Array_Type_Definition =>
2320                Array_Type_Declaration (T, Def);
2321
2322             when N_Derived_Type_Definition =>
2323                Derived_Type_Declaration (T, N, T /= Def_Id);
2324
2325             when N_Enumeration_Type_Definition =>
2326                Enumeration_Type_Declaration (T, Def);
2327
2328             when N_Floating_Point_Definition =>
2329                Floating_Point_Type_Declaration (T, Def);
2330
2331             when N_Decimal_Fixed_Point_Definition =>
2332                Decimal_Fixed_Point_Type_Declaration (T, Def);
2333
2334             when N_Ordinary_Fixed_Point_Definition =>
2335                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2336
2337             when N_Signed_Integer_Type_Definition =>
2338                Signed_Integer_Type_Declaration (T, Def);
2339
2340             when N_Modular_Type_Definition =>
2341                Modular_Type_Declaration (T, Def);
2342
2343             when N_Record_Definition =>
2344                Record_Type_Declaration (T, N, Prev);
2345
2346             --  If declaration has a parse error, nothing to elaborate.
2347
2348             when N_Error =>
2349                null;
2350
2351             when others =>
2352                raise Program_Error;
2353
2354          end case;
2355       end if;
2356
2357       if Etype (T) = Any_Type then
2358          return;
2359       end if;
2360
2361       if Formal_Verification_Mode then
2362
2363          --  Controlled type is not allowed in SPARK and ALFA
2364
2365          if Is_Visibly_Controlled (T) then
2366             Formal_Error_Msg_N ("controlled type is not allowed", N);
2367          end if;
2368
2369          --  Discriminant type is not allowed in SPARK and ALFA
2370
2371          if Present (Discriminant_Specifications (N)) then
2372             Formal_Error_Msg_N ("discriminant type is not allowed", N);
2373          end if;
2374       end if;
2375
2376       --  Some common processing for all types
2377
2378       Set_Depends_On_Private (T, Has_Private_Component (T));
2379       Check_Ops_From_Incomplete_Type;
2380
2381       --  Both the declared entity, and its anonymous base type if one
2382       --  was created, need freeze nodes allocated.
2383
2384       declare
2385          B : constant Entity_Id := Base_Type (T);
2386
2387       begin
2388          --  In the case where the base type differs from the first subtype, we
2389          --  pre-allocate a freeze node, and set the proper link to the first
2390          --  subtype. Freeze_Entity will use this preallocated freeze node when
2391          --  it freezes the entity.
2392
2393          --  This does not apply if the base type is a generic type, whose
2394          --  declaration is independent of the current derived definition.
2395
2396          if B /= T and then not Is_Generic_Type (B) then
2397             Ensure_Freeze_Node (B);
2398             Set_First_Subtype_Link (Freeze_Node (B), T);
2399          end if;
2400
2401          --  A type that is imported through a limited_with clause cannot
2402          --  generate any code, and thus need not be frozen. However, an access
2403          --  type with an imported designated type needs a finalization list,
2404          --  which may be referenced in some other package that has non-limited
2405          --  visibility on the designated type. Thus we must create the
2406          --  finalization list at the point the access type is frozen, to
2407          --  prevent unsatisfied references at link time.
2408
2409          if not From_With_Type (T) or else Is_Access_Type (T) then
2410             Set_Has_Delayed_Freeze (T);
2411          end if;
2412       end;
2413
2414       --  Case where T is the full declaration of some private type which has
2415       --  been swapped in Defining_Identifier (N).
2416
2417       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2418          Process_Full_View (N, T, Def_Id);
2419
2420          --  Record the reference. The form of this is a little strange, since
2421          --  the full declaration has been swapped in. So the first parameter
2422          --  here represents the entity to which a reference is made which is
2423          --  the "real" entity, i.e. the one swapped in, and the second
2424          --  parameter provides the reference location.
2425
2426          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2427          --  since we don't want a complaint about the full type being an
2428          --  unwanted reference to the private type
2429
2430          declare
2431             B : constant Boolean := Has_Pragma_Unreferenced (T);
2432          begin
2433             Set_Has_Pragma_Unreferenced (T, False);
2434             Generate_Reference (T, T, 'c');
2435             Set_Has_Pragma_Unreferenced (T, B);
2436          end;
2437
2438          Set_Completion_Referenced (Def_Id);
2439
2440       --  For completion of incomplete type, process incomplete dependents
2441       --  and always mark the full type as referenced (it is the incomplete
2442       --  type that we get for any real reference).
2443
2444       elsif Ekind (Prev) = E_Incomplete_Type then
2445          Process_Incomplete_Dependents (N, T, Prev);
2446          Generate_Reference (Prev, Def_Id, 'c');
2447          Set_Completion_Referenced (Def_Id);
2448
2449       --  If not private type or incomplete type completion, this is a real
2450       --  definition of a new entity, so record it.
2451
2452       else
2453          Generate_Definition (Def_Id);
2454       end if;
2455
2456       if Chars (Scope (Def_Id)) = Name_System
2457         and then Chars (Def_Id) = Name_Address
2458         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2459       then
2460          Set_Is_Descendent_Of_Address (Def_Id);
2461          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2462          Set_Is_Descendent_Of_Address (Prev);
2463       end if;
2464
2465       Set_Optimize_Alignment_Flags (Def_Id);
2466       Check_Eliminated (Def_Id);
2467
2468       Analyze_Aspect_Specifications (N, Def_Id, Aspect_Specifications (N));
2469    end Analyze_Full_Type_Declaration;
2470
2471    ----------------------------------
2472    -- Analyze_Incomplete_Type_Decl --
2473    ----------------------------------
2474
2475    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2476       F : constant Boolean := Is_Pure (Current_Scope);
2477       T : Entity_Id;
2478
2479    begin
2480       Generate_Definition (Defining_Identifier (N));
2481
2482       --  Process an incomplete declaration. The identifier must not have been
2483       --  declared already in the scope. However, an incomplete declaration may
2484       --  appear in the private part of a package, for a private type that has
2485       --  already been declared.
2486
2487       --  In this case, the discriminants (if any) must match
2488
2489       T := Find_Type_Name (N);
2490
2491       Set_Ekind (T, E_Incomplete_Type);
2492       Init_Size_Align (T);
2493       Set_Is_First_Subtype (T, True);
2494       Set_Etype (T, T);
2495
2496       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2497       --  incomplete types.
2498
2499       if Tagged_Present (N) then
2500          Set_Is_Tagged_Type (T);
2501          Make_Class_Wide_Type (T);
2502          Set_Direct_Primitive_Operations (T, New_Elmt_List);
2503       end if;
2504
2505       Push_Scope (T);
2506
2507       Set_Stored_Constraint (T, No_Elist);
2508
2509       if Present (Discriminant_Specifications (N)) then
2510          Process_Discriminants (N);
2511       end if;
2512
2513       End_Scope;
2514
2515       --  If the type has discriminants, non-trivial subtypes may be
2516       --  declared before the full view of the type. The full views of those
2517       --  subtypes will be built after the full view of the type.
2518
2519       Set_Private_Dependents (T, New_Elmt_List);
2520       Set_Is_Pure (T, F);
2521    end Analyze_Incomplete_Type_Decl;
2522
2523    -----------------------------------
2524    -- Analyze_Interface_Declaration --
2525    -----------------------------------
2526
2527    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2528       CW : constant Entity_Id := Class_Wide_Type (T);
2529
2530    begin
2531       Set_Is_Tagged_Type (T);
2532
2533       Set_Is_Limited_Record (T, Limited_Present (Def)
2534                                   or else Task_Present (Def)
2535                                   or else Protected_Present (Def)
2536                                   or else Synchronized_Present (Def));
2537
2538       --  Type is abstract if full declaration carries keyword, or if previous
2539       --  partial view did.
2540
2541       Set_Is_Abstract_Type (T);
2542       Set_Is_Interface (T);
2543
2544       --  Type is a limited interface if it includes the keyword limited, task,
2545       --  protected, or synchronized.
2546
2547       Set_Is_Limited_Interface
2548         (T, Limited_Present (Def)
2549               or else Protected_Present (Def)
2550               or else Synchronized_Present (Def)
2551               or else Task_Present (Def));
2552
2553       Set_Interfaces (T, New_Elmt_List);
2554       Set_Direct_Primitive_Operations (T, New_Elmt_List);
2555
2556       --  Complete the decoration of the class-wide entity if it was already
2557       --  built (i.e. during the creation of the limited view)
2558
2559       if Present (CW) then
2560          Set_Is_Interface (CW);
2561          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2562       end if;
2563
2564       --  Check runtime support for synchronized interfaces
2565
2566       if VM_Target = No_VM
2567         and then (Is_Task_Interface (T)
2568                     or else Is_Protected_Interface (T)
2569                     or else Is_Synchronized_Interface (T))
2570         and then not RTE_Available (RE_Select_Specific_Data)
2571       then
2572          Error_Msg_CRT ("synchronized interfaces", T);
2573       end if;
2574    end Analyze_Interface_Declaration;
2575
2576    -----------------------------
2577    -- Analyze_Itype_Reference --
2578    -----------------------------
2579
2580    --  Nothing to do. This node is placed in the tree only for the benefit of
2581    --  back end processing, and has no effect on the semantic processing.
2582
2583    procedure Analyze_Itype_Reference (N : Node_Id) is
2584    begin
2585       pragma Assert (Is_Itype (Itype (N)));
2586       null;
2587    end Analyze_Itype_Reference;
2588
2589    --------------------------------
2590    -- Analyze_Number_Declaration --
2591    --------------------------------
2592
2593    procedure Analyze_Number_Declaration (N : Node_Id) is
2594       Id    : constant Entity_Id := Defining_Identifier (N);
2595       E     : constant Node_Id   := Expression (N);
2596       T     : Entity_Id;
2597       Index : Interp_Index;
2598       It    : Interp;
2599
2600    begin
2601       Generate_Definition (Id);
2602       Enter_Name (Id);
2603
2604       --  This is an optimization of a common case of an integer literal
2605
2606       if Nkind (E) = N_Integer_Literal then
2607          Set_Is_Static_Expression (E, True);
2608          Set_Etype                (E, Universal_Integer);
2609
2610          Set_Etype     (Id, Universal_Integer);
2611          Set_Ekind     (Id, E_Named_Integer);
2612          Set_Is_Frozen (Id, True);
2613          return;
2614       end if;
2615
2616       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2617
2618       --  Process expression, replacing error by integer zero, to avoid
2619       --  cascaded errors or aborts further along in the processing
2620
2621       --  Replace Error by integer zero, which seems least likely to
2622       --  cause cascaded errors.
2623
2624       if E = Error then
2625          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2626          Set_Error_Posted (E);
2627       end if;
2628
2629       Analyze (E);
2630
2631       --  Verify that the expression is static and numeric. If
2632       --  the expression is overloaded, we apply the preference
2633       --  rule that favors root numeric types.
2634
2635       if not Is_Overloaded (E) then
2636          T := Etype (E);
2637
2638       else
2639          T := Any_Type;
2640
2641          Get_First_Interp (E, Index, It);
2642          while Present (It.Typ) loop
2643             if (Is_Integer_Type (It.Typ)
2644                  or else Is_Real_Type (It.Typ))
2645               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2646             then
2647                if T = Any_Type then
2648                   T := It.Typ;
2649
2650                elsif It.Typ = Universal_Real
2651                  or else It.Typ = Universal_Integer
2652                then
2653                   --  Choose universal interpretation over any other
2654
2655                   T := It.Typ;
2656                   exit;
2657                end if;
2658             end if;
2659
2660             Get_Next_Interp (Index, It);
2661          end loop;
2662       end if;
2663
2664       if Is_Integer_Type (T)  then
2665          Resolve (E, T);
2666          Set_Etype (Id, Universal_Integer);
2667          Set_Ekind (Id, E_Named_Integer);
2668
2669       elsif Is_Real_Type (T) then
2670
2671          --  Because the real value is converted to universal_real, this is a
2672          --  legal context for a universal fixed expression.
2673
2674          if T = Universal_Fixed then
2675             declare
2676                Loc  : constant Source_Ptr := Sloc (N);
2677                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2678                         Subtype_Mark =>
2679                           New_Occurrence_Of (Universal_Real, Loc),
2680                         Expression => Relocate_Node (E));
2681
2682             begin
2683                Rewrite (E, Conv);
2684                Analyze (E);
2685             end;
2686
2687          elsif T = Any_Fixed then
2688             Error_Msg_N ("illegal context for mixed mode operation", E);
2689
2690             --  Expression is of the form : universal_fixed * integer. Try to
2691             --  resolve as universal_real.
2692
2693             T := Universal_Real;
2694             Set_Etype (E, T);
2695          end if;
2696
2697          Resolve (E, T);
2698          Set_Etype (Id, Universal_Real);
2699          Set_Ekind (Id, E_Named_Real);
2700
2701       else
2702          Wrong_Type (E, Any_Numeric);
2703          Resolve (E, T);
2704
2705          Set_Etype               (Id, T);
2706          Set_Ekind               (Id, E_Constant);
2707          Set_Never_Set_In_Source (Id, True);
2708          Set_Is_True_Constant    (Id, True);
2709          return;
2710       end if;
2711
2712       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2713          Set_Etype (E, Etype (Id));
2714       end if;
2715
2716       if not Is_OK_Static_Expression (E) then
2717          Flag_Non_Static_Expr
2718            ("non-static expression used in number declaration!", E);
2719          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2720          Set_Etype (E, Any_Type);
2721       end if;
2722    end Analyze_Number_Declaration;
2723
2724    --------------------------------
2725    -- Analyze_Object_Declaration --
2726    --------------------------------
2727
2728    procedure Analyze_Object_Declaration (N : Node_Id) is
2729       Loc   : constant Source_Ptr := Sloc (N);
2730       Id    : constant Entity_Id  := Defining_Identifier (N);
2731       T     : Entity_Id;
2732       Act_T : Entity_Id;
2733
2734       E : Node_Id := Expression (N);
2735       --  E is set to Expression (N) throughout this routine. When
2736       --  Expression (N) is modified, E is changed accordingly.
2737
2738       Prev_Entity : Entity_Id := Empty;
2739
2740       function Count_Tasks (T : Entity_Id) return Uint;
2741       --  This function is called when a non-generic library level object of a
2742       --  task type is declared. Its function is to count the static number of
2743       --  tasks declared within the type (it is only called if Has_Tasks is set
2744       --  for T). As a side effect, if an array of tasks with non-static bounds
2745       --  or a variant record type is encountered, Check_Restrictions is called
2746       --  indicating the count is unknown.
2747
2748       -----------------
2749       -- Count_Tasks --
2750       -----------------
2751
2752       function Count_Tasks (T : Entity_Id) return Uint is
2753          C : Entity_Id;
2754          X : Node_Id;
2755          V : Uint;
2756
2757       begin
2758          if Is_Task_Type (T) then
2759             return Uint_1;
2760
2761          elsif Is_Record_Type (T) then
2762             if Has_Discriminants (T) then
2763                Check_Restriction (Max_Tasks, N);
2764                return Uint_0;
2765
2766             else
2767                V := Uint_0;
2768                C := First_Component (T);
2769                while Present (C) loop
2770                   V := V + Count_Tasks (Etype (C));
2771                   Next_Component (C);
2772                end loop;
2773
2774                return V;
2775             end if;
2776
2777          elsif Is_Array_Type (T) then
2778             X := First_Index (T);
2779             V := Count_Tasks (Component_Type (T));
2780             while Present (X) loop
2781                C := Etype (X);
2782
2783                if not Is_Static_Subtype (C) then
2784                   Check_Restriction (Max_Tasks, N);
2785                   return Uint_0;
2786                else
2787                   V := V * (UI_Max (Uint_0,
2788                                     Expr_Value (Type_High_Bound (C)) -
2789                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2790                end if;
2791
2792                Next_Index (X);
2793             end loop;
2794
2795             return V;
2796
2797          else
2798             return Uint_0;
2799          end if;
2800       end Count_Tasks;
2801
2802    --  Start of processing for Analyze_Object_Declaration
2803
2804    begin
2805       --  There are three kinds of implicit types generated by an
2806       --  object declaration:
2807
2808       --   1. Those for generated by the original Object Definition
2809
2810       --   2. Those generated by the Expression
2811
2812       --   3. Those used to constrained the Object Definition with the
2813       --       expression constraints when it is unconstrained
2814
2815       --  They must be generated in this order to avoid order of elaboration
2816       --  issues. Thus the first step (after entering the name) is to analyze
2817       --  the object definition.
2818
2819       if Constant_Present (N) then
2820          Prev_Entity := Current_Entity_In_Scope (Id);
2821
2822          if Present (Prev_Entity)
2823            and then
2824              --  If the homograph is an implicit subprogram, it is overridden
2825              --  by the current declaration.
2826
2827              ((Is_Overloadable (Prev_Entity)
2828                 and then Is_Inherited_Operation (Prev_Entity))
2829
2830                --  The current object is a discriminal generated for an entry
2831                --  family index. Even though the index is a constant, in this
2832                --  particular context there is no true constant redeclaration.
2833                --  Enter_Name will handle the visibility.
2834
2835                or else
2836                 (Is_Discriminal (Id)
2837                    and then Ekind (Discriminal_Link (Id)) =
2838                               E_Entry_Index_Parameter)
2839
2840                --  The current object is the renaming for a generic declared
2841                --  within the instance.
2842
2843                or else
2844                 (Ekind (Prev_Entity) = E_Package
2845                   and then Nkind (Parent (Prev_Entity)) =
2846                                          N_Package_Renaming_Declaration
2847                   and then not Comes_From_Source (Prev_Entity)
2848                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
2849          then
2850             Prev_Entity := Empty;
2851          end if;
2852       end if;
2853
2854       if Present (Prev_Entity) then
2855          Constant_Redeclaration (Id, N, T);
2856
2857          Generate_Reference (Prev_Entity, Id, 'c');
2858          Set_Completion_Referenced (Id);
2859
2860          if Error_Posted (N) then
2861
2862             --  Type mismatch or illegal redeclaration, Do not analyze
2863             --  expression to avoid cascaded errors.
2864
2865             T := Find_Type_Of_Object (Object_Definition (N), N);
2866             Set_Etype (Id, T);
2867             Set_Ekind (Id, E_Variable);
2868             goto Leave;
2869          end if;
2870
2871       --  In the normal case, enter identifier at the start to catch premature
2872       --  usage in the initialization expression.
2873
2874       else
2875          Generate_Definition (Id);
2876          Enter_Name (Id);
2877
2878          Mark_Coextensions (N, Object_Definition (N));
2879
2880          T := Find_Type_Of_Object (Object_Definition (N), N);
2881
2882          if Nkind (Object_Definition (N)) = N_Access_Definition
2883            and then Present
2884              (Access_To_Subprogram_Definition (Object_Definition (N)))
2885            and then Protected_Present
2886              (Access_To_Subprogram_Definition (Object_Definition (N)))
2887          then
2888             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2889          end if;
2890
2891          if Error_Posted (Id) then
2892             Set_Etype (Id, T);
2893             Set_Ekind (Id, E_Variable);
2894             goto Leave;
2895          end if;
2896       end if;
2897
2898       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2899       --  out some static checks
2900
2901       if Ada_Version >= Ada_2005
2902         and then Can_Never_Be_Null (T)
2903       then
2904          --  In case of aggregates we must also take care of the correct
2905          --  initialization of nested aggregates bug this is done at the
2906          --  point of the analysis of the aggregate (see sem_aggr.adb)
2907
2908          if Present (Expression (N))
2909            and then Nkind (Expression (N)) = N_Aggregate
2910          then
2911             null;
2912
2913          else
2914             declare
2915                Save_Typ : constant Entity_Id := Etype (Id);
2916             begin
2917                Set_Etype (Id, T); --  Temp. decoration for static checks
2918                Null_Exclusion_Static_Checks (N);
2919                Set_Etype (Id, Save_Typ);
2920             end;
2921          end if;
2922       end if;
2923
2924       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2925
2926       --  If deferred constant, make sure context is appropriate. We detect
2927       --  a deferred constant as a constant declaration with no expression.
2928       --  A deferred constant can appear in a package body if its completion
2929       --  is by means of an interface pragma.
2930
2931       if Constant_Present (N)
2932         and then No (E)
2933       then
2934          --  A deferred constant may appear in the declarative part of the
2935          --  following constructs:
2936
2937          --     blocks
2938          --     entry bodies
2939          --     extended return statements
2940          --     package specs
2941          --     package bodies
2942          --     subprogram bodies
2943          --     task bodies
2944
2945          --  When declared inside a package spec, a deferred constant must be
2946          --  completed by a full constant declaration or pragma Import. In all
2947          --  other cases, the only proper completion is pragma Import. Extended
2948          --  return statements are flagged as invalid contexts because they do
2949          --  not have a declarative part and so cannot accommodate the pragma.
2950
2951          if Ekind (Current_Scope) = E_Return_Statement then
2952             Error_Msg_N
2953               ("invalid context for deferred constant declaration (RM 7.4)",
2954                N);
2955             Error_Msg_N
2956               ("\declaration requires an initialization expression",
2957                 N);
2958             Set_Constant_Present (N, False);
2959
2960          --  In Ada 83, deferred constant must be of private type
2961
2962          elsif not Is_Private_Type (T) then
2963             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
2964                Error_Msg_N
2965                  ("(Ada 83) deferred constant must be private type", N);
2966             end if;
2967          end if;
2968
2969       --  If not a deferred constant, then object declaration freezes its type
2970
2971       else
2972          Check_Fully_Declared (T, N);
2973          Freeze_Before (N, T);
2974       end if;
2975
2976       --  If the object was created by a constrained array definition, then
2977       --  set the link in both the anonymous base type and anonymous subtype
2978       --  that are built to represent the array type to point to the object.
2979
2980       if Nkind (Object_Definition (Declaration_Node (Id))) =
2981                         N_Constrained_Array_Definition
2982       then
2983          Set_Related_Array_Object (T, Id);
2984          Set_Related_Array_Object (Base_Type (T), Id);
2985       end if;
2986
2987       --  Special checks for protected objects not at library level
2988
2989       if Is_Protected_Type (T)
2990         and then not Is_Library_Level_Entity (Id)
2991       then
2992          Check_Restriction (No_Local_Protected_Objects, Id);
2993
2994          --  Protected objects with interrupt handlers must be at library level
2995
2996          --  Ada 2005: this test is not needed (and the corresponding clause
2997          --  in the RM is removed) because accessibility checks are sufficient
2998          --  to make handlers not at the library level illegal.
2999
3000          if Has_Interrupt_Handler (T)
3001            and then Ada_Version < Ada_2005
3002          then
3003             Error_Msg_N
3004               ("interrupt object can only be declared at library level", Id);
3005          end if;
3006       end if;
3007
3008       --  The actual subtype of the object is the nominal subtype, unless
3009       --  the nominal one is unconstrained and obtained from the expression.
3010
3011       Act_T := T;
3012
3013       --  Process initialization expression if present and not in error
3014
3015       if Present (E) and then E /= Error then
3016
3017          --  Generate an error in case of CPP class-wide object initialization.
3018          --  Required because otherwise the expansion of the class-wide
3019          --  assignment would try to use 'size to initialize the object
3020          --  (primitive that is not available in CPP tagged types).
3021
3022          if Is_Class_Wide_Type (Act_T)
3023            and then
3024              (Is_CPP_Class (Root_Type (Etype (Act_T)))
3025                or else
3026                  (Present (Full_View (Root_Type (Etype (Act_T))))
3027                     and then
3028                       Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
3029          then
3030             Error_Msg_N
3031               ("predefined assignment not available for 'C'P'P tagged types",
3032                E);
3033          end if;
3034
3035          Mark_Coextensions (N, E);
3036          Analyze (E);
3037
3038          --  In case of errors detected in the analysis of the expression,
3039          --  decorate it with the expected type to avoid cascaded errors
3040
3041          if No (Etype (E)) then
3042             Set_Etype (E, T);
3043          end if;
3044
3045          --  If an initialization expression is present, then we set the
3046          --  Is_True_Constant flag. It will be reset if this is a variable
3047          --  and it is indeed modified.
3048
3049          Set_Is_True_Constant (Id, True);
3050
3051          --  If we are analyzing a constant declaration, set its completion
3052          --  flag after analyzing and resolving the expression.
3053
3054          if Constant_Present (N) then
3055             Set_Has_Completion (Id);
3056          end if;
3057
3058          --  Set type and resolve (type may be overridden later on)
3059
3060          Set_Etype (Id, T);
3061          Resolve (E, T);
3062
3063          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3064          --  node (which was marked already-analyzed), we need to set the type
3065          --  to something other than Any_Access in order to keep gigi happy.
3066
3067          if Etype (E) = Any_Access then
3068             Set_Etype (E, T);
3069          end if;
3070
3071          --  If the object is an access to variable, the initialization
3072          --  expression cannot be an access to constant.
3073
3074          if Is_Access_Type (T)
3075            and then not Is_Access_Constant (T)
3076            and then Is_Access_Type (Etype (E))
3077            and then Is_Access_Constant (Etype (E))
3078          then
3079             Error_Msg_N
3080               ("access to variable cannot be initialized "
3081                & "with an access-to-constant expression", E);
3082          end if;
3083
3084          if not Assignment_OK (N) then
3085             Check_Initialization (T, E);
3086          end if;
3087
3088          Check_Unset_Reference (E);
3089
3090          --  If this is a variable, then set current value. If this is a
3091          --  declared constant of a scalar type with a static expression,
3092          --  indicate that it is always valid.
3093
3094          if not Constant_Present (N) then
3095             if Compile_Time_Known_Value (E) then
3096                Set_Current_Value (Id, E);
3097             end if;
3098
3099          elsif Is_Scalar_Type (T)
3100            and then Is_OK_Static_Expression (E)
3101          then
3102             Set_Is_Known_Valid (Id);
3103          end if;
3104
3105          --  Deal with setting of null flags
3106
3107          if Is_Access_Type (T) then
3108             if Known_Non_Null (E) then
3109                Set_Is_Known_Non_Null (Id, True);
3110             elsif Known_Null (E)
3111               and then not Can_Never_Be_Null (Id)
3112             then
3113                Set_Is_Known_Null (Id, True);
3114             end if;
3115          end if;
3116
3117          --  Check incorrect use of dynamically tagged expressions.
3118
3119          if Is_Tagged_Type (T) then
3120             Check_Dynamically_Tagged_Expression
3121               (Expr        => E,
3122                Typ         => T,
3123                Related_Nod => N);
3124          end if;
3125
3126          Apply_Scalar_Range_Check (E, T);
3127          Apply_Static_Length_Check (E, T);
3128       end if;
3129
3130       --  If the No_Streams restriction is set, check that the type of the
3131       --  object is not, and does not contain, any subtype derived from
3132       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3133       --  Has_Stream just for efficiency reasons. There is no point in
3134       --  spending time on a Has_Stream check if the restriction is not set.
3135
3136       if Restriction_Check_Required (No_Streams) then
3137          if Has_Stream (T) then
3138             Check_Restriction (No_Streams, N);
3139          end if;
3140       end if;
3141
3142       --  Deal with predicate check before we start to do major rewriting.
3143       --  it is OK to initialize and then check the initialized value, since
3144       --  the object goes out of scope if we get a predicate failure. Note
3145       --  that we do this in the analyzer and not the expander because the
3146       --  analyzer does some substantial rewriting in some cases.
3147
3148       --  We need a predicate check if the type has predicates, and if either
3149       --  there is an initializing expression, or for default initialization
3150       --  when we have at least one case of an explicit default initial value.
3151
3152       if not Suppress_Assignment_Checks (N)
3153         and then Present (Predicate_Function (T))
3154         and then
3155           (Present (E)
3156             or else
3157               Is_Partially_Initialized_Type (T, Include_Implicit => False))
3158       then
3159          Insert_After (N,
3160            Make_Predicate_Check (T, New_Occurrence_Of (Id, Loc)));
3161       end if;
3162
3163       --  Case of unconstrained type
3164
3165       if Is_Indefinite_Subtype (T) then
3166
3167          --  Nothing to do in deferred constant case
3168
3169          if Constant_Present (N) and then No (E) then
3170             null;
3171
3172          --  Case of no initialization present
3173
3174          elsif No (E) then
3175             if No_Initialization (N) then
3176                null;
3177
3178             elsif Is_Class_Wide_Type (T) then
3179                Error_Msg_N
3180                  ("initialization required in class-wide declaration ", N);
3181
3182             else
3183                Error_Msg_N
3184                  ("unconstrained subtype not allowed (need initialization)",
3185                   Object_Definition (N));
3186
3187                if Is_Record_Type (T) and then Has_Discriminants (T) then
3188                   Error_Msg_N
3189                     ("\provide initial value or explicit discriminant values",
3190                      Object_Definition (N));
3191
3192                   Error_Msg_NE
3193                     ("\or give default discriminant values for type&",
3194                      Object_Definition (N), T);
3195
3196                elsif Is_Array_Type (T) then
3197                   Error_Msg_N
3198                     ("\provide initial value or explicit array bounds",
3199                      Object_Definition (N));
3200                end if;
3201             end if;
3202
3203          --  Case of initialization present but in error. Set initial
3204          --  expression as absent (but do not make above complaints)
3205
3206          elsif E = Error then
3207             Set_Expression (N, Empty);
3208             E := Empty;
3209
3210          --  Case of initialization present
3211
3212          else
3213             --  Not allowed in Ada 83
3214
3215             if not Constant_Present (N) then
3216                if Ada_Version = Ada_83
3217                  and then Comes_From_Source (Object_Definition (N))
3218                then
3219                   Error_Msg_N
3220                     ("(Ada 83) unconstrained variable not allowed",
3221                      Object_Definition (N));
3222                end if;
3223             end if;
3224
3225             --  Now we constrain the variable from the initializing expression
3226
3227             --  If the expression is an aggregate, it has been expanded into
3228             --  individual assignments. Retrieve the actual type from the
3229             --  expanded construct.
3230
3231             if Is_Array_Type (T)
3232               and then No_Initialization (N)
3233               and then Nkind (Original_Node (E)) = N_Aggregate
3234             then
3235                Act_T := Etype (E);
3236
3237             --  In case of class-wide interface object declarations we delay
3238             --  the generation of the equivalent record type declarations until
3239             --  its expansion because there are cases in they are not required.
3240
3241             elsif Is_Interface (T) then
3242                null;
3243
3244             else
3245                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3246                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3247             end if;
3248
3249             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3250
3251             if Aliased_Present (N) then
3252                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3253             end if;
3254
3255             Freeze_Before (N, Act_T);
3256             Freeze_Before (N, T);
3257          end if;
3258
3259       elsif Is_Array_Type (T)
3260         and then No_Initialization (N)
3261         and then Nkind (Original_Node (E)) = N_Aggregate
3262       then
3263          if not Is_Entity_Name (Object_Definition (N)) then
3264             Act_T := Etype (E);
3265             Check_Compile_Time_Size (Act_T);
3266
3267             if Aliased_Present (N) then
3268                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3269             end if;
3270          end if;
3271
3272          --  When the given object definition and the aggregate are specified
3273          --  independently, and their lengths might differ do a length check.
3274          --  This cannot happen if the aggregate is of the form (others =>...)
3275
3276          if not Is_Constrained (T) then
3277             null;
3278
3279          elsif Nkind (E) = N_Raise_Constraint_Error then
3280
3281             --  Aggregate is statically illegal. Place back in declaration
3282
3283             Set_Expression (N, E);
3284             Set_No_Initialization (N, False);
3285
3286          elsif T = Etype (E) then
3287             null;
3288
3289          elsif Nkind (E) = N_Aggregate
3290            and then Present (Component_Associations (E))
3291            and then Present (Choices (First (Component_Associations (E))))
3292            and then Nkind (First
3293             (Choices (First (Component_Associations (E))))) = N_Others_Choice
3294          then
3295             null;
3296
3297          else
3298             Apply_Length_Check (E, T);
3299          end if;
3300
3301       --  If the type is limited unconstrained with defaulted discriminants and
3302       --  there is no expression, then the object is constrained by the
3303       --  defaults, so it is worthwhile building the corresponding subtype.
3304
3305       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
3306         and then not Is_Constrained (T)
3307         and then Has_Discriminants (T)
3308       then
3309          if No (E) then
3310             Act_T := Build_Default_Subtype (T, N);
3311          else
3312             --  Ada 2005:  a limited object may be initialized by means of an
3313             --  aggregate. If the type has default discriminants it has an
3314             --  unconstrained nominal type, Its actual subtype will be obtained
3315             --  from the aggregate, and not from the default discriminants.
3316
3317             Act_T := Etype (E);
3318          end if;
3319
3320          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
3321
3322       elsif Present (Underlying_Type (T))
3323         and then not Is_Constrained (Underlying_Type (T))
3324         and then Has_Discriminants (Underlying_Type (T))
3325         and then Nkind (E) = N_Function_Call
3326         and then Constant_Present (N)
3327       then
3328          --  The back-end has problems with constants of a discriminated type
3329          --  with defaults, if the initial value is a function call. We
3330          --  generate an intermediate temporary for the result of the call.
3331          --  It is unclear why this should make it acceptable to gcc. ???
3332
3333          Remove_Side_Effects (E);
3334       end if;
3335
3336       --  Check No_Wide_Characters restriction
3337
3338       Check_Wide_Character_Restriction (T, Object_Definition (N));
3339
3340       --  Indicate this is not set in source. Certainly true for constants,
3341       --  and true for variables so far (will be reset for a variable if and
3342       --  when we encounter a modification in the source).
3343
3344       Set_Never_Set_In_Source (Id, True);
3345
3346       --  Now establish the proper kind and type of the object
3347
3348       if Constant_Present (N) then
3349          Set_Ekind            (Id, E_Constant);
3350          Set_Is_True_Constant (Id, True);
3351
3352       else
3353          Set_Ekind (Id, E_Variable);
3354
3355          --  A variable is set as shared passive if it appears in a shared
3356          --  passive package, and is at the outer level. This is not done
3357          --  for entities generated during expansion, because those are
3358          --  always manipulated locally.
3359
3360          if Is_Shared_Passive (Current_Scope)
3361            and then Is_Library_Level_Entity (Id)
3362            and then Comes_From_Source (Id)
3363          then
3364             Set_Is_Shared_Passive (Id);
3365             Check_Shared_Var (Id, T, N);
3366          end if;
3367
3368          --  Set Has_Initial_Value if initializing expression present. Note
3369          --  that if there is no initializing expression, we leave the state
3370          --  of this flag unchanged (usually it will be False, but notably in
3371          --  the case of exception choice variables, it will already be true).
3372
3373          if Present (E) then
3374             Set_Has_Initial_Value (Id, True);
3375          end if;
3376       end if;
3377
3378       --  Initialize alignment and size and capture alignment setting
3379
3380       Init_Alignment               (Id);
3381       Init_Esize                   (Id);
3382       Set_Optimize_Alignment_Flags (Id);
3383
3384       --  Deal with aliased case
3385
3386       if Aliased_Present (N) then
3387          Set_Is_Aliased (Id);
3388
3389          --  If the object is aliased and the type is unconstrained with
3390          --  defaulted discriminants and there is no expression, then the
3391          --  object is constrained by the defaults, so it is worthwhile
3392          --  building the corresponding subtype.
3393
3394          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3395          --  unconstrained, then only establish an actual subtype if the
3396          --  nominal subtype is indefinite. In definite cases the object is
3397          --  unconstrained in Ada 2005.
3398
3399          if No (E)
3400            and then Is_Record_Type (T)
3401            and then not Is_Constrained (T)
3402            and then Has_Discriminants (T)
3403            and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
3404          then
3405             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3406          end if;
3407       end if;
3408
3409       --  Now we can set the type of the object
3410
3411       Set_Etype (Id, Act_T);
3412
3413       --  Deal with controlled types
3414
3415       if Has_Controlled_Component (Etype (Id))
3416         or else Is_Controlled (Etype (Id))
3417       then
3418          if not Is_Library_Level_Entity (Id) then
3419             Check_Restriction (No_Nested_Finalization, N);
3420          else
3421             Validate_Controlled_Object (Id);
3422          end if;
3423
3424          --  Generate a warning when an initialization causes an obvious ABE
3425          --  violation. If the init expression is a simple aggregate there
3426          --  shouldn't be any initialize/adjust call generated. This will be
3427          --  true as soon as aggregates are built in place when possible.
3428
3429          --  ??? at the moment we do not generate warnings for temporaries
3430          --  created for those aggregates although Program_Error might be
3431          --  generated if compiled with -gnato.
3432
3433          if Is_Controlled (Etype (Id))
3434             and then Comes_From_Source (Id)
3435          then
3436             declare
3437                BT : constant Entity_Id := Base_Type (Etype (Id));
3438
3439                Implicit_Call : Entity_Id;
3440                pragma Warnings (Off, Implicit_Call);
3441                --  ??? what is this for (never referenced!)
3442
3443                function Is_Aggr (N : Node_Id) return Boolean;
3444                --  Check that N is an aggregate
3445
3446                -------------
3447                -- Is_Aggr --
3448                -------------
3449
3450                function Is_Aggr (N : Node_Id) return Boolean is
3451                begin
3452                   case Nkind (Original_Node (N)) is
3453                      when N_Aggregate | N_Extension_Aggregate =>
3454                         return True;
3455
3456                      when N_Qualified_Expression |
3457                           N_Type_Conversion      |
3458                           N_Unchecked_Type_Conversion =>
3459                         return Is_Aggr (Expression (Original_Node (N)));
3460
3461                      when others =>
3462                         return False;
3463                   end case;
3464                end Is_Aggr;
3465
3466             begin
3467                --  If no underlying type, we already are in an error situation.
3468                --  Do not try to add a warning since we do not have access to
3469                --  prim-op list.
3470
3471                if No (Underlying_Type (BT)) then
3472                   Implicit_Call := Empty;
3473
3474                --  A generic type does not have usable primitive operators.
3475                --  Initialization calls are built for instances.
3476
3477                elsif Is_Generic_Type (BT) then
3478                   Implicit_Call := Empty;
3479
3480                --  If the init expression is not an aggregate, an adjust call
3481                --  will be generated
3482
3483                elsif Present (E) and then not Is_Aggr (E) then
3484                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
3485
3486                --  If no init expression and we are not in the deferred
3487                --  constant case, an Initialize call will be generated
3488
3489                elsif No (E) and then not Constant_Present (N) then
3490                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
3491
3492                else
3493                   Implicit_Call := Empty;
3494                end if;
3495             end;
3496          end if;
3497       end if;
3498
3499       if Has_Task (Etype (Id)) then
3500          Check_Restriction (No_Tasking, N);
3501
3502          --  Deal with counting max tasks
3503
3504          --  Nothing to do if inside a generic
3505
3506          if Inside_A_Generic then
3507             null;
3508
3509          --  If library level entity, then count tasks
3510
3511          elsif Is_Library_Level_Entity (Id) then
3512             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3513
3514          --  If not library level entity, then indicate we don't know max
3515          --  tasks and also check task hierarchy restriction and blocking
3516          --  operation (since starting a task is definitely blocking!)
3517
3518          else
3519             Check_Restriction (Max_Tasks, N);
3520             Check_Restriction (No_Task_Hierarchy, N);
3521             Check_Potentially_Blocking_Operation (N);
3522          end if;
3523
3524          --  A rather specialized test. If we see two tasks being declared
3525          --  of the same type in the same object declaration, and the task
3526          --  has an entry with an address clause, we know that program error
3527          --  will be raised at run time since we can't have two tasks with
3528          --  entries at the same address.
3529
3530          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3531             declare
3532                E : Entity_Id;
3533
3534             begin
3535                E := First_Entity (Etype (Id));
3536                while Present (E) loop
3537                   if Ekind (E) = E_Entry
3538                     and then Present (Get_Attribute_Definition_Clause
3539                                         (E, Attribute_Address))
3540                   then
3541                      Error_Msg_N
3542                        ("?more than one task with same entry address", N);
3543                      Error_Msg_N
3544                        ("\?Program_Error will be raised at run time", N);
3545                      Insert_Action (N,
3546                        Make_Raise_Program_Error (Loc,
3547                          Reason => PE_Duplicated_Entry_Address));
3548                      exit;
3549                   end if;
3550
3551                   Next_Entity (E);
3552                end loop;
3553             end;
3554          end if;
3555       end if;
3556
3557       --  Some simple constant-propagation: if the expression is a constant
3558       --  string initialized with a literal, share the literal. This avoids
3559       --  a run-time copy.
3560
3561       if Present (E)
3562         and then Is_Entity_Name (E)
3563         and then Ekind (Entity (E)) = E_Constant
3564         and then Base_Type (Etype (E)) = Standard_String
3565       then
3566          declare
3567             Val : constant Node_Id := Constant_Value (Entity (E));
3568          begin
3569             if Present (Val)
3570               and then Nkind (Val) = N_String_Literal
3571             then
3572                Rewrite (E, New_Copy (Val));
3573             end if;
3574          end;
3575       end if;
3576
3577       --  Another optimization: if the nominal subtype is unconstrained and
3578       --  the expression is a function call that returns an unconstrained
3579       --  type, rewrite the declaration as a renaming of the result of the
3580       --  call. The exceptions below are cases where the copy is expected,
3581       --  either by the back end (Aliased case) or by the semantics, as for
3582       --  initializing controlled types or copying tags for classwide types.
3583
3584       if Present (E)
3585         and then Nkind (E) = N_Explicit_Dereference
3586         and then Nkind (Original_Node (E)) = N_Function_Call
3587         and then not Is_Library_Level_Entity (Id)
3588         and then not Is_Constrained (Underlying_Type (T))
3589         and then not Is_Aliased (Id)
3590         and then not Is_Class_Wide_Type (T)
3591         and then not Is_Controlled (T)
3592         and then not Has_Controlled_Component (Base_Type (T))
3593         and then Expander_Active
3594       then
3595          Rewrite (N,
3596            Make_Object_Renaming_Declaration (Loc,
3597              Defining_Identifier => Id,
3598              Access_Definition   => Empty,
3599              Subtype_Mark        => New_Occurrence_Of
3600                                       (Base_Type (Etype (Id)), Loc),
3601              Name                => E));
3602
3603          Set_Renamed_Object (Id, E);
3604
3605          --  Force generation of debugging information for the constant and for
3606          --  the renamed function call.
3607
3608          Set_Debug_Info_Needed (Id);
3609          Set_Debug_Info_Needed (Entity (Prefix (E)));
3610       end if;
3611
3612       if Present (Prev_Entity)
3613         and then Is_Frozen (Prev_Entity)
3614         and then not Error_Posted (Id)
3615       then
3616          Error_Msg_N ("full constant declaration appears too late", N);
3617       end if;
3618
3619       Check_Eliminated (Id);
3620
3621       --  Deal with setting In_Private_Part flag if in private part
3622
3623       if Ekind (Scope (Id)) = E_Package
3624         and then In_Private_Part (Scope (Id))
3625       then
3626          Set_In_Private_Part (Id);
3627       end if;
3628
3629       --  Check for violation of No_Local_Timing_Events
3630
3631       if Is_RTE (Etype (Id), RE_Timing_Event)
3632         and then not Is_Library_Level_Entity (Id)
3633       then
3634          Check_Restriction (No_Local_Timing_Events, N);
3635       end if;
3636
3637    <<Leave>>
3638       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
3639    end Analyze_Object_Declaration;
3640
3641    ---------------------------
3642    -- Analyze_Others_Choice --
3643    ---------------------------
3644
3645    --  Nothing to do for the others choice node itself, the semantic analysis
3646    --  of the others choice will occur as part of the processing of the parent
3647
3648    procedure Analyze_Others_Choice (N : Node_Id) is
3649       pragma Warnings (Off, N);
3650    begin
3651       null;
3652    end Analyze_Others_Choice;
3653
3654    -------------------------------------------
3655    -- Analyze_Private_Extension_Declaration --
3656    -------------------------------------------
3657
3658    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3659       T           : constant Entity_Id := Defining_Identifier (N);
3660       Indic       : constant Node_Id   := Subtype_Indication (N);
3661       Parent_Type : Entity_Id;
3662       Parent_Base : Entity_Id;
3663
3664    begin
3665       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3666
3667       if Is_Non_Empty_List (Interface_List (N)) then
3668          declare
3669             Intf : Node_Id;
3670             T    : Entity_Id;
3671
3672          begin
3673             Intf := First (Interface_List (N));
3674             while Present (Intf) loop
3675                T := Find_Type_Of_Subtype_Indic (Intf);
3676
3677                Diagnose_Interface (Intf, T);
3678                Next (Intf);
3679             end loop;
3680          end;
3681       end if;
3682
3683       Generate_Definition (T);
3684
3685       --  For other than Ada 2012, just enter the name in the current scope
3686
3687       if Ada_Version < Ada_2012 then
3688          Enter_Name (T);
3689
3690       --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
3691       --  case of private type that completes an incomplete type.
3692
3693       else
3694          declare
3695             Prev : Entity_Id;
3696
3697          begin
3698             Prev := Find_Type_Name (N);
3699
3700             pragma Assert (Prev = T
3701               or else (Ekind (Prev) = E_Incomplete_Type
3702                          and then Present (Full_View (Prev))
3703                          and then Full_View (Prev) = T));
3704          end;
3705       end if;
3706
3707       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3708       Parent_Base := Base_Type (Parent_Type);
3709
3710       if Parent_Type = Any_Type
3711         or else Etype (Parent_Type) = Any_Type
3712       then
3713          Set_Ekind (T, Ekind (Parent_Type));
3714          Set_Etype (T, Any_Type);
3715          goto Leave;
3716
3717       elsif not Is_Tagged_Type (Parent_Type) then
3718          Error_Msg_N
3719            ("parent of type extension must be a tagged type ", Indic);
3720          goto Leave;
3721
3722       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3723          Error_Msg_N ("premature derivation of incomplete type", Indic);
3724          goto Leave;
3725
3726       elsif Is_Concurrent_Type (Parent_Type) then
3727          Error_Msg_N
3728            ("parent type of a private extension cannot be "
3729             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3730
3731          Set_Etype              (T, Any_Type);
3732          Set_Ekind              (T, E_Limited_Private_Type);
3733          Set_Private_Dependents (T, New_Elmt_List);
3734          Set_Error_Posted       (T);
3735          goto Leave;
3736       end if;
3737
3738       --  Perhaps the parent type should be changed to the class-wide type's
3739       --  specific type in this case to prevent cascading errors ???
3740
3741       if Is_Class_Wide_Type (Parent_Type) then
3742          Error_Msg_N
3743            ("parent of type extension must not be a class-wide type", Indic);
3744          goto Leave;
3745       end if;
3746
3747       if (not Is_Package_Or_Generic_Package (Current_Scope)
3748            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3749         or else In_Private_Part (Current_Scope)
3750
3751       then
3752          Error_Msg_N ("invalid context for private extension", N);
3753       end if;
3754
3755       --  Set common attributes
3756
3757       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3758       Set_Scope            (T, Current_Scope);
3759       Set_Ekind            (T, E_Record_Type_With_Private);
3760       Init_Size_Align      (T);
3761
3762       Set_Etype            (T,            Parent_Base);
3763       Set_Has_Task         (T, Has_Task  (Parent_Base));
3764
3765       Set_Convention       (T, Convention     (Parent_Type));
3766       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3767       Set_Is_First_Subtype (T);
3768       Make_Class_Wide_Type (T);
3769
3770       if Unknown_Discriminants_Present (N) then
3771          Set_Discriminant_Constraint (T, No_Elist);
3772       end if;
3773
3774       Build_Derived_Record_Type (N, Parent_Type, T);
3775
3776       --  Propagate inherited invariant information. The new type has
3777       --  invariants, if the parent type has inheritable invariants,
3778       --  and these invariants can in turn be inherited.
3779
3780       if Has_Inheritable_Invariants (Parent_Type) then
3781          Set_Has_Inheritable_Invariants (T);
3782          Set_Has_Invariants (T);
3783       end if;
3784
3785       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3786       --  synchronized formal derived type.
3787
3788       if Ada_Version >= Ada_2005
3789         and then Synchronized_Present (N)
3790       then
3791          Set_Is_Limited_Record (T);
3792
3793          --  Formal derived type case
3794
3795          if Is_Generic_Type (T) then
3796
3797             --  The parent must be a tagged limited type or a synchronized
3798             --  interface.
3799
3800             if (not Is_Tagged_Type (Parent_Type)
3801                   or else not Is_Limited_Type (Parent_Type))
3802               and then
3803                (not Is_Interface (Parent_Type)
3804                   or else not Is_Synchronized_Interface (Parent_Type))
3805             then
3806                Error_Msg_NE ("parent type of & must be tagged limited " &
3807                              "or synchronized", N, T);
3808             end if;
3809
3810             --  The progenitors (if any) must be limited or synchronized
3811             --  interfaces.
3812
3813             if Present (Interfaces (T)) then
3814                declare
3815                   Iface      : Entity_Id;
3816                   Iface_Elmt : Elmt_Id;
3817
3818                begin
3819                   Iface_Elmt := First_Elmt (Interfaces (T));
3820                   while Present (Iface_Elmt) loop
3821                      Iface := Node (Iface_Elmt);
3822
3823                      if not Is_Limited_Interface (Iface)
3824                        and then not Is_Synchronized_Interface (Iface)
3825                      then
3826                         Error_Msg_NE ("progenitor & must be limited " &
3827                                       "or synchronized", N, Iface);
3828                      end if;
3829
3830                      Next_Elmt (Iface_Elmt);
3831                   end loop;
3832                end;
3833             end if;
3834
3835          --  Regular derived extension, the parent must be a limited or
3836          --  synchronized interface.
3837
3838          else
3839             if not Is_Interface (Parent_Type)
3840               or else (not Is_Limited_Interface (Parent_Type)
3841                          and then
3842                        not Is_Synchronized_Interface (Parent_Type))
3843             then
3844                Error_Msg_NE
3845                  ("parent type of & must be limited interface", N, T);
3846             end if;
3847          end if;
3848
3849       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
3850       --  extension with a synchronized parent must be explicitly declared
3851       --  synchronized, because the full view will be a synchronized type.
3852       --  This must be checked before the check for limited types below,
3853       --  to ensure that types declared limited are not allowed to extend
3854       --  synchronized interfaces.
3855
3856       elsif Is_Interface (Parent_Type)
3857         and then Is_Synchronized_Interface (Parent_Type)
3858         and then not Synchronized_Present (N)
3859       then
3860          Error_Msg_NE
3861            ("private extension of& must be explicitly synchronized",
3862              N, Parent_Type);
3863
3864       elsif Limited_Present (N) then
3865          Set_Is_Limited_Record (T);
3866
3867          if not Is_Limited_Type (Parent_Type)
3868            and then
3869              (not Is_Interface (Parent_Type)
3870                or else not Is_Limited_Interface (Parent_Type))
3871          then
3872             Error_Msg_NE ("parent type& of limited extension must be limited",
3873               N, Parent_Type);
3874          end if;
3875       end if;
3876
3877       <<Leave>>
3878          Analyze_Aspect_Specifications (N, T, Aspect_Specifications (N));
3879    end Analyze_Private_Extension_Declaration;
3880
3881    ---------------------------------
3882    -- Analyze_Subtype_Declaration --
3883    ---------------------------------
3884
3885    procedure Analyze_Subtype_Declaration
3886      (N    : Node_Id;
3887       Skip : Boolean := False)
3888    is
3889       Id       : constant Entity_Id := Defining_Identifier (N);
3890       T        : Entity_Id;
3891       R_Checks : Check_Result;
3892
3893    begin
3894       Generate_Definition (Id);
3895       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3896       Init_Size_Align (Id);
3897
3898       --  The following guard condition on Enter_Name is to handle cases where
3899       --  the defining identifier has already been entered into the scope but
3900       --  the declaration as a whole needs to be analyzed.
3901
3902       --  This case in particular happens for derived enumeration types. The
3903       --  derived enumeration type is processed as an inserted enumeration type
3904       --  declaration followed by a rewritten subtype declaration. The defining
3905       --  identifier, however, is entered into the name scope very early in the
3906       --  processing of the original type declaration and therefore needs to be
3907       --  avoided here, when the created subtype declaration is analyzed. (See
3908       --  Build_Derived_Types)
3909
3910       --  This also happens when the full view of a private type is derived
3911       --  type with constraints. In this case the entity has been introduced
3912       --  in the private declaration.
3913
3914       if Skip
3915         or else (Present (Etype (Id))
3916                    and then (Is_Private_Type (Etype (Id))
3917                                or else Is_Task_Type (Etype (Id))
3918                                or else Is_Rewrite_Substitution (N)))
3919       then
3920          null;
3921
3922       else
3923          Enter_Name (Id);
3924       end if;
3925
3926       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
3927
3928       --  Inherit common attributes
3929
3930       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
3931       Set_Is_Volatile       (Id, Is_Volatile       (T));
3932       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
3933       Set_Is_Atomic         (Id, Is_Atomic         (T));
3934       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
3935       Set_Is_Ada_2012_Only  (Id, Is_Ada_2012_Only  (T));
3936       Set_Convention        (Id, Convention        (T));
3937
3938       --  If ancestor has predicates then so does the subtype, and in addition
3939       --  we must delay the freeze to properly arrange predicate inheritance.
3940
3941       --  The Ancestor_Type test is a big kludge, there seem to be cases in
3942       --  which T = ID, so the above tests and assignments do nothing???
3943
3944       if Has_Predicates (T)
3945         or else (Present (Ancestor_Subtype (T))
3946                    and then Has_Predicates (Ancestor_Subtype (T)))
3947       then
3948          Set_Has_Predicates (Id);
3949          Set_Has_Delayed_Freeze (Id);
3950       end if;
3951
3952       --  In the case where there is no constraint given in the subtype
3953       --  indication, Process_Subtype just returns the Subtype_Mark, so its
3954       --  semantic attributes must be established here.
3955
3956       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
3957          Set_Etype (Id, Base_Type (T));
3958
3959          case Ekind (T) is
3960             when Array_Kind =>
3961                Set_Ekind                       (Id, E_Array_Subtype);
3962                Copy_Array_Subtype_Attributes   (Id, T);
3963
3964             when Decimal_Fixed_Point_Kind =>
3965                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
3966                Set_Digits_Value         (Id, Digits_Value       (T));
3967                Set_Delta_Value          (Id, Delta_Value        (T));
3968                Set_Scale_Value          (Id, Scale_Value        (T));
3969                Set_Small_Value          (Id, Small_Value        (T));
3970                Set_Scalar_Range         (Id, Scalar_Range       (T));
3971                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
3972                Set_Is_Constrained       (Id, Is_Constrained     (T));
3973                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3974                Set_RM_Size              (Id, RM_Size            (T));
3975
3976             when Enumeration_Kind =>
3977                Set_Ekind                (Id, E_Enumeration_Subtype);
3978                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
3979                Set_Scalar_Range         (Id, Scalar_Range       (T));
3980                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
3981                Set_Is_Constrained       (Id, Is_Constrained     (T));
3982                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3983                Set_RM_Size              (Id, RM_Size            (T));
3984
3985             when Ordinary_Fixed_Point_Kind =>
3986                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
3987                Set_Scalar_Range         (Id, Scalar_Range       (T));
3988                Set_Small_Value          (Id, Small_Value        (T));
3989                Set_Delta_Value          (Id, Delta_Value        (T));
3990                Set_Is_Constrained       (Id, Is_Constrained     (T));
3991                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3992                Set_RM_Size              (Id, RM_Size            (T));
3993
3994             when Float_Kind =>
3995                Set_Ekind                (Id, E_Floating_Point_Subtype);
3996                Set_Scalar_Range         (Id, Scalar_Range       (T));
3997                Set_Digits_Value         (Id, Digits_Value       (T));
3998                Set_Is_Constrained       (Id, Is_Constrained     (T));
3999
4000             when Signed_Integer_Kind =>
4001                Set_Ekind                (Id, E_Signed_Integer_Subtype);
4002                Set_Scalar_Range         (Id, Scalar_Range       (T));
4003                Set_Is_Constrained       (Id, Is_Constrained     (T));
4004                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4005                Set_RM_Size              (Id, RM_Size            (T));
4006
4007             when Modular_Integer_Kind =>
4008                Set_Ekind                (Id, E_Modular_Integer_Subtype);
4009                Set_Scalar_Range         (Id, Scalar_Range       (T));
4010                Set_Is_Constrained       (Id, Is_Constrained     (T));
4011                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4012                Set_RM_Size              (Id, RM_Size            (T));
4013
4014             when Class_Wide_Kind =>
4015                Set_Ekind                (Id, E_Class_Wide_Subtype);
4016                Set_First_Entity         (Id, First_Entity       (T));
4017                Set_Last_Entity          (Id, Last_Entity        (T));
4018                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
4019                Set_Cloned_Subtype       (Id, T);
4020                Set_Is_Tagged_Type       (Id, True);
4021                Set_Has_Unknown_Discriminants
4022                                         (Id, True);
4023
4024                if Ekind (T) = E_Class_Wide_Subtype then
4025                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
4026                end if;
4027
4028             when E_Record_Type | E_Record_Subtype =>
4029                Set_Ekind                (Id, E_Record_Subtype);
4030
4031                if Ekind (T) = E_Record_Subtype
4032                  and then Present (Cloned_Subtype (T))
4033                then
4034                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
4035                else
4036                   Set_Cloned_Subtype    (Id, T);
4037                end if;
4038
4039                Set_First_Entity         (Id, First_Entity       (T));
4040                Set_Last_Entity          (Id, Last_Entity        (T));
4041                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
4042                Set_Is_Constrained       (Id, Is_Constrained     (T));
4043                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
4044                Set_Has_Unknown_Discriminants
4045                                         (Id, Has_Unknown_Discriminants (T));
4046
4047                if Has_Discriminants (T) then
4048                   Set_Discriminant_Constraint
4049                                         (Id, Discriminant_Constraint (T));
4050                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4051
4052                elsif Has_Unknown_Discriminants (Id) then
4053                   Set_Discriminant_Constraint (Id, No_Elist);
4054                end if;
4055
4056                if Is_Tagged_Type (T) then
4057                   Set_Is_Tagged_Type    (Id);
4058                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
4059                   Set_Direct_Primitive_Operations
4060                                         (Id, Direct_Primitive_Operations (T));
4061                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
4062
4063                   if Is_Interface (T) then
4064                      Set_Is_Interface (Id);
4065                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
4066                   end if;
4067                end if;
4068
4069             when Private_Kind =>
4070                Set_Ekind              (Id, Subtype_Kind (Ekind   (T)));
4071                Set_Has_Discriminants  (Id, Has_Discriminants     (T));
4072                Set_Is_Constrained     (Id, Is_Constrained        (T));
4073                Set_First_Entity       (Id, First_Entity          (T));
4074                Set_Last_Entity        (Id, Last_Entity           (T));
4075                Set_Private_Dependents (Id, New_Elmt_List);
4076                Set_Is_Limited_Record  (Id, Is_Limited_Record     (T));
4077                Set_Has_Unknown_Discriminants
4078                                       (Id, Has_Unknown_Discriminants (T));
4079                Set_Known_To_Have_Preelab_Init
4080                                       (Id, Known_To_Have_Preelab_Init (T));
4081
4082                if Is_Tagged_Type (T) then
4083                   Set_Is_Tagged_Type              (Id);
4084                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
4085                   Set_Class_Wide_Type             (Id, Class_Wide_Type (T));
4086                   Set_Direct_Primitive_Operations (Id,
4087                     Direct_Primitive_Operations (T));
4088                end if;
4089
4090                --  In general the attributes of the subtype of a private type
4091                --  are the attributes of the partial view of parent. However,
4092                --  the full view may be a discriminated type, and the subtype
4093                --  must share the discriminant constraint to generate correct
4094                --  calls to initialization procedures.
4095
4096                if Has_Discriminants (T) then
4097                   Set_Discriminant_Constraint
4098                                      (Id, Discriminant_Constraint (T));
4099                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4100
4101                elsif Present (Full_View (T))
4102                  and then Has_Discriminants (Full_View (T))
4103                then
4104                   Set_Discriminant_Constraint
4105                                (Id, Discriminant_Constraint (Full_View (T)));
4106                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4107
4108                   --  This would seem semantically correct, but apparently
4109                   --  confuses the back-end. To be explained and checked with
4110                   --  current version ???
4111
4112                   --  Set_Has_Discriminants (Id);
4113                end if;
4114
4115                Prepare_Private_Subtype_Completion (Id, N);
4116
4117             when Access_Kind =>
4118                Set_Ekind             (Id, E_Access_Subtype);
4119                Set_Is_Constrained    (Id, Is_Constrained        (T));
4120                Set_Is_Access_Constant
4121                                      (Id, Is_Access_Constant    (T));
4122                Set_Directly_Designated_Type
4123                                      (Id, Designated_Type       (T));
4124                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4125
4126                --  A Pure library_item must not contain the declaration of a
4127                --  named access type, except within a subprogram, generic
4128                --  subprogram, task unit, or protected unit, or if it has
4129                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4130
4131                if Comes_From_Source (Id)
4132                  and then In_Pure_Unit
4133                  and then not In_Subprogram_Task_Protected_Unit
4134                  and then not No_Pool_Assigned (Id)
4135                then
4136                   Error_Msg_N
4137                     ("named access types not allowed in pure unit", N);
4138                end if;
4139
4140             when Concurrent_Kind =>
4141                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4142                Set_Corresponding_Record_Type (Id,
4143                                          Corresponding_Record_Type (T));
4144                Set_First_Entity         (Id, First_Entity          (T));
4145                Set_First_Private_Entity (Id, First_Private_Entity  (T));
4146                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4147                Set_Is_Constrained       (Id, Is_Constrained        (T));
4148                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4149                Set_Last_Entity          (Id, Last_Entity           (T));
4150
4151                if Has_Discriminants (T) then
4152                   Set_Discriminant_Constraint (Id,
4153                                            Discriminant_Constraint (T));
4154                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4155                end if;
4156
4157             when E_Incomplete_Type =>
4158                if Ada_Version >= Ada_2005 then
4159                   Set_Ekind (Id, E_Incomplete_Subtype);
4160
4161                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
4162                   --  of an incomplete type visible through a limited
4163                   --  with clause.
4164
4165                   if From_With_Type (T)
4166                     and then Present (Non_Limited_View (T))
4167                   then
4168                      Set_From_With_Type   (Id);
4169                      Set_Non_Limited_View (Id, Non_Limited_View (T));
4170
4171                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
4172                   --  to the private dependents of the original incomplete
4173                   --  type for future transformation.
4174
4175                   else
4176                      Append_Elmt (Id, Private_Dependents (T));
4177                   end if;
4178
4179                --  If the subtype name denotes an incomplete type an error
4180                --  was already reported by Process_Subtype.
4181
4182                else
4183                   Set_Etype (Id, Any_Type);
4184                end if;
4185
4186             when others =>
4187                raise Program_Error;
4188          end case;
4189       end if;
4190
4191       if Etype (Id) = Any_Type then
4192          goto Leave;
4193       end if;
4194
4195       --  Some common processing on all types
4196
4197       Set_Size_Info      (Id,                 T);
4198       Set_First_Rep_Item (Id, First_Rep_Item (T));
4199
4200       T := Etype (Id);
4201
4202       Set_Is_Immediately_Visible   (Id, True);
4203       Set_Depends_On_Private       (Id, Has_Private_Component (T));
4204       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
4205
4206       if Is_Interface (T) then
4207          Set_Is_Interface (Id);
4208       end if;
4209
4210       if Present (Generic_Parent_Type (N))
4211         and then
4212           (Nkind
4213             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
4214             or else Nkind
4215               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
4216                 /= N_Formal_Private_Type_Definition)
4217       then
4218          if Is_Tagged_Type (Id) then
4219
4220             --  If this is a generic actual subtype for a synchronized type,
4221             --  the primitive operations are those of the corresponding record
4222             --  for which there is a separate subtype declaration.
4223
4224             if Is_Concurrent_Type (Id) then
4225                null;
4226             elsif Is_Class_Wide_Type (Id) then
4227                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
4228             else
4229                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
4230             end if;
4231
4232          elsif Scope (Etype (Id)) /= Standard_Standard then
4233             Derive_Subprograms (Generic_Parent_Type (N), Id);
4234          end if;
4235       end if;
4236
4237       if Is_Private_Type (T)
4238         and then Present (Full_View (T))
4239       then
4240          Conditional_Delay (Id, Full_View (T));
4241
4242       --  The subtypes of components or subcomponents of protected types
4243       --  do not need freeze nodes, which would otherwise appear in the
4244       --  wrong scope (before the freeze node for the protected type). The
4245       --  proper subtypes are those of the subcomponents of the corresponding
4246       --  record.
4247
4248       elsif Ekind (Scope (Id)) /= E_Protected_Type
4249         and then Present (Scope (Scope (Id))) -- error defense!
4250         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
4251       then
4252          Conditional_Delay (Id, T);
4253       end if;
4254
4255       --  Check that constraint_error is raised for a scalar subtype
4256       --  indication when the lower or upper bound of a non-null range
4257       --  lies outside the range of the type mark.
4258
4259       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4260          if Is_Scalar_Type (Etype (Id))
4261             and then Scalar_Range (Id) /=
4262                      Scalar_Range (Etype (Subtype_Mark
4263                                            (Subtype_Indication (N))))
4264          then
4265             Apply_Range_Check
4266               (Scalar_Range (Id),
4267                Etype (Subtype_Mark (Subtype_Indication (N))));
4268
4269          elsif Is_Array_Type (Etype (Id))
4270            and then Present (First_Index (Id))
4271          then
4272             --  This really should be a subprogram that finds the indications
4273             --  to check???
4274
4275             if ((Nkind (First_Index (Id)) = N_Identifier
4276                    and then Ekind (Entity (First_Index (Id))) in Scalar_Kind)
4277                  or else Nkind (First_Index (Id)) = N_Subtype_Indication)
4278               and then
4279                 Nkind (Scalar_Range (Etype (First_Index (Id)))) = N_Range
4280             then
4281                declare
4282                   Target_Typ : constant Entity_Id :=
4283                                  Etype
4284                                    (First_Index (Etype
4285                                      (Subtype_Mark (Subtype_Indication (N)))));
4286                begin
4287                   R_Checks :=
4288                     Get_Range_Checks
4289                       (Scalar_Range (Etype (First_Index (Id))),
4290                        Target_Typ,
4291                        Etype (First_Index (Id)),
4292                        Defining_Identifier (N));
4293
4294                   Insert_Range_Checks
4295                     (R_Checks,
4296                      N,
4297                      Target_Typ,
4298                      Sloc (Defining_Identifier (N)));
4299                end;
4300             end if;
4301          end if;
4302       end if;
4303
4304       --  Make sure that generic actual types are properly frozen. The subtype
4305       --  is marked as a generic actual type when the enclosing instance is
4306       --  analyzed, so here we identify the subtype from the tree structure.
4307
4308       if Expander_Active
4309         and then Is_Generic_Actual_Type (Id)
4310         and then In_Instance
4311         and then not Comes_From_Source (N)
4312         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
4313         and then Is_Frozen (T)
4314       then
4315          Freeze_Before (N, Id);
4316       end if;
4317
4318       Set_Optimize_Alignment_Flags (Id);
4319       Check_Eliminated (Id);
4320
4321    <<Leave>>
4322       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
4323    end Analyze_Subtype_Declaration;
4324
4325    --------------------------------
4326    -- Analyze_Subtype_Indication --
4327    --------------------------------
4328
4329    procedure Analyze_Subtype_Indication (N : Node_Id) is
4330       T : constant Entity_Id := Subtype_Mark (N);
4331       R : constant Node_Id   := Range_Expression (Constraint (N));
4332
4333    begin
4334       Analyze (T);
4335
4336       if R /= Error then
4337          Analyze (R);
4338          Set_Etype (N, Etype (R));
4339          Resolve (R, Entity (T));
4340       else
4341          Set_Error_Posted (R);
4342          Set_Error_Posted (T);
4343       end if;
4344    end Analyze_Subtype_Indication;
4345
4346    --------------------------
4347    -- Analyze_Variant_Part --
4348    --------------------------
4349
4350    procedure Analyze_Variant_Part (N : Node_Id) is
4351
4352       procedure Non_Static_Choice_Error (Choice : Node_Id);
4353       --  Error routine invoked by the generic instantiation below when the
4354       --  variant part has a non static choice.
4355
4356       procedure Process_Declarations (Variant : Node_Id);
4357       --  Analyzes all the declarations associated with a Variant. Needed by
4358       --  the generic instantiation below.
4359
4360       package Variant_Choices_Processing is new
4361         Generic_Choices_Processing
4362           (Get_Alternatives          => Variants,
4363            Get_Choices               => Discrete_Choices,
4364            Process_Empty_Choice      => No_OP,
4365            Process_Non_Static_Choice => Non_Static_Choice_Error,
4366            Process_Associated_Node   => Process_Declarations);
4367       use Variant_Choices_Processing;
4368       --  Instantiation of the generic choice processing package
4369
4370       -----------------------------
4371       -- Non_Static_Choice_Error --
4372       -----------------------------
4373
4374       procedure Non_Static_Choice_Error (Choice : Node_Id) is
4375       begin
4376          Flag_Non_Static_Expr
4377            ("choice given in variant part is not static!", Choice);
4378       end Non_Static_Choice_Error;
4379
4380       --------------------------
4381       -- Process_Declarations --
4382       --------------------------
4383
4384       procedure Process_Declarations (Variant : Node_Id) is
4385       begin
4386          if not Null_Present (Component_List (Variant)) then
4387             Analyze_Declarations (Component_Items (Component_List (Variant)));
4388
4389             if Present (Variant_Part (Component_List (Variant))) then
4390                Analyze (Variant_Part (Component_List (Variant)));
4391             end if;
4392          end if;
4393       end Process_Declarations;
4394
4395       --  Local Variables
4396
4397       Discr_Name : Node_Id;
4398       Discr_Type : Entity_Id;
4399
4400       Dont_Care      : Boolean;
4401       Others_Present : Boolean := False;
4402
4403       pragma Warnings (Off, Dont_Care);
4404       pragma Warnings (Off, Others_Present);
4405       --  We don't care about the assigned values of any of these
4406
4407    --  Start of processing for Analyze_Variant_Part
4408
4409    begin
4410       Discr_Name := Name (N);
4411       Analyze (Discr_Name);
4412
4413       --  If Discr_Name bad, get out (prevent cascaded errors)
4414
4415       if Etype (Discr_Name) = Any_Type then
4416          return;
4417       end if;
4418
4419       --  Check invalid discriminant in variant part
4420
4421       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4422          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4423       end if;
4424
4425       Discr_Type := Etype (Entity (Discr_Name));
4426
4427       if not Is_Discrete_Type (Discr_Type) then
4428          Error_Msg_N
4429            ("discriminant in a variant part must be of a discrete type",
4430              Name (N));
4431          return;
4432       end if;
4433
4434       --  Call the instantiated Analyze_Choices which does the rest of the work
4435
4436       Analyze_Choices (N, Discr_Type, Dont_Care, Others_Present);
4437    end Analyze_Variant_Part;
4438
4439    ----------------------------
4440    -- Array_Type_Declaration --
4441    ----------------------------
4442
4443    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4444       Component_Def : constant Node_Id := Component_Definition (Def);
4445       Element_Type  : Entity_Id;
4446       Implicit_Base : Entity_Id;
4447       Index         : Node_Id;
4448       Related_Id    : Entity_Id := Empty;
4449       Nb_Index      : Nat;
4450       P             : constant Node_Id := Parent (Def);
4451       Priv          : Entity_Id;
4452
4453    begin
4454       if Nkind (Def) = N_Constrained_Array_Definition then
4455          Index := First (Discrete_Subtype_Definitions (Def));
4456       else
4457          Index := First (Subtype_Marks (Def));
4458       end if;
4459
4460       --  Find proper names for the implicit types which may be public. In case
4461       --  of anonymous arrays we use the name of the first object of that type
4462       --  as prefix.
4463
4464       if No (T) then
4465          Related_Id :=  Defining_Identifier (P);
4466       else
4467          Related_Id := T;
4468       end if;
4469
4470       Nb_Index := 1;
4471       while Present (Index) loop
4472          Analyze (Index);
4473
4474          --  Add a subtype declaration for each index of private array type
4475          --  declaration whose etype is also private. For example:
4476
4477          --     package Pkg is
4478          --        type Index is private;
4479          --     private
4480          --        type Table is array (Index) of ...
4481          --     end;
4482
4483          --  This is currently required by the expander for the internally
4484          --  generated equality subprogram of records with variant parts in
4485          --  which the etype of some component is such private type.
4486
4487          if Ekind (Current_Scope) = E_Package
4488            and then In_Private_Part (Current_Scope)
4489            and then Has_Private_Declaration (Etype (Index))
4490          then
4491             declare
4492                Loc   : constant Source_Ptr := Sloc (Def);
4493                New_E : Entity_Id;
4494                Decl  : Entity_Id;
4495
4496             begin
4497                New_E := Make_Temporary (Loc, 'T');
4498                Set_Is_Internal (New_E);
4499
4500                Decl :=
4501                  Make_Subtype_Declaration (Loc,
4502                    Defining_Identifier => New_E,
4503                    Subtype_Indication  =>
4504                      New_Occurrence_Of (Etype (Index), Loc));
4505
4506                Insert_Before (Parent (Def), Decl);
4507                Analyze (Decl);
4508                Set_Etype (Index, New_E);
4509
4510                --  If the index is a range the Entity attribute is not
4511                --  available. Example:
4512
4513                --     package Pkg is
4514                --        type T is private;
4515                --     private
4516                --        type T is new Natural;
4517                --        Table : array (T(1) .. T(10)) of Boolean;
4518                --     end Pkg;
4519
4520                if Nkind (Index) /= N_Range then
4521                   Set_Entity (Index, New_E);
4522                end if;
4523             end;
4524          end if;
4525
4526          Make_Index (Index, P, Related_Id, Nb_Index);
4527
4528          --  Check error of subtype with predicate for index type
4529
4530          Bad_Predicated_Subtype_Use
4531            ("subtype& has predicate, not allowed as index subtype",
4532             Index, Etype (Index));
4533
4534          --  Move to next index
4535
4536          Next_Index (Index);
4537          Nb_Index := Nb_Index + 1;
4538       end loop;
4539
4540       --  Process subtype indication if one is present
4541
4542       if Present (Subtype_Indication (Component_Def)) then
4543          Element_Type :=
4544            Process_Subtype
4545              (Subtype_Indication (Component_Def), P, Related_Id, 'C');
4546
4547       --  Ada 2005 (AI-230): Access Definition case
4548
4549       else pragma Assert (Present (Access_Definition (Component_Def)));
4550
4551          --  Indicate that the anonymous access type is created by the
4552          --  array type declaration.
4553
4554          Element_Type := Access_Definition
4555                            (Related_Nod => P,
4556                             N           => Access_Definition (Component_Def));
4557          Set_Is_Local_Anonymous_Access (Element_Type);
4558
4559          --  Propagate the parent. This field is needed if we have to generate
4560          --  the master_id associated with an anonymous access to task type
4561          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4562
4563          Set_Parent (Element_Type, Parent (T));
4564
4565          --  Ada 2005 (AI-230): In case of components that are anonymous access
4566          --  types the level of accessibility depends on the enclosing type
4567          --  declaration
4568
4569          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4570
4571          --  Ada 2005 (AI-254)
4572
4573          declare
4574             CD : constant Node_Id :=
4575                    Access_To_Subprogram_Definition
4576                      (Access_Definition (Component_Def));
4577          begin
4578             if Present (CD) and then Protected_Present (CD) then
4579                Element_Type :=
4580                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4581             end if;
4582          end;
4583       end if;
4584
4585       --  Constrained array case
4586
4587       if No (T) then
4588          T := Create_Itype (E_Void, P, Related_Id, 'T');
4589       end if;
4590
4591       if Nkind (Def) = N_Constrained_Array_Definition then
4592
4593          --  Establish Implicit_Base as unconstrained base type
4594
4595          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4596
4597          Set_Etype              (Implicit_Base, Implicit_Base);
4598          Set_Scope              (Implicit_Base, Current_Scope);
4599          Set_Has_Delayed_Freeze (Implicit_Base);
4600
4601          --  The constrained array type is a subtype of the unconstrained one
4602
4603          Set_Ekind          (T, E_Array_Subtype);
4604          Init_Size_Align    (T);
4605          Set_Etype          (T, Implicit_Base);
4606          Set_Scope          (T, Current_Scope);
4607          Set_Is_Constrained (T, True);
4608          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4609          Set_Has_Delayed_Freeze (T);
4610
4611          --  Complete setup of implicit base type
4612
4613          Set_First_Index       (Implicit_Base, First_Index (T));
4614          Set_Component_Type    (Implicit_Base, Element_Type);
4615          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4616          Set_Component_Size    (Implicit_Base, Uint_0);
4617          Set_Packed_Array_Type (Implicit_Base, Empty);
4618          Set_Has_Controlled_Component
4619                                (Implicit_Base, Has_Controlled_Component
4620                                                         (Element_Type)
4621                                                  or else Is_Controlled
4622                                                         (Element_Type));
4623          Set_Finalize_Storage_Only
4624                                (Implicit_Base, Finalize_Storage_Only
4625                                                         (Element_Type));
4626
4627       --  Unconstrained array case
4628
4629       else
4630          Set_Ekind                    (T, E_Array_Type);
4631          Init_Size_Align              (T);
4632          Set_Etype                    (T, T);
4633          Set_Scope                    (T, Current_Scope);
4634          Set_Component_Size           (T, Uint_0);
4635          Set_Is_Constrained           (T, False);
4636          Set_First_Index              (T, First (Subtype_Marks (Def)));
4637          Set_Has_Delayed_Freeze       (T, True);
4638          Set_Has_Task                 (T, Has_Task      (Element_Type));
4639          Set_Has_Controlled_Component (T, Has_Controlled_Component
4640                                                         (Element_Type)
4641                                             or else
4642                                           Is_Controlled (Element_Type));
4643          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4644                                                         (Element_Type));
4645       end if;
4646
4647       --  Common attributes for both cases
4648
4649       Set_Component_Type (Base_Type (T), Element_Type);
4650       Set_Packed_Array_Type (T, Empty);
4651
4652       if Aliased_Present (Component_Definition (Def)) then
4653          Set_Has_Aliased_Components (Etype (T));
4654       end if;
4655
4656       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4657       --  array type to ensure that objects of this type are initialized.
4658
4659       if Ada_Version >= Ada_2005
4660         and then Can_Never_Be_Null (Element_Type)
4661       then
4662          Set_Can_Never_Be_Null (T);
4663
4664          if Null_Exclusion_Present (Component_Definition (Def))
4665
4666             --  No need to check itypes because in their case this check was
4667             --  done at their point of creation
4668
4669            and then not Is_Itype (Element_Type)
4670          then
4671             Error_Msg_N
4672               ("`NOT NULL` not allowed (null already excluded)",
4673                Subtype_Indication (Component_Definition (Def)));
4674          end if;
4675       end if;
4676
4677       Priv := Private_Component (Element_Type);
4678
4679       if Present (Priv) then
4680
4681          --  Check for circular definitions
4682
4683          if Priv = Any_Type then
4684             Set_Component_Type (Etype (T), Any_Type);
4685
4686          --  There is a gap in the visibility of operations on the composite
4687          --  type only if the component type is defined in a different scope.
4688
4689          elsif Scope (Priv) = Current_Scope then
4690             null;
4691
4692          elsif Is_Limited_Type (Priv) then
4693             Set_Is_Limited_Composite (Etype (T));
4694             Set_Is_Limited_Composite (T);
4695          else
4696             Set_Is_Private_Composite (Etype (T));
4697             Set_Is_Private_Composite (T);
4698          end if;
4699       end if;
4700
4701       --  A syntax error in the declaration itself may lead to an empty index
4702       --  list, in which case do a minimal patch.
4703
4704       if No (First_Index (T)) then
4705          Error_Msg_N ("missing index definition in array type declaration", T);
4706
4707          declare
4708             Indexes : constant List_Id :=
4709                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4710          begin
4711             Set_Discrete_Subtype_Definitions (Def, Indexes);
4712             Set_First_Index (T, First (Indexes));
4713             return;
4714          end;
4715       end if;
4716
4717       --  Create a concatenation operator for the new type. Internal array
4718       --  types created for packed entities do not need such, they are
4719       --  compatible with the user-defined type.
4720
4721       if Number_Dimensions (T) = 1
4722          and then not Is_Packed_Array_Type (T)
4723       then
4724          New_Concatenation_Op (T);
4725       end if;
4726
4727       --  In the case of an unconstrained array the parser has already verified
4728       --  that all the indexes are unconstrained but we still need to make sure
4729       --  that the element type is constrained.
4730
4731       if Is_Indefinite_Subtype (Element_Type) then
4732          Error_Msg_N
4733            ("unconstrained element type in array declaration",
4734             Subtype_Indication (Component_Def));
4735
4736       elsif Is_Abstract_Type (Element_Type) then
4737          Error_Msg_N
4738            ("the type of a component cannot be abstract",
4739             Subtype_Indication (Component_Def));
4740       end if;
4741    end Array_Type_Declaration;
4742
4743    ------------------------------------------------------
4744    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4745    ------------------------------------------------------
4746
4747    function Replace_Anonymous_Access_To_Protected_Subprogram
4748      (N : Node_Id) return Entity_Id
4749    is
4750       Loc : constant Source_Ptr := Sloc (N);
4751
4752       Curr_Scope : constant Scope_Stack_Entry :=
4753                      Scope_Stack.Table (Scope_Stack.Last);
4754
4755       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
4756       Acc  : Node_Id;
4757       Comp : Node_Id;
4758       Decl : Node_Id;
4759       P    : Node_Id;
4760
4761    begin
4762       Set_Is_Internal (Anon);
4763
4764       case Nkind (N) is
4765          when N_Component_Declaration       |
4766            N_Unconstrained_Array_Definition |
4767            N_Constrained_Array_Definition   =>
4768             Comp := Component_Definition (N);
4769             Acc  := Access_Definition (Comp);
4770
4771          when N_Discriminant_Specification =>
4772             Comp := Discriminant_Type (N);
4773             Acc  := Comp;
4774
4775          when N_Parameter_Specification =>
4776             Comp := Parameter_Type (N);
4777             Acc  := Comp;
4778
4779          when N_Access_Function_Definition  =>
4780             Comp := Result_Definition (N);
4781             Acc  := Comp;
4782
4783          when N_Object_Declaration  =>
4784             Comp := Object_Definition (N);
4785             Acc  := Comp;
4786
4787          when N_Function_Specification =>
4788             Comp := Result_Definition (N);
4789             Acc  := Comp;
4790
4791          when others =>
4792             raise Program_Error;
4793       end case;
4794
4795       Decl := Make_Full_Type_Declaration (Loc,
4796                 Defining_Identifier => Anon,
4797                 Type_Definition   =>
4798                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
4799
4800       Mark_Rewrite_Insertion (Decl);
4801
4802       --  Insert the new declaration in the nearest enclosing scope. If the
4803       --  node is a body and N is its return type, the declaration belongs in
4804       --  the enclosing scope.
4805
4806       P := Parent (N);
4807
4808       if Nkind (P) = N_Subprogram_Body
4809         and then Nkind (N) = N_Function_Specification
4810       then
4811          P := Parent (P);
4812       end if;
4813
4814       while Present (P) and then not Has_Declarations (P) loop
4815          P := Parent (P);
4816       end loop;
4817
4818       pragma Assert (Present (P));
4819
4820       if Nkind (P) = N_Package_Specification then
4821          Prepend (Decl, Visible_Declarations (P));
4822       else
4823          Prepend (Decl, Declarations (P));
4824       end if;
4825
4826       --  Replace the anonymous type with an occurrence of the new declaration.
4827       --  In all cases the rewritten node does not have the null-exclusion
4828       --  attribute because (if present) it was already inherited by the
4829       --  anonymous entity (Anon). Thus, in case of components we do not
4830       --  inherit this attribute.
4831
4832       if Nkind (N) = N_Parameter_Specification then
4833          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4834          Set_Etype (Defining_Identifier (N), Anon);
4835          Set_Null_Exclusion_Present (N, False);
4836
4837       elsif Nkind (N) = N_Object_Declaration then
4838          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4839          Set_Etype (Defining_Identifier (N), Anon);
4840
4841       elsif Nkind (N) = N_Access_Function_Definition then
4842          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4843
4844       elsif Nkind (N) = N_Function_Specification then
4845          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4846          Set_Etype (Defining_Unit_Name (N), Anon);
4847
4848       else
4849          Rewrite (Comp,
4850            Make_Component_Definition (Loc,
4851              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
4852       end if;
4853
4854       Mark_Rewrite_Insertion (Comp);
4855
4856       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
4857          Analyze (Decl);
4858
4859       else
4860          --  Temporarily remove the current scope (record or subprogram) from
4861          --  the stack to add the new declarations to the enclosing scope.
4862
4863          Scope_Stack.Decrement_Last;
4864          Analyze (Decl);
4865          Set_Is_Itype (Anon);
4866          Scope_Stack.Append (Curr_Scope);
4867       end if;
4868
4869       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
4870       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
4871       return Anon;
4872    end Replace_Anonymous_Access_To_Protected_Subprogram;
4873
4874    -------------------------------
4875    -- Build_Derived_Access_Type --
4876    -------------------------------
4877
4878    procedure Build_Derived_Access_Type
4879      (N            : Node_Id;
4880       Parent_Type  : Entity_Id;
4881       Derived_Type : Entity_Id)
4882    is
4883       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
4884
4885       Desig_Type      : Entity_Id;
4886       Discr           : Entity_Id;
4887       Discr_Con_Elist : Elist_Id;
4888       Discr_Con_El    : Elmt_Id;
4889       Subt            : Entity_Id;
4890
4891    begin
4892       --  Set the designated type so it is available in case this is an access
4893       --  to a self-referential type, e.g. a standard list type with a next
4894       --  pointer. Will be reset after subtype is built.
4895
4896       Set_Directly_Designated_Type
4897         (Derived_Type, Designated_Type (Parent_Type));
4898
4899       Subt := Process_Subtype (S, N);
4900
4901       if Nkind (S) /= N_Subtype_Indication
4902         and then Subt /= Base_Type (Subt)
4903       then
4904          Set_Ekind (Derived_Type, E_Access_Subtype);
4905       end if;
4906
4907       if Ekind (Derived_Type) = E_Access_Subtype then
4908          declare
4909             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
4910             Ibase      : constant Entity_Id :=
4911                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
4912             Svg_Chars  : constant Name_Id   := Chars (Ibase);
4913             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
4914
4915          begin
4916             Copy_Node (Pbase, Ibase);
4917
4918             Set_Chars             (Ibase, Svg_Chars);
4919             Set_Next_Entity       (Ibase, Svg_Next_E);
4920             Set_Sloc              (Ibase, Sloc (Derived_Type));
4921             Set_Scope             (Ibase, Scope (Derived_Type));
4922             Set_Freeze_Node       (Ibase, Empty);
4923             Set_Is_Frozen         (Ibase, False);
4924             Set_Comes_From_Source (Ibase, False);
4925             Set_Is_First_Subtype  (Ibase, False);
4926
4927             Set_Etype (Ibase, Pbase);
4928             Set_Etype (Derived_Type, Ibase);
4929          end;
4930       end if;
4931
4932       Set_Directly_Designated_Type
4933         (Derived_Type, Designated_Type (Subt));
4934
4935       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
4936       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
4937       Set_Size_Info          (Derived_Type,                     Parent_Type);
4938       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
4939       Set_Depends_On_Private (Derived_Type,
4940                               Has_Private_Component (Derived_Type));
4941       Conditional_Delay      (Derived_Type, Subt);
4942
4943       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
4944       --  that it is not redundant.
4945
4946       if Null_Exclusion_Present (Type_Definition (N)) then
4947          Set_Can_Never_Be_Null (Derived_Type);
4948
4949          if Can_Never_Be_Null (Parent_Type)
4950            and then False
4951          then
4952             Error_Msg_NE
4953               ("`NOT NULL` not allowed (& already excludes null)",
4954                 N, Parent_Type);
4955          end if;
4956
4957       elsif Can_Never_Be_Null (Parent_Type) then
4958          Set_Can_Never_Be_Null (Derived_Type);
4959       end if;
4960
4961       --  Note: we do not copy the Storage_Size_Variable, since we always go to
4962       --  the root type for this information.
4963
4964       --  Apply range checks to discriminants for derived record case
4965       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
4966
4967       Desig_Type := Designated_Type (Derived_Type);
4968       if Is_Composite_Type (Desig_Type)
4969         and then (not Is_Array_Type (Desig_Type))
4970         and then Has_Discriminants (Desig_Type)
4971         and then Base_Type (Desig_Type) /= Desig_Type
4972       then
4973          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
4974          Discr_Con_El := First_Elmt (Discr_Con_Elist);
4975
4976          Discr := First_Discriminant (Base_Type (Desig_Type));
4977          while Present (Discr_Con_El) loop
4978             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
4979             Next_Elmt (Discr_Con_El);
4980             Next_Discriminant (Discr);
4981          end loop;
4982       end if;
4983    end Build_Derived_Access_Type;
4984
4985    ------------------------------
4986    -- Build_Derived_Array_Type --
4987    ------------------------------
4988
4989    procedure Build_Derived_Array_Type
4990      (N            : Node_Id;
4991       Parent_Type  : Entity_Id;
4992       Derived_Type : Entity_Id)
4993    is
4994       Loc           : constant Source_Ptr := Sloc (N);
4995       Tdef          : constant Node_Id    := Type_Definition (N);
4996       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
4997       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
4998       Implicit_Base : Entity_Id;
4999       New_Indic     : Node_Id;
5000
5001       procedure Make_Implicit_Base;
5002       --  If the parent subtype is constrained, the derived type is a subtype
5003       --  of an implicit base type derived from the parent base.
5004
5005       ------------------------
5006       -- Make_Implicit_Base --
5007       ------------------------
5008
5009       procedure Make_Implicit_Base is
5010       begin
5011          Implicit_Base :=
5012            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5013
5014          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
5015          Set_Etype (Implicit_Base, Parent_Base);
5016
5017          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
5018          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
5019
5020          Set_Has_Delayed_Freeze (Implicit_Base, True);
5021       end Make_Implicit_Base;
5022
5023    --  Start of processing for Build_Derived_Array_Type
5024
5025    begin
5026       if not Is_Constrained (Parent_Type) then
5027          if Nkind (Indic) /= N_Subtype_Indication then
5028             Set_Ekind (Derived_Type, E_Array_Type);
5029
5030             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
5031             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
5032
5033             Set_Has_Delayed_Freeze (Derived_Type, True);
5034
5035          else
5036             Make_Implicit_Base;
5037             Set_Etype (Derived_Type, Implicit_Base);
5038
5039             New_Indic :=
5040               Make_Subtype_Declaration (Loc,
5041                 Defining_Identifier => Derived_Type,
5042                 Subtype_Indication  =>
5043                   Make_Subtype_Indication (Loc,
5044                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
5045                     Constraint => Constraint (Indic)));
5046
5047             Rewrite (N, New_Indic);
5048             Analyze (N);
5049          end if;
5050
5051       else
5052          if Nkind (Indic) /= N_Subtype_Indication then
5053             Make_Implicit_Base;
5054
5055             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
5056             Set_Etype             (Derived_Type, Implicit_Base);
5057             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
5058
5059          else
5060             Error_Msg_N ("illegal constraint on constrained type", Indic);
5061          end if;
5062       end if;
5063
5064       --  If parent type is not a derived type itself, and is declared in
5065       --  closed scope (e.g. a subprogram), then we must explicitly introduce
5066       --  the new type's concatenation operator since Derive_Subprograms
5067       --  will not inherit the parent's operator. If the parent type is
5068       --  unconstrained, the operator is of the unconstrained base type.
5069
5070       if Number_Dimensions (Parent_Type) = 1
5071         and then not Is_Limited_Type (Parent_Type)
5072         and then not Is_Derived_Type (Parent_Type)
5073         and then not Is_Package_Or_Generic_Package
5074                        (Scope (Base_Type (Parent_Type)))
5075       then
5076          if not Is_Constrained (Parent_Type)
5077            and then Is_Constrained (Derived_Type)
5078          then
5079             New_Concatenation_Op (Implicit_Base);
5080          else
5081             New_Concatenation_Op (Derived_Type);
5082          end if;
5083       end if;
5084    end Build_Derived_Array_Type;
5085
5086    -----------------------------------
5087    -- Build_Derived_Concurrent_Type --
5088    -----------------------------------
5089
5090    procedure Build_Derived_Concurrent_Type
5091      (N            : Node_Id;
5092       Parent_Type  : Entity_Id;
5093       Derived_Type : Entity_Id)
5094    is
5095       Loc : constant Source_Ptr := Sloc (N);
5096
5097       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
5098       Corr_Decl        : Node_Id;
5099       Corr_Decl_Needed : Boolean;
5100       --  If the derived type has fewer discriminants than its parent, the
5101       --  corresponding record is also a derived type, in order to account for
5102       --  the bound discriminants. We create a full type declaration for it in
5103       --  this case.
5104
5105       Constraint_Present : constant Boolean :=
5106                              Nkind (Subtype_Indication (Type_Definition (N))) =
5107                                                           N_Subtype_Indication;
5108
5109       D_Constraint   : Node_Id;
5110       New_Constraint : Elist_Id;
5111       Old_Disc       : Entity_Id;
5112       New_Disc       : Entity_Id;
5113       New_N          : Node_Id;
5114
5115    begin
5116       Set_Stored_Constraint (Derived_Type, No_Elist);
5117       Corr_Decl_Needed := False;
5118       Old_Disc := Empty;
5119
5120       if Present (Discriminant_Specifications (N))
5121         and then Constraint_Present
5122       then
5123          Old_Disc := First_Discriminant (Parent_Type);
5124          New_Disc := First (Discriminant_Specifications (N));
5125          while Present (New_Disc) and then Present (Old_Disc) loop
5126             Next_Discriminant (Old_Disc);
5127             Next (New_Disc);
5128          end loop;
5129       end if;
5130
5131       if Present (Old_Disc) and then Expander_Active then
5132
5133          --  The new type has fewer discriminants, so we need to create a new
5134          --  corresponding record, which is derived from the corresponding
5135          --  record of the parent, and has a stored constraint that captures
5136          --  the values of the discriminant constraints. The corresponding
5137          --  record is needed only if expander is active and code generation is
5138          --  enabled.
5139
5140          --  The type declaration for the derived corresponding record has the
5141          --  same discriminant part and constraints as the current declaration.
5142          --  Copy the unanalyzed tree to build declaration.
5143
5144          Corr_Decl_Needed := True;
5145          New_N := Copy_Separate_Tree (N);
5146
5147          Corr_Decl :=
5148            Make_Full_Type_Declaration (Loc,
5149              Defining_Identifier         => Corr_Record,
5150              Discriminant_Specifications =>
5151                 Discriminant_Specifications (New_N),
5152              Type_Definition             =>
5153                Make_Derived_Type_Definition (Loc,
5154                  Subtype_Indication =>
5155                    Make_Subtype_Indication (Loc,
5156                      Subtype_Mark =>
5157                         New_Occurrence_Of
5158                           (Corresponding_Record_Type (Parent_Type), Loc),
5159                      Constraint   =>
5160                        Constraint
5161                          (Subtype_Indication (Type_Definition (New_N))))));
5162       end if;
5163
5164       --  Copy Storage_Size and Relative_Deadline variables if task case
5165
5166       if Is_Task_Type (Parent_Type) then
5167          Set_Storage_Size_Variable (Derived_Type,
5168            Storage_Size_Variable (Parent_Type));
5169          Set_Relative_Deadline_Variable (Derived_Type,
5170            Relative_Deadline_Variable (Parent_Type));
5171       end if;
5172
5173       if Present (Discriminant_Specifications (N)) then
5174          Push_Scope (Derived_Type);
5175          Check_Or_Process_Discriminants (N, Derived_Type);
5176
5177          if Constraint_Present then
5178             New_Constraint :=
5179               Expand_To_Stored_Constraint
5180                 (Parent_Type,
5181                  Build_Discriminant_Constraints
5182                    (Parent_Type,
5183                     Subtype_Indication (Type_Definition (N)), True));
5184          end if;
5185
5186          End_Scope;
5187
5188       elsif Constraint_Present then
5189
5190          --  Build constrained subtype and derive from it
5191
5192          declare
5193             Loc  : constant Source_Ptr := Sloc (N);
5194             Anon : constant Entity_Id :=
5195                      Make_Defining_Identifier (Loc,
5196                        Chars => New_External_Name (Chars (Derived_Type), 'T'));
5197             Decl : Node_Id;
5198
5199          begin
5200             Decl :=
5201               Make_Subtype_Declaration (Loc,
5202                 Defining_Identifier => Anon,
5203                 Subtype_Indication =>
5204                   Subtype_Indication (Type_Definition (N)));
5205             Insert_Before (N, Decl);
5206             Analyze (Decl);
5207
5208             Rewrite (Subtype_Indication (Type_Definition (N)),
5209               New_Occurrence_Of (Anon, Loc));
5210             Set_Analyzed (Derived_Type, False);
5211             Analyze (N);
5212             return;
5213          end;
5214       end if;
5215
5216       --  By default, operations and private data are inherited from parent.
5217       --  However, in the presence of bound discriminants, a new corresponding
5218       --  record will be created, see below.
5219
5220       Set_Has_Discriminants
5221         (Derived_Type, Has_Discriminants         (Parent_Type));
5222       Set_Corresponding_Record_Type
5223         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5224
5225       --  Is_Constrained is set according the parent subtype, but is set to
5226       --  False if the derived type is declared with new discriminants.
5227
5228       Set_Is_Constrained
5229         (Derived_Type,
5230          (Is_Constrained (Parent_Type) or else Constraint_Present)
5231            and then not Present (Discriminant_Specifications (N)));
5232
5233       if Constraint_Present then
5234          if not Has_Discriminants (Parent_Type) then
5235             Error_Msg_N ("untagged parent must have discriminants", N);
5236
5237          elsif Present (Discriminant_Specifications (N)) then
5238
5239             --  Verify that new discriminants are used to constrain old ones
5240
5241             D_Constraint :=
5242               First
5243                 (Constraints
5244                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5245
5246             Old_Disc := First_Discriminant (Parent_Type);
5247
5248             while Present (D_Constraint) loop
5249                if Nkind (D_Constraint) /= N_Discriminant_Association then
5250
5251                   --  Positional constraint. If it is a reference to a new
5252                   --  discriminant, it constrains the corresponding old one.
5253
5254                   if Nkind (D_Constraint) = N_Identifier then
5255                      New_Disc := First_Discriminant (Derived_Type);
5256                      while Present (New_Disc) loop
5257                         exit when Chars (New_Disc) = Chars (D_Constraint);
5258                         Next_Discriminant (New_Disc);
5259                      end loop;
5260
5261                      if Present (New_Disc) then
5262                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5263                      end if;
5264                   end if;
5265
5266                   Next_Discriminant (Old_Disc);
5267
5268                   --  if this is a named constraint, search by name for the old
5269                   --  discriminants constrained by the new one.
5270
5271                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5272
5273                   --  Find new discriminant with that name
5274
5275                   New_Disc := First_Discriminant (Derived_Type);
5276                   while Present (New_Disc) loop
5277                      exit when
5278                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5279                      Next_Discriminant (New_Disc);
5280                   end loop;
5281
5282                   if Present (New_Disc) then
5283
5284                      --  Verify that new discriminant renames some discriminant
5285                      --  of the parent type, and associate the new discriminant
5286                      --  with one or more old ones that it renames.
5287
5288                      declare
5289                         Selector : Node_Id;
5290
5291                      begin
5292                         Selector := First (Selector_Names (D_Constraint));
5293                         while Present (Selector) loop
5294                            Old_Disc := First_Discriminant (Parent_Type);
5295                            while Present (Old_Disc) loop
5296                               exit when Chars (Old_Disc) = Chars (Selector);
5297                               Next_Discriminant (Old_Disc);
5298                            end loop;
5299
5300                            if Present (Old_Disc) then
5301                               Set_Corresponding_Discriminant
5302                                 (New_Disc, Old_Disc);
5303                            end if;
5304
5305                            Next (Selector);
5306                         end loop;
5307                      end;
5308                   end if;
5309                end if;
5310
5311                Next (D_Constraint);
5312             end loop;
5313
5314             New_Disc := First_Discriminant (Derived_Type);
5315             while Present (New_Disc) loop
5316                if No (Corresponding_Discriminant (New_Disc)) then
5317                   Error_Msg_NE
5318                     ("new discriminant& must constrain old one", N, New_Disc);
5319
5320                elsif not
5321                  Subtypes_Statically_Compatible
5322                    (Etype (New_Disc),
5323                     Etype (Corresponding_Discriminant (New_Disc)))
5324                then
5325                   Error_Msg_NE
5326                     ("& not statically compatible with parent discriminant",
5327                       N, New_Disc);
5328                end if;
5329
5330                Next_Discriminant (New_Disc);
5331             end loop;
5332          end if;
5333
5334       elsif Present (Discriminant_Specifications (N)) then
5335          Error_Msg_N
5336            ("missing discriminant constraint in untagged derivation", N);
5337       end if;
5338
5339       --  The entity chain of the derived type includes the new discriminants
5340       --  but shares operations with the parent.
5341
5342       if Present (Discriminant_Specifications (N)) then
5343          Old_Disc := First_Discriminant (Parent_Type);
5344          while Present (Old_Disc) loop
5345             if No (Next_Entity (Old_Disc))
5346               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5347             then
5348                Set_Next_Entity
5349                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5350                exit;
5351             end if;
5352
5353             Next_Discriminant (Old_Disc);
5354          end loop;
5355
5356       else
5357          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5358          if Has_Discriminants (Parent_Type) then
5359             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5360             Set_Discriminant_Constraint (
5361               Derived_Type, Discriminant_Constraint (Parent_Type));
5362          end if;
5363       end if;
5364
5365       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5366
5367       Set_Has_Completion (Derived_Type);
5368
5369       if Corr_Decl_Needed then
5370          Set_Stored_Constraint (Derived_Type, New_Constraint);
5371          Insert_After (N, Corr_Decl);
5372          Analyze (Corr_Decl);
5373          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5374       end if;
5375    end Build_Derived_Concurrent_Type;
5376
5377    ------------------------------------
5378    -- Build_Derived_Enumeration_Type --
5379    ------------------------------------
5380
5381    procedure Build_Derived_Enumeration_Type
5382      (N            : Node_Id;
5383       Parent_Type  : Entity_Id;
5384       Derived_Type : Entity_Id)
5385    is
5386       Loc           : constant Source_Ptr := Sloc (N);
5387       Def           : constant Node_Id    := Type_Definition (N);
5388       Indic         : constant Node_Id    := Subtype_Indication (Def);
5389       Implicit_Base : Entity_Id;
5390       Literal       : Entity_Id;
5391       New_Lit       : Entity_Id;
5392       Literals_List : List_Id;
5393       Type_Decl     : Node_Id;
5394       Hi, Lo        : Node_Id;
5395       Rang_Expr     : Node_Id;
5396
5397    begin
5398       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5399       --  not have explicit literals lists we need to process types derived
5400       --  from them specially. This is handled by Derived_Standard_Character.
5401       --  If the parent type is a generic type, there are no literals either,
5402       --  and we construct the same skeletal representation as for the generic
5403       --  parent type.
5404
5405       if Is_Standard_Character_Type (Parent_Type) then
5406          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5407
5408       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5409          declare
5410             Lo : Node_Id;
5411             Hi : Node_Id;
5412
5413          begin
5414             if Nkind (Indic) /= N_Subtype_Indication then
5415                Lo :=
5416                   Make_Attribute_Reference (Loc,
5417                     Attribute_Name => Name_First,
5418                     Prefix         => New_Reference_To (Derived_Type, Loc));
5419                Set_Etype (Lo, Derived_Type);
5420
5421                Hi :=
5422                   Make_Attribute_Reference (Loc,
5423                     Attribute_Name => Name_Last,
5424                     Prefix         => New_Reference_To (Derived_Type, Loc));
5425                Set_Etype (Hi, Derived_Type);
5426
5427                Set_Scalar_Range (Derived_Type,
5428                   Make_Range (Loc,
5429                     Low_Bound  => Lo,
5430                     High_Bound => Hi));
5431             else
5432
5433                --   Analyze subtype indication and verify compatibility
5434                --   with parent type.
5435
5436                if Base_Type (Process_Subtype (Indic, N)) /=
5437                   Base_Type (Parent_Type)
5438                then
5439                   Error_Msg_N
5440                     ("illegal constraint for formal discrete type", N);
5441                end if;
5442             end if;
5443          end;
5444
5445       else
5446          --  If a constraint is present, analyze the bounds to catch
5447          --  premature usage of the derived literals.
5448
5449          if Nkind (Indic) = N_Subtype_Indication
5450            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5451          then
5452             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5453             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5454          end if;
5455
5456          --  Introduce an implicit base type for the derived type even if there
5457          --  is no constraint attached to it, since this seems closer to the
5458          --  Ada semantics. Build a full type declaration tree for the derived
5459          --  type using the implicit base type as the defining identifier. The
5460          --  build a subtype declaration tree which applies the constraint (if
5461          --  any) have it replace the derived type declaration.
5462
5463          Literal := First_Literal (Parent_Type);
5464          Literals_List := New_List;
5465          while Present (Literal)
5466            and then Ekind (Literal) = E_Enumeration_Literal
5467          loop
5468             --  Literals of the derived type have the same representation as
5469             --  those of the parent type, but this representation can be
5470             --  overridden by an explicit representation clause. Indicate
5471             --  that there is no explicit representation given yet. These
5472             --  derived literals are implicit operations of the new type,
5473             --  and can be overridden by explicit ones.
5474
5475             if Nkind (Literal) = N_Defining_Character_Literal then
5476                New_Lit :=
5477                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5478             else
5479                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5480             end if;
5481
5482             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5483             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5484             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5485             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5486             Set_Alias                (New_Lit, Literal);
5487             Set_Is_Known_Valid       (New_Lit, True);
5488
5489             Append (New_Lit, Literals_List);
5490             Next_Literal (Literal);
5491          end loop;
5492
5493          Implicit_Base :=
5494            Make_Defining_Identifier (Sloc (Derived_Type),
5495              Chars => New_External_Name (Chars (Derived_Type), 'B'));
5496
5497          --  Indicate the proper nature of the derived type. This must be done
5498          --  before analysis of the literals, to recognize cases when a literal
5499          --  may be hidden by a previous explicit function definition (cf.
5500          --  c83031a).
5501
5502          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5503          Set_Etype (Derived_Type, Implicit_Base);
5504
5505          Type_Decl :=
5506            Make_Full_Type_Declaration (Loc,
5507              Defining_Identifier => Implicit_Base,
5508              Discriminant_Specifications => No_List,
5509              Type_Definition =>
5510                Make_Enumeration_Type_Definition (Loc, Literals_List));
5511
5512          Mark_Rewrite_Insertion (Type_Decl);
5513          Insert_Before (N, Type_Decl);
5514          Analyze (Type_Decl);
5515
5516          --  After the implicit base is analyzed its Etype needs to be changed
5517          --  to reflect the fact that it is derived from the parent type which
5518          --  was ignored during analysis. We also set the size at this point.
5519
5520          Set_Etype (Implicit_Base, Parent_Type);
5521
5522          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5523          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5524          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5525
5526          --  Copy other flags from parent type
5527
5528          Set_Has_Non_Standard_Rep
5529                             (Implicit_Base, Has_Non_Standard_Rep
5530                                                            (Parent_Type));
5531          Set_Has_Pragma_Ordered
5532                             (Implicit_Base, Has_Pragma_Ordered
5533                                                            (Parent_Type));
5534          Set_Has_Delayed_Freeze (Implicit_Base);
5535
5536          --  Process the subtype indication including a validation check on the
5537          --  constraint, if any. If a constraint is given, its bounds must be
5538          --  implicitly converted to the new type.
5539
5540          if Nkind (Indic) = N_Subtype_Indication then
5541             declare
5542                R : constant Node_Id :=
5543                      Range_Expression (Constraint (Indic));
5544
5545             begin
5546                if Nkind (R) = N_Range then
5547                   Hi := Build_Scalar_Bound
5548                           (High_Bound (R), Parent_Type, Implicit_Base);
5549                   Lo := Build_Scalar_Bound
5550                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5551
5552                else
5553                   --  Constraint is a Range attribute. Replace with explicit
5554                   --  mention of the bounds of the prefix, which must be a
5555                   --  subtype.
5556
5557                   Analyze (Prefix (R));
5558                   Hi :=
5559                     Convert_To (Implicit_Base,
5560                       Make_Attribute_Reference (Loc,
5561                         Attribute_Name => Name_Last,
5562                         Prefix =>
5563                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5564
5565                   Lo :=
5566                     Convert_To (Implicit_Base,
5567                       Make_Attribute_Reference (Loc,
5568                         Attribute_Name => Name_First,
5569                         Prefix =>
5570                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5571                end if;
5572             end;
5573
5574          else
5575             Hi :=
5576               Build_Scalar_Bound
5577                 (Type_High_Bound (Parent_Type),
5578                  Parent_Type, Implicit_Base);
5579             Lo :=
5580                Build_Scalar_Bound
5581                  (Type_Low_Bound (Parent_Type),
5582                   Parent_Type, Implicit_Base);
5583          end if;
5584
5585          Rang_Expr :=
5586            Make_Range (Loc,
5587              Low_Bound  => Lo,
5588              High_Bound => Hi);
5589
5590          --  If we constructed a default range for the case where no range
5591          --  was given, then the expressions in the range must not freeze
5592          --  since they do not correspond to expressions in the source.
5593
5594          if Nkind (Indic) /= N_Subtype_Indication then
5595             Set_Must_Not_Freeze (Lo);
5596             Set_Must_Not_Freeze (Hi);
5597             Set_Must_Not_Freeze (Rang_Expr);
5598          end if;
5599
5600          Rewrite (N,
5601            Make_Subtype_Declaration (Loc,
5602              Defining_Identifier => Derived_Type,
5603              Subtype_Indication =>
5604                Make_Subtype_Indication (Loc,
5605                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
5606                  Constraint =>
5607                    Make_Range_Constraint (Loc,
5608                      Range_Expression => Rang_Expr))));
5609
5610          Analyze (N);
5611
5612          --  If pragma Discard_Names applies on the first subtype of the parent
5613          --  type, then it must be applied on this subtype as well.
5614
5615          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
5616             Set_Discard_Names (Derived_Type);
5617          end if;
5618
5619          --  Apply a range check. Since this range expression doesn't have an
5620          --  Etype, we have to specifically pass the Source_Typ parameter. Is
5621          --  this right???
5622
5623          if Nkind (Indic) = N_Subtype_Indication then
5624             Apply_Range_Check (Range_Expression (Constraint (Indic)),
5625                                Parent_Type,
5626                                Source_Typ => Entity (Subtype_Mark (Indic)));
5627          end if;
5628       end if;
5629    end Build_Derived_Enumeration_Type;
5630
5631    --------------------------------
5632    -- Build_Derived_Numeric_Type --
5633    --------------------------------
5634
5635    procedure Build_Derived_Numeric_Type
5636      (N            : Node_Id;
5637       Parent_Type  : Entity_Id;
5638       Derived_Type : Entity_Id)
5639    is
5640       Loc           : constant Source_Ptr := Sloc (N);
5641       Tdef          : constant Node_Id    := Type_Definition (N);
5642       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5643       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5644       No_Constraint : constant Boolean    := Nkind (Indic) /=
5645                                                   N_Subtype_Indication;
5646       Implicit_Base : Entity_Id;
5647
5648       Lo : Node_Id;
5649       Hi : Node_Id;
5650
5651    begin
5652       --  Process the subtype indication including a validation check on
5653       --  the constraint if any.
5654
5655       Discard_Node (Process_Subtype (Indic, N));
5656
5657       --  Introduce an implicit base type for the derived type even if there
5658       --  is no constraint attached to it, since this seems closer to the Ada
5659       --  semantics.
5660
5661       Implicit_Base :=
5662         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5663
5664       Set_Etype          (Implicit_Base, Parent_Base);
5665       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
5666       Set_Size_Info      (Implicit_Base,                 Parent_Base);
5667       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
5668       Set_Parent         (Implicit_Base, Parent (Derived_Type));
5669       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
5670
5671       --  Set RM Size for discrete type or decimal fixed-point type
5672       --  Ordinary fixed-point is excluded, why???
5673
5674       if Is_Discrete_Type (Parent_Base)
5675         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
5676       then
5677          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
5678       end if;
5679
5680       Set_Has_Delayed_Freeze (Implicit_Base);
5681
5682       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
5683       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
5684
5685       Set_Scalar_Range (Implicit_Base,
5686         Make_Range (Loc,
5687           Low_Bound  => Lo,
5688           High_Bound => Hi));
5689
5690       if Has_Infinities (Parent_Base) then
5691          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
5692       end if;
5693
5694       --  The Derived_Type, which is the entity of the declaration, is a
5695       --  subtype of the implicit base. Its Ekind is a subtype, even in the
5696       --  absence of an explicit constraint.
5697
5698       Set_Etype (Derived_Type, Implicit_Base);
5699
5700       --  If we did not have a constraint, then the Ekind is set from the
5701       --  parent type (otherwise Process_Subtype has set the bounds)
5702
5703       if No_Constraint then
5704          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
5705       end if;
5706
5707       --  If we did not have a range constraint, then set the range from the
5708       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
5709
5710       if No_Constraint
5711         or else not Has_Range_Constraint (Indic)
5712       then
5713          Set_Scalar_Range (Derived_Type,
5714            Make_Range (Loc,
5715              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
5716              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
5717          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5718
5719          if Has_Infinities (Parent_Type) then
5720             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5721          end if;
5722
5723          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
5724       end if;
5725
5726       Set_Is_Descendent_Of_Address (Derived_Type,
5727         Is_Descendent_Of_Address (Parent_Type));
5728       Set_Is_Descendent_Of_Address (Implicit_Base,
5729         Is_Descendent_Of_Address (Parent_Type));
5730
5731       --  Set remaining type-specific fields, depending on numeric type
5732
5733       if Is_Modular_Integer_Type (Parent_Type) then
5734          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5735
5736          Set_Non_Binary_Modulus
5737            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5738
5739          Set_Is_Known_Valid
5740            (Implicit_Base, Is_Known_Valid (Parent_Base));
5741
5742       elsif Is_Floating_Point_Type (Parent_Type) then
5743
5744          --  Digits of base type is always copied from the digits value of
5745          --  the parent base type, but the digits of the derived type will
5746          --  already have been set if there was a constraint present.
5747
5748          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5749          Set_Float_Rep    (Implicit_Base, Float_Rep    (Parent_Base));
5750
5751          if No_Constraint then
5752             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5753          end if;
5754
5755       elsif Is_Fixed_Point_Type (Parent_Type) then
5756
5757          --  Small of base type and derived type are always copied from the
5758          --  parent base type, since smalls never change. The delta of the
5759          --  base type is also copied from the parent base type. However the
5760          --  delta of the derived type will have been set already if a
5761          --  constraint was present.
5762
5763          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5764          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5765          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5766
5767          if No_Constraint then
5768             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5769          end if;
5770
5771          --  The scale and machine radix in the decimal case are always
5772          --  copied from the parent base type.
5773
5774          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
5775             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
5776             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
5777
5778             Set_Machine_Radix_10
5779               (Derived_Type,  Machine_Radix_10 (Parent_Base));
5780             Set_Machine_Radix_10
5781               (Implicit_Base, Machine_Radix_10 (Parent_Base));
5782
5783             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5784
5785             if No_Constraint then
5786                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
5787
5788             else
5789                --  the analysis of the subtype_indication sets the
5790                --  digits value of the derived type.
5791
5792                null;
5793             end if;
5794          end if;
5795       end if;
5796
5797       --  The type of the bounds is that of the parent type, and they
5798       --  must be converted to the derived type.
5799
5800       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
5801
5802       --  The implicit_base should be frozen when the derived type is frozen,
5803       --  but note that it is used in the conversions of the bounds. For fixed
5804       --  types we delay the determination of the bounds until the proper
5805       --  freezing point. For other numeric types this is rejected by GCC, for
5806       --  reasons that are currently unclear (???), so we choose to freeze the
5807       --  implicit base now. In the case of integers and floating point types
5808       --  this is harmless because subsequent representation clauses cannot
5809       --  affect anything, but it is still baffling that we cannot use the
5810       --  same mechanism for all derived numeric types.
5811
5812       --  There is a further complication: actually *some* representation
5813       --  clauses can affect the implicit base type. Namely, attribute
5814       --  definition clauses for stream-oriented attributes need to set the
5815       --  corresponding TSS entries on the base type, and this normally cannot
5816       --  be done after the base type is frozen, so the circuitry in
5817       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
5818       --  not use Set_TSS in this case.
5819
5820       if Is_Fixed_Point_Type (Parent_Type) then
5821          Conditional_Delay (Implicit_Base, Parent_Type);
5822       else
5823          Freeze_Before (N, Implicit_Base);
5824       end if;
5825    end Build_Derived_Numeric_Type;
5826
5827    --------------------------------
5828    -- Build_Derived_Private_Type --
5829    --------------------------------
5830
5831    procedure Build_Derived_Private_Type
5832      (N             : Node_Id;
5833       Parent_Type   : Entity_Id;
5834       Derived_Type  : Entity_Id;
5835       Is_Completion : Boolean;
5836       Derive_Subps  : Boolean := True)
5837    is
5838       Loc         : constant Source_Ptr := Sloc (N);
5839       Der_Base    : Entity_Id;
5840       Discr       : Entity_Id;
5841       Full_Decl   : Node_Id := Empty;
5842       Full_Der    : Entity_Id;
5843       Full_P      : Entity_Id;
5844       Last_Discr  : Entity_Id;
5845       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
5846       Swapped     : Boolean := False;
5847
5848       procedure Copy_And_Build;
5849       --  Copy derived type declaration, replace parent with its full view,
5850       --  and analyze new declaration.
5851
5852       --------------------
5853       -- Copy_And_Build --
5854       --------------------
5855
5856       procedure Copy_And_Build is
5857          Full_N : Node_Id;
5858
5859       begin
5860          if Ekind (Parent_Type) in Record_Kind
5861            or else
5862              (Ekind (Parent_Type) in Enumeration_Kind
5863                and then not Is_Standard_Character_Type (Parent_Type)
5864                and then not Is_Generic_Type (Root_Type (Parent_Type)))
5865          then
5866             Full_N := New_Copy_Tree (N);
5867             Insert_After (N, Full_N);
5868             Build_Derived_Type (
5869               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
5870
5871          else
5872             Build_Derived_Type (
5873               N, Parent_Type, Full_Der, True, Derive_Subps => False);
5874          end if;
5875       end Copy_And_Build;
5876
5877    --  Start of processing for Build_Derived_Private_Type
5878
5879    begin
5880       if Is_Tagged_Type (Parent_Type) then
5881          Full_P := Full_View (Parent_Type);
5882
5883          --  A type extension of a type with unknown discriminants is an
5884          --  indefinite type that the back-end cannot handle directly.
5885          --  We treat it as a private type, and build a completion that is
5886          --  derived from the full view of the parent, and hopefully has
5887          --  known discriminants.
5888
5889          --  If the full view of the parent type has an underlying record view,
5890          --  use it to generate the underlying record view of this derived type
5891          --  (required for chains of derivations with unknown discriminants).
5892
5893          --  Minor optimization: we avoid the generation of useless underlying
5894          --  record view entities if the private type declaration has unknown
5895          --  discriminants but its corresponding full view has no
5896          --  discriminants.
5897
5898          if Has_Unknown_Discriminants (Parent_Type)
5899            and then Present (Full_P)
5900            and then (Has_Discriminants (Full_P)
5901                       or else Present (Underlying_Record_View (Full_P)))
5902            and then not In_Open_Scopes (Par_Scope)
5903            and then Expander_Active
5904          then
5905             declare
5906                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
5907                New_Ext  : constant Node_Id :=
5908                             Copy_Separate_Tree
5909                               (Record_Extension_Part (Type_Definition (N)));
5910                Decl     : Node_Id;
5911
5912             begin
5913                Build_Derived_Record_Type
5914                  (N, Parent_Type, Derived_Type, Derive_Subps);
5915
5916                --  Build anonymous completion, as a derivation from the full
5917                --  view of the parent. This is not a completion in the usual
5918                --  sense, because the current type is not private.
5919
5920                Decl :=
5921                  Make_Full_Type_Declaration (Loc,
5922                    Defining_Identifier => Full_Der,
5923                    Type_Definition     =>
5924                      Make_Derived_Type_Definition (Loc,
5925                        Subtype_Indication =>
5926                          New_Copy_Tree
5927                            (Subtype_Indication (Type_Definition (N))),
5928                        Record_Extension_Part => New_Ext));
5929
5930                --  If the parent type has an underlying record view, use it
5931                --  here to build the new underlying record view.
5932
5933                if Present (Underlying_Record_View (Full_P)) then
5934                   pragma Assert
5935                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
5936                        = N_Identifier);
5937                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
5938                     Underlying_Record_View (Full_P));
5939                end if;
5940
5941                Install_Private_Declarations (Par_Scope);
5942                Install_Visible_Declarations (Par_Scope);
5943                Insert_Before (N, Decl);
5944
5945                --  Mark entity as an underlying record view before analysis,
5946                --  to avoid generating the list of its primitive operations
5947                --  (which is not really required for this entity) and thus
5948                --  prevent spurious errors associated with missing overriding
5949                --  of abstract primitives (overridden only for Derived_Type).
5950
5951                Set_Ekind (Full_Der, E_Record_Type);
5952                Set_Is_Underlying_Record_View (Full_Der);
5953
5954                Analyze (Decl);
5955
5956                pragma Assert (Has_Discriminants (Full_Der)
5957                  and then not Has_Unknown_Discriminants (Full_Der));
5958
5959                Uninstall_Declarations (Par_Scope);
5960
5961                --  Freeze the underlying record view, to prevent generation of
5962                --  useless dispatching information, which is simply shared with
5963                --  the real derived type.
5964
5965                Set_Is_Frozen (Full_Der);
5966
5967                --  Set up links between real entity and underlying record view
5968
5969                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
5970                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
5971             end;
5972
5973          --  If discriminants are known, build derived record
5974
5975          else
5976             Build_Derived_Record_Type
5977               (N, Parent_Type, Derived_Type, Derive_Subps);
5978          end if;
5979
5980          return;
5981
5982       elsif Has_Discriminants (Parent_Type) then
5983          if Present (Full_View (Parent_Type)) then
5984             if not Is_Completion then
5985
5986                --  Copy declaration for subsequent analysis, to provide a
5987                --  completion for what is a private declaration. Indicate that
5988                --  the full type is internally generated.
5989
5990                Full_Decl := New_Copy_Tree (N);
5991                Full_Der  := New_Copy (Derived_Type);
5992                Set_Comes_From_Source (Full_Decl, False);
5993                Set_Comes_From_Source (Full_Der, False);
5994                Set_Parent (Full_Der, Full_Decl);
5995
5996                Insert_After (N, Full_Decl);
5997
5998             else
5999                --  If this is a completion, the full view being built is itself
6000                --  private. We build a subtype of the parent with the same
6001                --  constraints as this full view, to convey to the back end the
6002                --  constrained components and the size of this subtype. If the
6003                --  parent is constrained, its full view can serve as the
6004                --  underlying full view of the derived type.
6005
6006                if No (Discriminant_Specifications (N)) then
6007                   if Nkind (Subtype_Indication (Type_Definition (N))) =
6008                                                         N_Subtype_Indication
6009                   then
6010                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
6011
6012                   elsif Is_Constrained (Full_View (Parent_Type)) then
6013                      Set_Underlying_Full_View
6014                        (Derived_Type, Full_View (Parent_Type));
6015                   end if;
6016
6017                else
6018                   --  If there are new discriminants, the parent subtype is
6019                   --  constrained by them, but it is not clear how to build
6020                   --  the Underlying_Full_View in this case???
6021
6022                   null;
6023                end if;
6024             end if;
6025          end if;
6026
6027          --  Build partial view of derived type from partial view of parent
6028
6029          Build_Derived_Record_Type
6030            (N, Parent_Type, Derived_Type, Derive_Subps);
6031
6032          if Present (Full_View (Parent_Type)) and then not Is_Completion then
6033             if not In_Open_Scopes (Par_Scope)
6034               or else not In_Same_Source_Unit (N, Parent_Type)
6035             then
6036                --  Swap partial and full views temporarily
6037
6038                Install_Private_Declarations (Par_Scope);
6039                Install_Visible_Declarations (Par_Scope);
6040                Swapped := True;
6041             end if;
6042
6043             --  Build full view of derived type from full view of parent which
6044             --  is now installed. Subprograms have been derived on the partial
6045             --  view, the completion does not derive them anew.
6046
6047             if not Is_Tagged_Type (Parent_Type) then
6048
6049                --  If the parent is itself derived from another private type,
6050                --  installing the private declarations has not affected its
6051                --  privacy status, so use its own full view explicitly.
6052
6053                if Is_Private_Type (Parent_Type) then
6054                   Build_Derived_Record_Type
6055                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
6056                else
6057                   Build_Derived_Record_Type
6058                     (Full_Decl, Parent_Type, Full_Der, False);
6059                end if;
6060
6061             else
6062                --  If full view of parent is tagged, the completion inherits
6063                --  the proper primitive operations.
6064
6065                Set_Defining_Identifier (Full_Decl, Full_Der);
6066                Build_Derived_Record_Type
6067                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
6068             end if;
6069
6070             --  The full declaration has been introduced into the tree and
6071             --  processed in the step above. It should not be analyzed again
6072             --  (when encountered later in the current list of declarations)
6073             --  to prevent spurious name conflicts. The full entity remains
6074             --  invisible.
6075
6076             Set_Analyzed (Full_Decl);
6077
6078             if Swapped then
6079                Uninstall_Declarations (Par_Scope);
6080
6081                if In_Open_Scopes (Par_Scope) then
6082                   Install_Visible_Declarations (Par_Scope);
6083                end if;
6084             end if;
6085
6086             Der_Base := Base_Type (Derived_Type);
6087             Set_Full_View (Derived_Type, Full_Der);
6088             Set_Full_View (Der_Base, Base_Type (Full_Der));
6089
6090             --  Copy the discriminant list from full view to the partial views
6091             --  (base type and its subtype). Gigi requires that the partial and
6092             --  full views have the same discriminants.
6093
6094             --  Note that since the partial view is pointing to discriminants
6095             --  in the full view, their scope will be that of the full view.
6096             --  This might cause some front end problems and need adjustment???
6097
6098             Discr := First_Discriminant (Base_Type (Full_Der));
6099             Set_First_Entity (Der_Base, Discr);
6100
6101             loop
6102                Last_Discr := Discr;
6103                Next_Discriminant (Discr);
6104                exit when No (Discr);
6105             end loop;
6106
6107             Set_Last_Entity (Der_Base, Last_Discr);
6108
6109             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
6110             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
6111             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
6112
6113          else
6114             --  If this is a completion, the derived type stays private and
6115             --  there is no need to create a further full view, except in the
6116             --  unusual case when the derivation is nested within a child unit,
6117             --  see below.
6118
6119             null;
6120          end if;
6121
6122       elsif Present (Full_View (Parent_Type))
6123         and then  Has_Discriminants (Full_View (Parent_Type))
6124       then
6125          if Has_Unknown_Discriminants (Parent_Type)
6126            and then Nkind (Subtype_Indication (Type_Definition (N))) =
6127                                                          N_Subtype_Indication
6128          then
6129             Error_Msg_N
6130               ("cannot constrain type with unknown discriminants",
6131                Subtype_Indication (Type_Definition (N)));
6132             return;
6133          end if;
6134
6135          --  If full view of parent is a record type, build full view as a
6136          --  derivation from the parent's full view. Partial view remains
6137          --  private. For code generation and linking, the full view must have
6138          --  the same public status as the partial one. This full view is only
6139          --  needed if the parent type is in an enclosing scope, so that the
6140          --  full view may actually become visible, e.g. in a child unit. This
6141          --  is both more efficient, and avoids order of freezing problems with
6142          --  the added entities.
6143
6144          if not Is_Private_Type (Full_View (Parent_Type))
6145            and then (In_Open_Scopes (Scope (Parent_Type)))
6146          then
6147             Full_Der :=
6148               Make_Defining_Identifier
6149                 (Sloc (Derived_Type), Chars (Derived_Type));
6150             Set_Is_Itype (Full_Der);
6151             Set_Has_Private_Declaration (Full_Der);
6152             Set_Has_Private_Declaration (Derived_Type);
6153             Set_Associated_Node_For_Itype (Full_Der, N);
6154             Set_Parent (Full_Der, Parent (Derived_Type));
6155             Set_Full_View (Derived_Type, Full_Der);
6156             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6157             Full_P := Full_View (Parent_Type);
6158             Exchange_Declarations (Parent_Type);
6159             Copy_And_Build;
6160             Exchange_Declarations (Full_P);
6161
6162          else
6163             Build_Derived_Record_Type
6164               (N, Full_View (Parent_Type), Derived_Type,
6165                 Derive_Subps => False);
6166          end if;
6167
6168          --  In any case, the primitive operations are inherited from the
6169          --  parent type, not from the internal full view.
6170
6171          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6172
6173          if Derive_Subps then
6174             Derive_Subprograms (Parent_Type, Derived_Type);
6175          end if;
6176
6177       else
6178          --  Untagged type, No discriminants on either view
6179
6180          if Nkind (Subtype_Indication (Type_Definition (N))) =
6181                                                    N_Subtype_Indication
6182          then
6183             Error_Msg_N
6184               ("illegal constraint on type without discriminants", N);
6185          end if;
6186
6187          if Present (Discriminant_Specifications (N))
6188            and then Present (Full_View (Parent_Type))
6189            and then not Is_Tagged_Type (Full_View (Parent_Type))
6190          then
6191             Error_Msg_N ("cannot add discriminants to untagged type", N);
6192          end if;
6193
6194          Set_Stored_Constraint (Derived_Type, No_Elist);
6195          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6196          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6197          Set_Has_Controlled_Component
6198                                (Derived_Type, Has_Controlled_Component
6199                                                              (Parent_Type));
6200
6201          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6202
6203          if not Is_Controlled  (Parent_Type) then
6204             Set_Finalize_Storage_Only
6205               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6206          end if;
6207
6208          --  Construct the implicit full view by deriving from full view of the
6209          --  parent type. In order to get proper visibility, we install the
6210          --  parent scope and its declarations.
6211
6212          --  ??? If the parent is untagged private and its completion is
6213          --  tagged, this mechanism will not work because we cannot derive from
6214          --  the tagged full view unless we have an extension.
6215
6216          if Present (Full_View (Parent_Type))
6217            and then not Is_Tagged_Type (Full_View (Parent_Type))
6218            and then not Is_Completion
6219          then
6220             Full_Der :=
6221               Make_Defining_Identifier
6222                 (Sloc (Derived_Type), Chars (Derived_Type));
6223             Set_Is_Itype (Full_Der);
6224             Set_Has_Private_Declaration (Full_Der);
6225             Set_Has_Private_Declaration (Derived_Type);
6226             Set_Associated_Node_For_Itype (Full_Der, N);
6227             Set_Parent (Full_Der, Parent (Derived_Type));
6228             Set_Full_View (Derived_Type, Full_Der);
6229
6230             if not In_Open_Scopes (Par_Scope) then
6231                Install_Private_Declarations (Par_Scope);
6232                Install_Visible_Declarations (Par_Scope);
6233                Copy_And_Build;
6234                Uninstall_Declarations (Par_Scope);
6235
6236             --  If parent scope is open and in another unit, and parent has a
6237             --  completion, then the derivation is taking place in the visible
6238             --  part of a child unit. In that case retrieve the full view of
6239             --  the parent momentarily.
6240
6241             elsif not In_Same_Source_Unit (N, Parent_Type) then
6242                Full_P := Full_View (Parent_Type);
6243                Exchange_Declarations (Parent_Type);
6244                Copy_And_Build;
6245                Exchange_Declarations (Full_P);
6246
6247             --  Otherwise it is a local derivation
6248
6249             else
6250                Copy_And_Build;
6251             end if;
6252
6253             Set_Scope                (Full_Der, Current_Scope);
6254             Set_Is_First_Subtype     (Full_Der,
6255                                        Is_First_Subtype (Derived_Type));
6256             Set_Has_Size_Clause      (Full_Der, False);
6257             Set_Has_Alignment_Clause (Full_Der, False);
6258             Set_Next_Entity          (Full_Der, Empty);
6259             Set_Has_Delayed_Freeze   (Full_Der);
6260             Set_Is_Frozen            (Full_Der, False);
6261             Set_Freeze_Node          (Full_Der, Empty);
6262             Set_Depends_On_Private   (Full_Der,
6263                                        Has_Private_Component (Full_Der));
6264             Set_Public_Status        (Full_Der);
6265          end if;
6266       end if;
6267
6268       Set_Has_Unknown_Discriminants (Derived_Type,
6269         Has_Unknown_Discriminants (Parent_Type));
6270
6271       if Is_Private_Type (Derived_Type) then
6272          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6273       end if;
6274
6275       if Is_Private_Type (Parent_Type)
6276         and then Base_Type (Parent_Type) = Parent_Type
6277         and then In_Open_Scopes (Scope (Parent_Type))
6278       then
6279          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6280
6281          if Is_Child_Unit (Scope (Current_Scope))
6282            and then Is_Completion
6283            and then In_Private_Part (Current_Scope)
6284            and then Scope (Parent_Type) /= Current_Scope
6285          then
6286             --  This is the unusual case where a type completed by a private
6287             --  derivation occurs within a package nested in a child unit, and
6288             --  the parent is declared in an ancestor. In this case, the full
6289             --  view of the parent type will become visible in the body of
6290             --  the enclosing child, and only then will the current type be
6291             --  possibly non-private. We build a underlying full view that
6292             --  will be installed when the enclosing child body is compiled.
6293
6294             Full_Der :=
6295               Make_Defining_Identifier
6296                 (Sloc (Derived_Type), Chars (Derived_Type));
6297             Set_Is_Itype (Full_Der);
6298             Build_Itype_Reference (Full_Der, N);
6299
6300             --  The full view will be used to swap entities on entry/exit to
6301             --  the body, and must appear in the entity list for the package.
6302
6303             Append_Entity (Full_Der, Scope (Derived_Type));
6304             Set_Has_Private_Declaration (Full_Der);
6305             Set_Has_Private_Declaration (Derived_Type);
6306             Set_Associated_Node_For_Itype (Full_Der, N);
6307             Set_Parent (Full_Der, Parent (Derived_Type));
6308             Full_P := Full_View (Parent_Type);
6309             Exchange_Declarations (Parent_Type);
6310             Copy_And_Build;
6311             Exchange_Declarations (Full_P);
6312             Set_Underlying_Full_View (Derived_Type, Full_Der);
6313          end if;
6314       end if;
6315    end Build_Derived_Private_Type;
6316
6317    -------------------------------
6318    -- Build_Derived_Record_Type --
6319    -------------------------------
6320
6321    --  1. INTRODUCTION
6322
6323    --  Ideally we would like to use the same model of type derivation for
6324    --  tagged and untagged record types. Unfortunately this is not quite
6325    --  possible because the semantics of representation clauses is different
6326    --  for tagged and untagged records under inheritance. Consider the
6327    --  following:
6328
6329    --     type R (...) is [tagged] record ... end record;
6330    --     type T (...) is new R (...) [with ...];
6331
6332    --  The representation clauses for T can specify a completely different
6333    --  record layout from R's. Hence the same component can be placed in two
6334    --  very different positions in objects of type T and R. If R and T are
6335    --  tagged types, representation clauses for T can only specify the layout
6336    --  of non inherited components, thus components that are common in R and T
6337    --  have the same position in objects of type R and T.
6338
6339    --  This has two implications. The first is that the entire tree for R's
6340    --  declaration needs to be copied for T in the untagged case, so that T
6341    --  can be viewed as a record type of its own with its own representation
6342    --  clauses. The second implication is the way we handle discriminants.
6343    --  Specifically, in the untagged case we need a way to communicate to Gigi
6344    --  what are the real discriminants in the record, while for the semantics
6345    --  we need to consider those introduced by the user to rename the
6346    --  discriminants in the parent type. This is handled by introducing the
6347    --  notion of stored discriminants. See below for more.
6348
6349    --  Fortunately the way regular components are inherited can be handled in
6350    --  the same way in tagged and untagged types.
6351
6352    --  To complicate things a bit more the private view of a private extension
6353    --  cannot be handled in the same way as the full view (for one thing the
6354    --  semantic rules are somewhat different). We will explain what differs
6355    --  below.
6356
6357    --  2. DISCRIMINANTS UNDER INHERITANCE
6358
6359    --  The semantic rules governing the discriminants of derived types are
6360    --  quite subtle.
6361
6362    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6363    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6364
6365    --  If parent type has discriminants, then the discriminants that are
6366    --  declared in the derived type are [3.4 (11)]:
6367
6368    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6369    --    there is one;
6370
6371    --  o Otherwise, each discriminant of the parent type (implicitly declared
6372    --    in the same order with the same specifications). In this case, the
6373    --    discriminants are said to be "inherited", or if unknown in the parent
6374    --    are also unknown in the derived type.
6375
6376    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6377
6378    --  o The parent subtype shall be constrained;
6379
6380    --  o If the parent type is not a tagged type, then each discriminant of
6381    --    the derived type shall be used in the constraint defining a parent
6382    --    subtype. [Implementation note: This ensures that the new discriminant
6383    --    can share storage with an existing discriminant.]
6384
6385    --  For the derived type each discriminant of the parent type is either
6386    --  inherited, constrained to equal some new discriminant of the derived
6387    --  type, or constrained to the value of an expression.
6388
6389    --  When inherited or constrained to equal some new discriminant, the
6390    --  parent discriminant and the discriminant of the derived type are said
6391    --  to "correspond".
6392
6393    --  If a discriminant of the parent type is constrained to a specific value
6394    --  in the derived type definition, then the discriminant is said to be
6395    --  "specified" by that derived type definition.
6396
6397    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6398
6399    --  We have spoken about stored discriminants in point 1 (introduction)
6400    --  above. There are two sort of stored discriminants: implicit and
6401    --  explicit. As long as the derived type inherits the same discriminants as
6402    --  the root record type, stored discriminants are the same as regular
6403    --  discriminants, and are said to be implicit. However, if any discriminant
6404    --  in the root type was renamed in the derived type, then the derived
6405    --  type will contain explicit stored discriminants. Explicit stored
6406    --  discriminants are discriminants in addition to the semantically visible
6407    --  discriminants defined for the derived type. Stored discriminants are
6408    --  used by Gigi to figure out what are the physical discriminants in
6409    --  objects of the derived type (see precise definition in einfo.ads).
6410    --  As an example, consider the following:
6411
6412    --           type R  (D1, D2, D3 : Int) is record ... end record;
6413    --           type T1 is new R;
6414    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6415    --           type T3 is new T2;
6416    --           type T4 (Y : Int) is new T3 (Y, 99);
6417
6418    --  The following table summarizes the discriminants and stored
6419    --  discriminants in R and T1 through T4.
6420
6421    --   Type      Discrim     Stored Discrim  Comment
6422    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6423    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6424    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6425    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6426    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6427
6428    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6429    --  find the corresponding discriminant in the parent type, while
6430    --  Original_Record_Component (abbreviated ORC below), the actual physical
6431    --  component that is renamed. Finally the field Is_Completely_Hidden
6432    --  (abbreviated ICH below) is set for all explicit stored discriminants
6433    --  (see einfo.ads for more info). For the above example this gives:
6434
6435    --                 Discrim     CD        ORC     ICH
6436    --                 ^^^^^^^     ^^        ^^^     ^^^
6437    --                 D1 in R    empty     itself    no
6438    --                 D2 in R    empty     itself    no
6439    --                 D3 in R    empty     itself    no
6440
6441    --                 D1 in T1  D1 in R    itself    no
6442    --                 D2 in T1  D2 in R    itself    no
6443    --                 D3 in T1  D3 in R    itself    no
6444
6445    --                 X1 in T2  D3 in T1  D3 in T2   no
6446    --                 X2 in T2  D1 in T1  D1 in T2   no
6447    --                 D1 in T2   empty    itself    yes
6448    --                 D2 in T2   empty    itself    yes
6449    --                 D3 in T2   empty    itself    yes
6450
6451    --                 X1 in T3  X1 in T2  D3 in T3   no
6452    --                 X2 in T3  X2 in T2  D1 in T3   no
6453    --                 D1 in T3   empty    itself    yes
6454    --                 D2 in T3   empty    itself    yes
6455    --                 D3 in T3   empty    itself    yes
6456
6457    --                 Y  in T4  X1 in T3  D3 in T3   no
6458    --                 D1 in T3   empty    itself    yes
6459    --                 D2 in T3   empty    itself    yes
6460    --                 D3 in T3   empty    itself    yes
6461
6462    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6463
6464    --  Type derivation for tagged types is fairly straightforward. If no
6465    --  discriminants are specified by the derived type, these are inherited
6466    --  from the parent. No explicit stored discriminants are ever necessary.
6467    --  The only manipulation that is done to the tree is that of adding a
6468    --  _parent field with parent type and constrained to the same constraint
6469    --  specified for the parent in the derived type definition. For instance:
6470
6471    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6472    --           type T1 is new R with null record;
6473    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6474
6475    --  are changed into:
6476
6477    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6478    --              _parent : R (D1, D2, D3);
6479    --           end record;
6480
6481    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6482    --              _parent : T1 (X2, 88, X1);
6483    --           end record;
6484
6485    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6486    --  ORC and ICH fields are:
6487
6488    --                 Discrim     CD        ORC     ICH
6489    --                 ^^^^^^^     ^^        ^^^     ^^^
6490    --                 D1 in R    empty     itself    no
6491    --                 D2 in R    empty     itself    no
6492    --                 D3 in R    empty     itself    no
6493
6494    --                 D1 in T1  D1 in R    D1 in R   no
6495    --                 D2 in T1  D2 in R    D2 in R   no
6496    --                 D3 in T1  D3 in R    D3 in R   no
6497
6498    --                 X1 in T2  D3 in T1   D3 in R   no
6499    --                 X2 in T2  D1 in T1   D1 in R   no
6500
6501    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6502    --
6503    --  Regardless of whether we dealing with a tagged or untagged type
6504    --  we will transform all derived type declarations of the form
6505    --
6506    --               type T is new R (...) [with ...];
6507    --  or
6508    --               subtype S is R (...);
6509    --               type T is new S [with ...];
6510    --  into
6511    --               type BT is new R [with ...];
6512    --               subtype T is BT (...);
6513    --
6514    --  That is, the base derived type is constrained only if it has no
6515    --  discriminants. The reason for doing this is that GNAT's semantic model
6516    --  assumes that a base type with discriminants is unconstrained.
6517    --
6518    --  Note that, strictly speaking, the above transformation is not always
6519    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6520    --
6521    --       procedure B34011A is
6522    --          type REC (D : integer := 0) is record
6523    --             I : Integer;
6524    --          end record;
6525
6526    --          package P is
6527    --             type T6 is new Rec;
6528    --             function F return T6;
6529    --          end P;
6530
6531    --          use P;
6532    --          package Q6 is
6533    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6534    --          end Q6;
6535    --
6536    --  The definition of Q6.U is illegal. However transforming Q6.U into
6537
6538    --             type BaseU is new T6;
6539    --             subtype U is BaseU (Q6.F.I)
6540
6541    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6542    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6543    --  the transformation described above.
6544
6545    --  There is another instance where the above transformation is incorrect.
6546    --  Consider:
6547
6548    --          package Pack is
6549    --             type Base (D : Integer) is tagged null record;
6550    --             procedure P (X : Base);
6551
6552    --             type Der is new Base (2) with null record;
6553    --             procedure P (X : Der);
6554    --          end Pack;
6555
6556    --  Then the above transformation turns this into
6557
6558    --             type Der_Base is new Base with null record;
6559    --             --  procedure P (X : Base) is implicitly inherited here
6560    --             --  as procedure P (X : Der_Base).
6561
6562    --             subtype Der is Der_Base (2);
6563    --             procedure P (X : Der);
6564    --             --  The overriding of P (X : Der_Base) is illegal since we
6565    --             --  have a parameter conformance problem.
6566
6567    --  To get around this problem, after having semantically processed Der_Base
6568    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6569    --  Discriminant_Constraint from Der so that when parameter conformance is
6570    --  checked when P is overridden, no semantic errors are flagged.
6571
6572    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6573
6574    --  Regardless of whether we are dealing with a tagged or untagged type
6575    --  we will transform all derived type declarations of the form
6576
6577    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6578    --               type T is new R [with ...];
6579    --  into
6580    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6581
6582    --  The reason for such transformation is that it allows us to implement a
6583    --  very clean form of component inheritance as explained below.
6584
6585    --  Note that this transformation is not achieved by direct tree rewriting
6586    --  and manipulation, but rather by redoing the semantic actions that the
6587    --  above transformation will entail. This is done directly in routine
6588    --  Inherit_Components.
6589
6590    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
6591
6592    --  In both tagged and untagged derived types, regular non discriminant
6593    --  components are inherited in the derived type from the parent type. In
6594    --  the absence of discriminants component, inheritance is straightforward
6595    --  as components can simply be copied from the parent.
6596
6597    --  If the parent has discriminants, inheriting components constrained with
6598    --  these discriminants requires caution. Consider the following example:
6599
6600    --      type R  (D1, D2 : Positive) is [tagged] record
6601    --         S : String (D1 .. D2);
6602    --      end record;
6603
6604    --      type T1                is new R        [with null record];
6605    --      type T2 (X : positive) is new R (1, X) [with null record];
6606
6607    --  As explained in 6. above, T1 is rewritten as
6608    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
6609    --  which makes the treatment for T1 and T2 identical.
6610
6611    --  What we want when inheriting S, is that references to D1 and D2 in R are
6612    --  replaced with references to their correct constraints, i.e. D1 and D2 in
6613    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
6614    --  with either discriminant references in the derived type or expressions.
6615    --  This replacement is achieved as follows: before inheriting R's
6616    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
6617    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
6618    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
6619    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
6620    --  by String (1 .. X).
6621
6622    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
6623
6624    --  We explain here the rules governing private type extensions relevant to
6625    --  type derivation. These rules are explained on the following example:
6626
6627    --      type D [(...)] is new A [(...)] with private;      <-- partial view
6628    --      type D [(...)] is new P [(...)] with null record;  <-- full view
6629
6630    --  Type A is called the ancestor subtype of the private extension.
6631    --  Type P is the parent type of the full view of the private extension. It
6632    --  must be A or a type derived from A.
6633
6634    --  The rules concerning the discriminants of private type extensions are
6635    --  [7.3(10-13)]:
6636
6637    --  o If a private extension inherits known discriminants from the ancestor
6638    --    subtype, then the full view shall also inherit its discriminants from
6639    --    the ancestor subtype and the parent subtype of the full view shall be
6640    --    constrained if and only if the ancestor subtype is constrained.
6641
6642    --  o If a partial view has unknown discriminants, then the full view may
6643    --    define a definite or an indefinite subtype, with or without
6644    --    discriminants.
6645
6646    --  o If a partial view has neither known nor unknown discriminants, then
6647    --    the full view shall define a definite subtype.
6648
6649    --  o If the ancestor subtype of a private extension has constrained
6650    --    discriminants, then the parent subtype of the full view shall impose a
6651    --    statically matching constraint on those discriminants.
6652
6653    --  This means that only the following forms of private extensions are
6654    --  allowed:
6655
6656    --      type D is new A with private;      <-- partial view
6657    --      type D is new P with null record;  <-- full view
6658
6659    --  If A has no discriminants than P has no discriminants, otherwise P must
6660    --  inherit A's discriminants.
6661
6662    --      type D is new A (...) with private;      <-- partial view
6663    --      type D is new P (:::) with null record;  <-- full view
6664
6665    --  P must inherit A's discriminants and (...) and (:::) must statically
6666    --  match.
6667
6668    --      subtype A is R (...);
6669    --      type D is new A with private;      <-- partial view
6670    --      type D is new P with null record;  <-- full view
6671
6672    --  P must have inherited R's discriminants and must be derived from A or
6673    --  any of its subtypes.
6674
6675    --      type D (..) is new A with private;              <-- partial view
6676    --      type D (..) is new P [(:::)] with null record;  <-- full view
6677
6678    --  No specific constraints on P's discriminants or constraint (:::).
6679    --  Note that A can be unconstrained, but the parent subtype P must either
6680    --  be constrained or (:::) must be present.
6681
6682    --      type D (..) is new A [(...)] with private;      <-- partial view
6683    --      type D (..) is new P [(:::)] with null record;  <-- full view
6684
6685    --  P's constraints on A's discriminants must statically match those
6686    --  imposed by (...).
6687
6688    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
6689
6690    --  The full view of a private extension is handled exactly as described
6691    --  above. The model chose for the private view of a private extension is
6692    --  the same for what concerns discriminants (i.e. they receive the same
6693    --  treatment as in the tagged case). However, the private view of the
6694    --  private extension always inherits the components of the parent base,
6695    --  without replacing any discriminant reference. Strictly speaking this is
6696    --  incorrect. However, Gigi never uses this view to generate code so this
6697    --  is a purely semantic issue. In theory, a set of transformations similar
6698    --  to those given in 5. and 6. above could be applied to private views of
6699    --  private extensions to have the same model of component inheritance as
6700    --  for non private extensions. However, this is not done because it would
6701    --  further complicate private type processing. Semantically speaking, this
6702    --  leaves us in an uncomfortable situation. As an example consider:
6703
6704    --          package Pack is
6705    --             type R (D : integer) is tagged record
6706    --                S : String (1 .. D);
6707    --             end record;
6708    --             procedure P (X : R);
6709    --             type T is new R (1) with private;
6710    --          private
6711    --             type T is new R (1) with null record;
6712    --          end;
6713
6714    --  This is transformed into:
6715
6716    --          package Pack is
6717    --             type R (D : integer) is tagged record
6718    --                S : String (1 .. D);
6719    --             end record;
6720    --             procedure P (X : R);
6721    --             type T is new R (1) with private;
6722    --          private
6723    --             type BaseT is new R with null record;
6724    --             subtype  T is BaseT (1);
6725    --          end;
6726
6727    --  (strictly speaking the above is incorrect Ada)
6728
6729    --  From the semantic standpoint the private view of private extension T
6730    --  should be flagged as constrained since one can clearly have
6731    --
6732    --             Obj : T;
6733    --
6734    --  in a unit withing Pack. However, when deriving subprograms for the
6735    --  private view of private extension T, T must be seen as unconstrained
6736    --  since T has discriminants (this is a constraint of the current
6737    --  subprogram derivation model). Thus, when processing the private view of
6738    --  a private extension such as T, we first mark T as unconstrained, we
6739    --  process it, we perform program derivation and just before returning from
6740    --  Build_Derived_Record_Type we mark T as constrained.
6741
6742    --  ??? Are there are other uncomfortable cases that we will have to
6743    --      deal with.
6744
6745    --  10. RECORD_TYPE_WITH_PRIVATE complications
6746
6747    --  Types that are derived from a visible record type and have a private
6748    --  extension present other peculiarities. They behave mostly like private
6749    --  types, but if they have primitive operations defined, these will not
6750    --  have the proper signatures for further inheritance, because other
6751    --  primitive operations will use the implicit base that we define for
6752    --  private derivations below. This affect subprogram inheritance (see
6753    --  Derive_Subprograms for details). We also derive the implicit base from
6754    --  the base type of the full view, so that the implicit base is a record
6755    --  type and not another private type, This avoids infinite loops.
6756
6757    procedure Build_Derived_Record_Type
6758      (N            : Node_Id;
6759       Parent_Type  : Entity_Id;
6760       Derived_Type : Entity_Id;
6761       Derive_Subps : Boolean := True)
6762    is
6763       Loc          : constant Source_Ptr := Sloc (N);
6764       Parent_Base  : Entity_Id;
6765       Type_Def     : Node_Id;
6766       Indic        : Node_Id;
6767       Discrim      : Entity_Id;
6768       Last_Discrim : Entity_Id;
6769       Constrs      : Elist_Id;
6770
6771       Discs : Elist_Id := New_Elmt_List;
6772       --  An empty Discs list means that there were no constraints in the
6773       --  subtype indication or that there was an error processing it.
6774
6775       Assoc_List : Elist_Id;
6776       New_Discrs : Elist_Id;
6777       New_Base   : Entity_Id;
6778       New_Decl   : Node_Id;
6779       New_Indic  : Node_Id;
6780
6781       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
6782       Discriminant_Specs : constant Boolean :=
6783                              Present (Discriminant_Specifications (N));
6784       Private_Extension  : constant Boolean :=
6785                              Nkind (N) = N_Private_Extension_Declaration;
6786
6787       Constraint_Present : Boolean;
6788       Inherit_Discrims   : Boolean := False;
6789       Save_Etype         : Entity_Id;
6790       Save_Discr_Constr  : Elist_Id;
6791       Save_Next_Entity   : Entity_Id;
6792
6793    begin
6794       if Ekind (Parent_Type) = E_Record_Type_With_Private
6795         and then Present (Full_View (Parent_Type))
6796         and then Has_Discriminants (Parent_Type)
6797       then
6798          Parent_Base := Base_Type (Full_View (Parent_Type));
6799       else
6800          Parent_Base := Base_Type (Parent_Type);
6801       end if;
6802
6803       --  Before we start the previously documented transformations, here is
6804       --  little fix for size and alignment of tagged types. Normally when we
6805       --  derive type D from type P, we copy the size and alignment of P as the
6806       --  default for D, and in the absence of explicit representation clauses
6807       --  for D, the size and alignment are indeed the same as the parent.
6808
6809       --  But this is wrong for tagged types, since fields may be added, and
6810       --  the default size may need to be larger, and the default alignment may
6811       --  need to be larger.
6812
6813       --  We therefore reset the size and alignment fields in the tagged case.
6814       --  Note that the size and alignment will in any case be at least as
6815       --  large as the parent type (since the derived type has a copy of the
6816       --  parent type in the _parent field)
6817
6818       --  The type is also marked as being tagged here, which is needed when
6819       --  processing components with a self-referential anonymous access type
6820       --  in the call to Check_Anonymous_Access_Components below. Note that
6821       --  this flag is also set later on for completeness.
6822
6823       if Is_Tagged then
6824          Set_Is_Tagged_Type (Derived_Type);
6825          Init_Size_Align    (Derived_Type);
6826       end if;
6827
6828       --  STEP 0a: figure out what kind of derived type declaration we have
6829
6830       if Private_Extension then
6831          Type_Def := N;
6832          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
6833
6834       else
6835          Type_Def := Type_Definition (N);
6836
6837          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
6838          --  Parent_Base can be a private type or private extension. However,
6839          --  for tagged types with an extension the newly added fields are
6840          --  visible and hence the Derived_Type is always an E_Record_Type.
6841          --  (except that the parent may have its own private fields).
6842          --  For untagged types we preserve the Ekind of the Parent_Base.
6843
6844          if Present (Record_Extension_Part (Type_Def)) then
6845             Set_Ekind (Derived_Type, E_Record_Type);
6846
6847             --  Create internal access types for components with anonymous
6848             --  access types.
6849
6850             if Ada_Version >= Ada_2005 then
6851                Check_Anonymous_Access_Components
6852                  (N, Derived_Type, Derived_Type,
6853                    Component_List (Record_Extension_Part (Type_Def)));
6854             end if;
6855
6856          else
6857             Set_Ekind (Derived_Type, Ekind (Parent_Base));
6858          end if;
6859       end if;
6860
6861       --  Indic can either be an N_Identifier if the subtype indication
6862       --  contains no constraint or an N_Subtype_Indication if the subtype
6863       --  indication has a constraint.
6864
6865       Indic := Subtype_Indication (Type_Def);
6866       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
6867
6868       --  Check that the type has visible discriminants. The type may be
6869       --  a private type with unknown discriminants whose full view has
6870       --  discriminants which are invisible.
6871
6872       if Constraint_Present then
6873          if not Has_Discriminants (Parent_Base)
6874            or else
6875              (Has_Unknown_Discriminants (Parent_Base)
6876                 and then Is_Private_Type (Parent_Base))
6877          then
6878             Error_Msg_N
6879               ("invalid constraint: type has no discriminant",
6880                  Constraint (Indic));
6881
6882             Constraint_Present := False;
6883             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6884
6885          elsif Is_Constrained (Parent_Type) then
6886             Error_Msg_N
6887                ("invalid constraint: parent type is already constrained",
6888                   Constraint (Indic));
6889
6890             Constraint_Present := False;
6891             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6892          end if;
6893       end if;
6894
6895       --  STEP 0b: If needed, apply transformation given in point 5. above
6896
6897       if not Private_Extension
6898         and then Has_Discriminants (Parent_Type)
6899         and then not Discriminant_Specs
6900         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
6901       then
6902          --  First, we must analyze the constraint (see comment in point 5.)
6903
6904          if Constraint_Present then
6905             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
6906
6907             if Has_Discriminants (Derived_Type)
6908               and then Has_Private_Declaration (Derived_Type)
6909               and then Present (Discriminant_Constraint (Derived_Type))
6910             then
6911                --  Verify that constraints of the full view statically match
6912                --  those given in the partial view.
6913
6914                declare
6915                   C1, C2 : Elmt_Id;
6916
6917                begin
6918                   C1 := First_Elmt (New_Discrs);
6919                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
6920                   while Present (C1) and then Present (C2) loop
6921                      if Fully_Conformant_Expressions (Node (C1), Node (C2))
6922                        or else
6923                          (Is_OK_Static_Expression (Node (C1))
6924                             and then
6925                           Is_OK_Static_Expression (Node (C2))
6926                             and then
6927                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
6928                      then
6929                         null;
6930
6931                      else
6932                         Error_Msg_N (
6933                           "constraint not conformant to previous declaration",
6934                              Node (C1));
6935                      end if;
6936
6937                      Next_Elmt (C1);
6938                      Next_Elmt (C2);
6939                   end loop;
6940                end;
6941             end if;
6942          end if;
6943
6944          --  Insert and analyze the declaration for the unconstrained base type
6945
6946          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
6947
6948          New_Decl :=
6949            Make_Full_Type_Declaration (Loc,
6950               Defining_Identifier => New_Base,
6951               Type_Definition     =>
6952                 Make_Derived_Type_Definition (Loc,
6953                   Abstract_Present      => Abstract_Present (Type_Def),
6954                   Limited_Present       => Limited_Present (Type_Def),
6955                   Subtype_Indication    =>
6956                     New_Occurrence_Of (Parent_Base, Loc),
6957                   Record_Extension_Part =>
6958                     Relocate_Node (Record_Extension_Part (Type_Def)),
6959                   Interface_List        => Interface_List (Type_Def)));
6960
6961          Set_Parent (New_Decl, Parent (N));
6962          Mark_Rewrite_Insertion (New_Decl);
6963          Insert_Before (N, New_Decl);
6964
6965          --  In the extension case, make sure ancestor is frozen appropriately
6966          --  (see also non-discriminated case below).
6967
6968          if Present (Record_Extension_Part (Type_Def))
6969            or else Is_Interface (Parent_Base)
6970          then
6971             Freeze_Before (New_Decl, Parent_Type);
6972          end if;
6973
6974          --  Note that this call passes False for the Derive_Subps parameter
6975          --  because subprogram derivation is deferred until after creating
6976          --  the subtype (see below).
6977
6978          Build_Derived_Type
6979            (New_Decl, Parent_Base, New_Base,
6980             Is_Completion => True, Derive_Subps => False);
6981
6982          --  ??? This needs re-examination to determine whether the
6983          --  above call can simply be replaced by a call to Analyze.
6984
6985          Set_Analyzed (New_Decl);
6986
6987          --  Insert and analyze the declaration for the constrained subtype
6988
6989          if Constraint_Present then
6990             New_Indic :=
6991               Make_Subtype_Indication (Loc,
6992                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6993                 Constraint   => Relocate_Node (Constraint (Indic)));
6994
6995          else
6996             declare
6997                Constr_List : constant List_Id := New_List;
6998                C           : Elmt_Id;
6999                Expr        : Node_Id;
7000
7001             begin
7002                C := First_Elmt (Discriminant_Constraint (Parent_Type));
7003                while Present (C) loop
7004                   Expr := Node (C);
7005
7006                   --  It is safe here to call New_Copy_Tree since
7007                   --  Force_Evaluation was called on each constraint in
7008                   --  Build_Discriminant_Constraints.
7009
7010                   Append (New_Copy_Tree (Expr), To => Constr_List);
7011
7012                   Next_Elmt (C);
7013                end loop;
7014
7015                New_Indic :=
7016                  Make_Subtype_Indication (Loc,
7017                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7018                    Constraint   =>
7019                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
7020             end;
7021          end if;
7022
7023          Rewrite (N,
7024            Make_Subtype_Declaration (Loc,
7025              Defining_Identifier => Derived_Type,
7026              Subtype_Indication  => New_Indic));
7027
7028          Analyze (N);
7029
7030          --  Derivation of subprograms must be delayed until the full subtype
7031          --  has been established to ensure proper overriding of subprograms
7032          --  inherited by full types. If the derivations occurred as part of
7033          --  the call to Build_Derived_Type above, then the check for type
7034          --  conformance would fail because earlier primitive subprograms
7035          --  could still refer to the full type prior the change to the new
7036          --  subtype and hence would not match the new base type created here.
7037
7038          Derive_Subprograms (Parent_Type, Derived_Type);
7039
7040          --  For tagged types the Discriminant_Constraint of the new base itype
7041          --  is inherited from the first subtype so that no subtype conformance
7042          --  problem arise when the first subtype overrides primitive
7043          --  operations inherited by the implicit base type.
7044
7045          if Is_Tagged then
7046             Set_Discriminant_Constraint
7047               (New_Base, Discriminant_Constraint (Derived_Type));
7048          end if;
7049
7050          return;
7051       end if;
7052
7053       --  If we get here Derived_Type will have no discriminants or it will be
7054       --  a discriminated unconstrained base type.
7055
7056       --  STEP 1a: perform preliminary actions/checks for derived tagged types
7057
7058       if Is_Tagged then
7059
7060          --  The parent type is frozen for non-private extensions (RM 13.14(7))
7061          --  The declaration of a specific descendant of an interface type
7062          --  freezes the interface type (RM 13.14).
7063
7064          if not Private_Extension or else Is_Interface (Parent_Base) then
7065             Freeze_Before (N, Parent_Type);
7066          end if;
7067
7068          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
7069          --  cannot be declared at a deeper level than its parent type is
7070          --  removed. The check on derivation within a generic body is also
7071          --  relaxed, but there's a restriction that a derived tagged type
7072          --  cannot be declared in a generic body if it's derived directly
7073          --  or indirectly from a formal type of that generic.
7074
7075          if Ada_Version >= Ada_2005 then
7076             if Present (Enclosing_Generic_Body (Derived_Type)) then
7077                declare
7078                   Ancestor_Type : Entity_Id;
7079
7080                begin
7081                   --  Check to see if any ancestor of the derived type is a
7082                   --  formal type.
7083
7084                   Ancestor_Type := Parent_Type;
7085                   while not Is_Generic_Type (Ancestor_Type)
7086                     and then Etype (Ancestor_Type) /= Ancestor_Type
7087                   loop
7088                      Ancestor_Type := Etype (Ancestor_Type);
7089                   end loop;
7090
7091                   --  If the derived type does have a formal type as an
7092                   --  ancestor, then it's an error if the derived type is
7093                   --  declared within the body of the generic unit that
7094                   --  declares the formal type in its generic formal part. It's
7095                   --  sufficient to check whether the ancestor type is declared
7096                   --  inside the same generic body as the derived type (such as
7097                   --  within a nested generic spec), in which case the
7098                   --  derivation is legal. If the formal type is declared
7099                   --  outside of that generic body, then it's guaranteed that
7100                   --  the derived type is declared within the generic body of
7101                   --  the generic unit declaring the formal type.
7102
7103                   if Is_Generic_Type (Ancestor_Type)
7104                     and then Enclosing_Generic_Body (Ancestor_Type) /=
7105                                Enclosing_Generic_Body (Derived_Type)
7106                   then
7107                      Error_Msg_NE
7108                        ("parent type of& must not be descendant of formal type"
7109                           & " of an enclosing generic body",
7110                             Indic, Derived_Type);
7111                   end if;
7112                end;
7113             end if;
7114
7115          elsif Type_Access_Level (Derived_Type) /=
7116                  Type_Access_Level (Parent_Type)
7117            and then not Is_Generic_Type (Derived_Type)
7118          then
7119             if Is_Controlled (Parent_Type) then
7120                Error_Msg_N
7121                  ("controlled type must be declared at the library level",
7122                   Indic);
7123             else
7124                Error_Msg_N
7125                  ("type extension at deeper accessibility level than parent",
7126                   Indic);
7127             end if;
7128
7129          else
7130             declare
7131                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
7132
7133             begin
7134                if Present (GB)
7135                  and then GB /= Enclosing_Generic_Body (Parent_Base)
7136                then
7137                   Error_Msg_NE
7138                     ("parent type of& must not be outside generic body"
7139                        & " (RM 3.9.1(4))",
7140                          Indic, Derived_Type);
7141                end if;
7142             end;
7143          end if;
7144       end if;
7145
7146       --  Ada 2005 (AI-251)
7147
7148       if Ada_Version >= Ada_2005 and then Is_Tagged then
7149
7150          --  "The declaration of a specific descendant of an interface type
7151          --  freezes the interface type" (RM 13.14).
7152
7153          declare
7154             Iface : Node_Id;
7155          begin
7156             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7157                Iface := First (Interface_List (Type_Def));
7158                while Present (Iface) loop
7159                   Freeze_Before (N, Etype (Iface));
7160                   Next (Iface);
7161                end loop;
7162             end if;
7163          end;
7164       end if;
7165
7166       --  STEP 1b : preliminary cleanup of the full view of private types
7167
7168       --  If the type is already marked as having discriminants, then it's the
7169       --  completion of a private type or private extension and we need to
7170       --  retain the discriminants from the partial view if the current
7171       --  declaration has Discriminant_Specifications so that we can verify
7172       --  conformance. However, we must remove any existing components that
7173       --  were inherited from the parent (and attached in Copy_And_Swap)
7174       --  because the full type inherits all appropriate components anyway, and
7175       --  we do not want the partial view's components interfering.
7176
7177       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7178          Discrim := First_Discriminant (Derived_Type);
7179          loop
7180             Last_Discrim := Discrim;
7181             Next_Discriminant (Discrim);
7182             exit when No (Discrim);
7183          end loop;
7184
7185          Set_Last_Entity (Derived_Type, Last_Discrim);
7186
7187       --  In all other cases wipe out the list of inherited components (even
7188       --  inherited discriminants), it will be properly rebuilt here.
7189
7190       else
7191          Set_First_Entity (Derived_Type, Empty);
7192          Set_Last_Entity  (Derived_Type, Empty);
7193       end if;
7194
7195       --  STEP 1c: Initialize some flags for the Derived_Type
7196
7197       --  The following flags must be initialized here so that
7198       --  Process_Discriminants can check that discriminants of tagged types do
7199       --  not have a default initial value and that access discriminants are
7200       --  only specified for limited records. For completeness, these flags are
7201       --  also initialized along with all the other flags below.
7202
7203       --  AI-419: Limitedness is not inherited from an interface parent, so to
7204       --  be limited in that case the type must be explicitly declared as
7205       --  limited. However, task and protected interfaces are always limited.
7206
7207       if Limited_Present (Type_Def) then
7208          Set_Is_Limited_Record (Derived_Type);
7209
7210       elsif Is_Limited_Record (Parent_Type)
7211         or else (Present (Full_View (Parent_Type))
7212                    and then Is_Limited_Record (Full_View (Parent_Type)))
7213       then
7214          if not Is_Interface (Parent_Type)
7215            or else Is_Synchronized_Interface (Parent_Type)
7216            or else Is_Protected_Interface (Parent_Type)
7217            or else Is_Task_Interface (Parent_Type)
7218          then
7219             Set_Is_Limited_Record (Derived_Type);
7220          end if;
7221       end if;
7222
7223       --  STEP 2a: process discriminants of derived type if any
7224
7225       Push_Scope (Derived_Type);
7226
7227       if Discriminant_Specs then
7228          Set_Has_Unknown_Discriminants (Derived_Type, False);
7229
7230          --  The following call initializes fields Has_Discriminants and
7231          --  Discriminant_Constraint, unless we are processing the completion
7232          --  of a private type declaration.
7233
7234          Check_Or_Process_Discriminants (N, Derived_Type);
7235
7236          --  For untagged types, the constraint on the Parent_Type must be
7237          --  present and is used to rename the discriminants.
7238
7239          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7240             Error_Msg_N ("untagged parent must have discriminants", Indic);
7241
7242          elsif not Is_Tagged and then not Constraint_Present then
7243             Error_Msg_N
7244               ("discriminant constraint needed for derived untagged records",
7245                Indic);
7246
7247          --  Otherwise the parent subtype must be constrained unless we have a
7248          --  private extension.
7249
7250          elsif not Constraint_Present
7251            and then not Private_Extension
7252            and then not Is_Constrained (Parent_Type)
7253          then
7254             Error_Msg_N
7255               ("unconstrained type not allowed in this context", Indic);
7256
7257          elsif Constraint_Present then
7258             --  The following call sets the field Corresponding_Discriminant
7259             --  for the discriminants in the Derived_Type.
7260
7261             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7262
7263             --  For untagged types all new discriminants must rename
7264             --  discriminants in the parent. For private extensions new
7265             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7266
7267             Discrim := First_Discriminant (Derived_Type);
7268             while Present (Discrim) loop
7269                if not Is_Tagged
7270                  and then No (Corresponding_Discriminant (Discrim))
7271                then
7272                   Error_Msg_N
7273                     ("new discriminants must constrain old ones", Discrim);
7274
7275                elsif Private_Extension
7276                  and then Present (Corresponding_Discriminant (Discrim))
7277                then
7278                   Error_Msg_N
7279                     ("only static constraints allowed for parent"
7280                      & " discriminants in the partial view", Indic);
7281                   exit;
7282                end if;
7283
7284                --  If a new discriminant is used in the constraint, then its
7285                --  subtype must be statically compatible with the parent
7286                --  discriminant's subtype (3.7(15)).
7287
7288                if Present (Corresponding_Discriminant (Discrim))
7289                  and then
7290                    not Subtypes_Statically_Compatible
7291                          (Etype (Discrim),
7292                           Etype (Corresponding_Discriminant (Discrim)))
7293                then
7294                   Error_Msg_N
7295                     ("subtype must be compatible with parent discriminant",
7296                      Discrim);
7297                end if;
7298
7299                Next_Discriminant (Discrim);
7300             end loop;
7301
7302             --  Check whether the constraints of the full view statically
7303             --  match those imposed by the parent subtype [7.3(13)].
7304
7305             if Present (Stored_Constraint (Derived_Type)) then
7306                declare
7307                   C1, C2 : Elmt_Id;
7308
7309                begin
7310                   C1 := First_Elmt (Discs);
7311                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7312                   while Present (C1) and then Present (C2) loop
7313                      if not
7314                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7315                      then
7316                         Error_Msg_N
7317                           ("not conformant with previous declaration",
7318                            Node (C1));
7319                      end if;
7320
7321                      Next_Elmt (C1);
7322                      Next_Elmt (C2);
7323                   end loop;
7324                end;
7325             end if;
7326          end if;
7327
7328       --  STEP 2b: No new discriminants, inherit discriminants if any
7329
7330       else
7331          if Private_Extension then
7332             Set_Has_Unknown_Discriminants
7333               (Derived_Type,
7334                Has_Unknown_Discriminants (Parent_Type)
7335                  or else Unknown_Discriminants_Present (N));
7336
7337          --  The partial view of the parent may have unknown discriminants,
7338          --  but if the full view has discriminants and the parent type is
7339          --  in scope they must be inherited.
7340
7341          elsif Has_Unknown_Discriminants (Parent_Type)
7342            and then
7343             (not Has_Discriminants (Parent_Type)
7344               or else not In_Open_Scopes (Scope (Parent_Type)))
7345          then
7346             Set_Has_Unknown_Discriminants (Derived_Type);
7347          end if;
7348
7349          if not Has_Unknown_Discriminants (Derived_Type)
7350            and then not Has_Unknown_Discriminants (Parent_Base)
7351            and then Has_Discriminants (Parent_Type)
7352          then
7353             Inherit_Discrims := True;
7354             Set_Has_Discriminants
7355               (Derived_Type, True);
7356             Set_Discriminant_Constraint
7357               (Derived_Type, Discriminant_Constraint (Parent_Base));
7358          end if;
7359
7360          --  The following test is true for private types (remember
7361          --  transformation 5. is not applied to those) and in an error
7362          --  situation.
7363
7364          if Constraint_Present then
7365             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7366          end if;
7367
7368          --  For now mark a new derived type as constrained only if it has no
7369          --  discriminants. At the end of Build_Derived_Record_Type we properly
7370          --  set this flag in the case of private extensions. See comments in
7371          --  point 9. just before body of Build_Derived_Record_Type.
7372
7373          Set_Is_Constrained
7374            (Derived_Type,
7375             not (Inherit_Discrims
7376                    or else Has_Unknown_Discriminants (Derived_Type)));
7377       end if;
7378
7379       --  STEP 3: initialize fields of derived type
7380
7381       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7382       Set_Stored_Constraint (Derived_Type, No_Elist);
7383
7384       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7385       --  but cannot be interfaces
7386
7387       if not Private_Extension
7388          and then Ekind (Derived_Type) /= E_Private_Type
7389          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7390       then
7391          if Interface_Present (Type_Def) then
7392             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7393          end if;
7394
7395          Set_Interfaces (Derived_Type, No_Elist);
7396       end if;
7397
7398       --  Fields inherited from the Parent_Type
7399
7400       Set_Discard_Names
7401         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
7402       Set_Has_Specified_Layout
7403         (Derived_Type, Has_Specified_Layout (Parent_Type));
7404       Set_Is_Limited_Composite
7405         (Derived_Type, Is_Limited_Composite (Parent_Type));
7406       Set_Is_Private_Composite
7407         (Derived_Type, Is_Private_Composite (Parent_Type));
7408
7409       --  Fields inherited from the Parent_Base
7410
7411       Set_Has_Controlled_Component
7412         (Derived_Type, Has_Controlled_Component (Parent_Base));
7413       Set_Has_Non_Standard_Rep
7414         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7415       Set_Has_Primitive_Operations
7416         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7417
7418       --  Fields inherited from the Parent_Base in the non-private case
7419
7420       if Ekind (Derived_Type) = E_Record_Type then
7421          Set_Has_Complex_Representation
7422            (Derived_Type, Has_Complex_Representation (Parent_Base));
7423       end if;
7424
7425       --  Fields inherited from the Parent_Base for record types
7426
7427       if Is_Record_Type (Derived_Type) then
7428
7429          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7430          --  Parent_Base can be a private type or private extension.
7431
7432          if Present (Full_View (Parent_Base)) then
7433             Set_OK_To_Reorder_Components
7434               (Derived_Type,
7435                OK_To_Reorder_Components (Full_View (Parent_Base)));
7436             Set_Reverse_Bit_Order
7437               (Derived_Type, Reverse_Bit_Order (Full_View (Parent_Base)));
7438          else
7439             Set_OK_To_Reorder_Components
7440               (Derived_Type, OK_To_Reorder_Components (Parent_Base));
7441             Set_Reverse_Bit_Order
7442               (Derived_Type, Reverse_Bit_Order (Parent_Base));
7443          end if;
7444       end if;
7445
7446       --  Direct controlled types do not inherit Finalize_Storage_Only flag
7447
7448       if not Is_Controlled (Parent_Type) then
7449          Set_Finalize_Storage_Only
7450            (Derived_Type, Finalize_Storage_Only (Parent_Type));
7451       end if;
7452
7453       --  Set fields for private derived types
7454
7455       if Is_Private_Type (Derived_Type) then
7456          Set_Depends_On_Private (Derived_Type, True);
7457          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7458
7459       --  Inherit fields from non private record types. If this is the
7460       --  completion of a derivation from a private type, the parent itself
7461       --  is private, and the attributes come from its full view, which must
7462       --  be present.
7463
7464       else
7465          if Is_Private_Type (Parent_Base)
7466            and then not Is_Record_Type (Parent_Base)
7467          then
7468             Set_Component_Alignment
7469               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7470             Set_C_Pass_By_Copy
7471               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7472          else
7473             Set_Component_Alignment
7474               (Derived_Type, Component_Alignment (Parent_Base));
7475             Set_C_Pass_By_Copy
7476               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7477          end if;
7478       end if;
7479
7480       --  Set fields for tagged types
7481
7482       if Is_Tagged then
7483          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
7484
7485          --  All tagged types defined in Ada.Finalization are controlled
7486
7487          if Chars (Scope (Derived_Type)) = Name_Finalization
7488            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7489            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7490          then
7491             Set_Is_Controlled (Derived_Type);
7492          else
7493             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7494          end if;
7495
7496          --  Minor optimization: there is no need to generate the class-wide
7497          --  entity associated with an underlying record view.
7498
7499          if not Is_Underlying_Record_View (Derived_Type) then
7500             Make_Class_Wide_Type (Derived_Type);
7501          end if;
7502
7503          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7504
7505          if Has_Discriminants (Derived_Type)
7506            and then Constraint_Present
7507          then
7508             Set_Stored_Constraint
7509               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7510          end if;
7511
7512          if Ada_Version >= Ada_2005 then
7513             declare
7514                Ifaces_List : Elist_Id;
7515
7516             begin
7517                --  Checks rules 3.9.4 (13/2 and 14/2)
7518
7519                if Comes_From_Source (Derived_Type)
7520                  and then not Is_Private_Type (Derived_Type)
7521                  and then Is_Interface (Parent_Type)
7522                  and then not Is_Interface (Derived_Type)
7523                then
7524                   if Is_Task_Interface (Parent_Type) then
7525                      Error_Msg_N
7526                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
7527                         Derived_Type);
7528
7529                   elsif Is_Protected_Interface (Parent_Type) then
7530                      Error_Msg_N
7531                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
7532                         Derived_Type);
7533                   end if;
7534                end if;
7535
7536                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
7537
7538                Check_Interfaces (N, Type_Def);
7539
7540                --  Ada 2005 (AI-251): Collect the list of progenitors that are
7541                --  not already in the parents.
7542
7543                Collect_Interfaces
7544                  (T               => Derived_Type,
7545                   Ifaces_List     => Ifaces_List,
7546                   Exclude_Parents => True);
7547
7548                Set_Interfaces (Derived_Type, Ifaces_List);
7549
7550                --  If the derived type is the anonymous type created for
7551                --  a declaration whose parent has a constraint, propagate
7552                --  the interface list to the source type. This must be done
7553                --  prior to the completion of the analysis of the source type
7554                --  because the components in the extension may contain current
7555                --  instances whose legality depends on some ancestor.
7556
7557                if Is_Itype (Derived_Type) then
7558                   declare
7559                      Def : constant Node_Id :=
7560                        Associated_Node_For_Itype (Derived_Type);
7561                   begin
7562                      if Present (Def)
7563                        and then Nkind (Def) = N_Full_Type_Declaration
7564                      then
7565                         Set_Interfaces
7566                           (Defining_Identifier (Def), Ifaces_List);
7567                      end if;
7568                   end;
7569                end if;
7570             end;
7571          end if;
7572
7573       else
7574          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
7575          Set_Has_Non_Standard_Rep
7576                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
7577       end if;
7578
7579       --  STEP 4: Inherit components from the parent base and constrain them.
7580       --          Apply the second transformation described in point 6. above.
7581
7582       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
7583         or else not Has_Discriminants (Parent_Type)
7584         or else not Is_Constrained (Parent_Type)
7585       then
7586          Constrs := Discs;
7587       else
7588          Constrs := Discriminant_Constraint (Parent_Type);
7589       end if;
7590
7591       Assoc_List :=
7592         Inherit_Components
7593           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
7594
7595       --  STEP 5a: Copy the parent record declaration for untagged types
7596
7597       if not Is_Tagged then
7598
7599          --  Discriminant_Constraint (Derived_Type) has been properly
7600          --  constructed. Save it and temporarily set it to Empty because we
7601          --  do not want the call to New_Copy_Tree below to mess this list.
7602
7603          if Has_Discriminants (Derived_Type) then
7604             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
7605             Set_Discriminant_Constraint (Derived_Type, No_Elist);
7606          else
7607             Save_Discr_Constr := No_Elist;
7608          end if;
7609
7610          --  Save the Etype field of Derived_Type. It is correctly set now,
7611          --  but the call to New_Copy tree may remap it to point to itself,
7612          --  which is not what we want. Ditto for the Next_Entity field.
7613
7614          Save_Etype       := Etype (Derived_Type);
7615          Save_Next_Entity := Next_Entity (Derived_Type);
7616
7617          --  Assoc_List maps all stored discriminants in the Parent_Base to
7618          --  stored discriminants in the Derived_Type. It is fundamental that
7619          --  no types or itypes with discriminants other than the stored
7620          --  discriminants appear in the entities declared inside
7621          --  Derived_Type, since the back end cannot deal with it.
7622
7623          New_Decl :=
7624            New_Copy_Tree
7625              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
7626
7627          --  Restore the fields saved prior to the New_Copy_Tree call
7628          --  and compute the stored constraint.
7629
7630          Set_Etype       (Derived_Type, Save_Etype);
7631          Set_Next_Entity (Derived_Type, Save_Next_Entity);
7632
7633          if Has_Discriminants (Derived_Type) then
7634             Set_Discriminant_Constraint
7635               (Derived_Type, Save_Discr_Constr);
7636             Set_Stored_Constraint
7637               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
7638             Replace_Components (Derived_Type, New_Decl);
7639          end if;
7640
7641          --  Insert the new derived type declaration
7642
7643          Rewrite (N, New_Decl);
7644
7645       --  STEP 5b: Complete the processing for record extensions in generics
7646
7647       --  There is no completion for record extensions declared in the
7648       --  parameter part of a generic, so we need to complete processing for
7649       --  these generic record extensions here. The Record_Type_Definition call
7650       --  will change the Ekind of the components from E_Void to E_Component.
7651
7652       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
7653          Record_Type_Definition (Empty, Derived_Type);
7654
7655       --  STEP 5c: Process the record extension for non private tagged types
7656
7657       elsif not Private_Extension then
7658
7659          --  Add the _parent field in the derived type
7660
7661          Expand_Record_Extension (Derived_Type, Type_Def);
7662
7663          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
7664          --  implemented interfaces if we are in expansion mode
7665
7666          if Expander_Active
7667            and then Has_Interfaces (Derived_Type)
7668          then
7669             Add_Interface_Tag_Components (N, Derived_Type);
7670          end if;
7671
7672          --  Analyze the record extension
7673
7674          Record_Type_Definition
7675            (Record_Extension_Part (Type_Def), Derived_Type);
7676       end if;
7677
7678       End_Scope;
7679
7680       --  Nothing else to do if there is an error in the derivation.
7681       --  An unusual case: the full view may be derived from a type in an
7682       --  instance, when the partial view was used illegally as an actual
7683       --  in that instance, leading to a circular definition.
7684
7685       if Etype (Derived_Type) = Any_Type
7686         or else Etype (Parent_Type) = Derived_Type
7687       then
7688          return;
7689       end if;
7690
7691       --  Set delayed freeze and then derive subprograms, we need to do
7692       --  this in this order so that derived subprograms inherit the
7693       --  derived freeze if necessary.
7694
7695       Set_Has_Delayed_Freeze (Derived_Type);
7696
7697       if Derive_Subps then
7698          Derive_Subprograms (Parent_Type, Derived_Type);
7699       end if;
7700
7701       --  If we have a private extension which defines a constrained derived
7702       --  type mark as constrained here after we have derived subprograms. See
7703       --  comment on point 9. just above the body of Build_Derived_Record_Type.
7704
7705       if Private_Extension and then Inherit_Discrims then
7706          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
7707             Set_Is_Constrained          (Derived_Type, True);
7708             Set_Discriminant_Constraint (Derived_Type, Discs);
7709
7710          elsif Is_Constrained (Parent_Type) then
7711             Set_Is_Constrained
7712               (Derived_Type, True);
7713             Set_Discriminant_Constraint
7714               (Derived_Type, Discriminant_Constraint (Parent_Type));
7715          end if;
7716       end if;
7717
7718       --  Update the class-wide type, which shares the now-completed entity
7719       --  list with its specific type. In case of underlying record views,
7720       --  we do not generate the corresponding class wide entity.
7721
7722       if Is_Tagged
7723         and then not Is_Underlying_Record_View (Derived_Type)
7724       then
7725          Set_First_Entity
7726            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
7727          Set_Last_Entity
7728            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
7729       end if;
7730
7731       --  Update the scope of anonymous access types of discriminants and other
7732       --  components, to prevent scope anomalies in gigi, when the derivation
7733       --  appears in a scope nested within that of the parent.
7734
7735       declare
7736          D : Entity_Id;
7737
7738       begin
7739          D := First_Entity (Derived_Type);
7740          while Present (D) loop
7741             if Ekind_In (D, E_Discriminant, E_Component) then
7742                if Is_Itype (Etype (D))
7743                   and then Ekind (Etype (D)) = E_Anonymous_Access_Type
7744                then
7745                   Set_Scope (Etype (D), Current_Scope);
7746                end if;
7747             end if;
7748
7749             Next_Entity (D);
7750          end loop;
7751       end;
7752    end Build_Derived_Record_Type;
7753
7754    ------------------------
7755    -- Build_Derived_Type --
7756    ------------------------
7757
7758    procedure Build_Derived_Type
7759      (N             : Node_Id;
7760       Parent_Type   : Entity_Id;
7761       Derived_Type  : Entity_Id;
7762       Is_Completion : Boolean;
7763       Derive_Subps  : Boolean := True)
7764    is
7765       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
7766
7767    begin
7768       --  Set common attributes
7769
7770       Set_Scope         (Derived_Type, Current_Scope);
7771
7772       Set_Ekind         (Derived_Type, Ekind    (Parent_Base));
7773       Set_Etype         (Derived_Type,           Parent_Base);
7774       Set_Has_Task      (Derived_Type, Has_Task (Parent_Base));
7775
7776       Set_Size_Info      (Derived_Type,                 Parent_Type);
7777       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
7778       Set_Convention     (Derived_Type, Convention     (Parent_Type));
7779       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
7780       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
7781
7782       --  Propagate invariant information. The new type has invariants if
7783       --  they are inherited from the parent type, and these invariants can
7784       --  be further inherited, so both flags are set.
7785
7786       if Has_Inheritable_Invariants (Parent_Type) then
7787          Set_Has_Inheritable_Invariants (Derived_Type);
7788          Set_Has_Invariants (Derived_Type);
7789       end if;
7790
7791       --  We similarly inherit predicates
7792
7793       if Has_Predicates (Parent_Type) then
7794          Set_Has_Predicates (Derived_Type);
7795       end if;
7796
7797       --  The derived type inherits the representation clauses of the parent.
7798       --  However, for a private type that is completed by a derivation, there
7799       --  may be operation attributes that have been specified already (stream
7800       --  attributes and External_Tag) and those must be provided. Finally,
7801       --  if the partial view is a private extension, the representation items
7802       --  of the parent have been inherited already, and should not be chained
7803       --  twice to the derived type.
7804
7805       if Is_Tagged_Type (Parent_Type)
7806         and then Present (First_Rep_Item (Derived_Type))
7807       then
7808          --  The existing items are either operational items or items inherited
7809          --  from a private extension declaration.
7810
7811          declare
7812             Rep : Node_Id;
7813             --  Used to iterate over representation items of the derived type
7814
7815             Last_Rep : Node_Id;
7816             --  Last representation item of the (non-empty) representation
7817             --  item list of the derived type.
7818
7819             Found : Boolean := False;
7820
7821          begin
7822             Rep      := First_Rep_Item (Derived_Type);
7823             Last_Rep := Rep;
7824             while Present (Rep) loop
7825                if Rep = First_Rep_Item (Parent_Type) then
7826                   Found := True;
7827                   exit;
7828
7829                else
7830                   Rep := Next_Rep_Item (Rep);
7831
7832                   if Present (Rep) then
7833                      Last_Rep := Rep;
7834                   end if;
7835                end if;
7836             end loop;
7837
7838             --  Here if we either encountered the parent type's first rep
7839             --  item on the derived type's rep item list (in which case
7840             --  Found is True, and we have nothing else to do), or if we
7841             --  reached the last rep item of the derived type, which is
7842             --  Last_Rep, in which case we further chain the parent type's
7843             --  rep items to those of the derived type.
7844
7845             if not Found then
7846                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
7847             end if;
7848          end;
7849
7850       else
7851          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
7852       end if;
7853
7854       case Ekind (Parent_Type) is
7855          when Numeric_Kind =>
7856             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
7857
7858          when Array_Kind =>
7859             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
7860
7861          when E_Record_Type
7862             | E_Record_Subtype
7863             | Class_Wide_Kind  =>
7864             Build_Derived_Record_Type
7865               (N, Parent_Type, Derived_Type, Derive_Subps);
7866             return;
7867
7868          when Enumeration_Kind =>
7869             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
7870
7871          when Access_Kind =>
7872             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
7873
7874          when Incomplete_Or_Private_Kind =>
7875             Build_Derived_Private_Type
7876               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
7877
7878             --  For discriminated types, the derivation includes deriving
7879             --  primitive operations. For others it is done below.
7880
7881             if Is_Tagged_Type (Parent_Type)
7882               or else Has_Discriminants (Parent_Type)
7883               or else (Present (Full_View (Parent_Type))
7884                         and then Has_Discriminants (Full_View (Parent_Type)))
7885             then
7886                return;
7887             end if;
7888
7889          when Concurrent_Kind =>
7890             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
7891
7892          when others =>
7893             raise Program_Error;
7894       end case;
7895
7896       if Etype (Derived_Type) = Any_Type then
7897          return;
7898       end if;
7899
7900       --  Set delayed freeze and then derive subprograms, we need to do this
7901       --  in this order so that derived subprograms inherit the derived freeze
7902       --  if necessary.
7903
7904       Set_Has_Delayed_Freeze (Derived_Type);
7905       if Derive_Subps then
7906          Derive_Subprograms (Parent_Type, Derived_Type);
7907       end if;
7908
7909       Set_Has_Primitive_Operations
7910         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
7911    end Build_Derived_Type;
7912
7913    -----------------------
7914    -- Build_Discriminal --
7915    -----------------------
7916
7917    procedure Build_Discriminal (Discrim : Entity_Id) is
7918       D_Minal : Entity_Id;
7919       CR_Disc : Entity_Id;
7920
7921    begin
7922       --  A discriminal has the same name as the discriminant
7923
7924       D_Minal := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
7925
7926       Set_Ekind     (D_Minal, E_In_Parameter);
7927       Set_Mechanism (D_Minal, Default_Mechanism);
7928       Set_Etype     (D_Minal, Etype (Discrim));
7929       Set_Scope     (D_Minal, Current_Scope);
7930
7931       Set_Discriminal (Discrim, D_Minal);
7932       Set_Discriminal_Link (D_Minal, Discrim);
7933
7934       --  For task types, build at once the discriminants of the corresponding
7935       --  record, which are needed if discriminants are used in entry defaults
7936       --  and in family bounds.
7937
7938       if Is_Concurrent_Type (Current_Scope)
7939         or else Is_Limited_Type (Current_Scope)
7940       then
7941          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
7942
7943          Set_Ekind            (CR_Disc, E_In_Parameter);
7944          Set_Mechanism        (CR_Disc, Default_Mechanism);
7945          Set_Etype            (CR_Disc, Etype (Discrim));
7946          Set_Scope            (CR_Disc, Current_Scope);
7947          Set_Discriminal_Link (CR_Disc, Discrim);
7948          Set_CR_Discriminant  (Discrim, CR_Disc);
7949       end if;
7950    end Build_Discriminal;
7951
7952    ------------------------------------
7953    -- Build_Discriminant_Constraints --
7954    ------------------------------------
7955
7956    function Build_Discriminant_Constraints
7957      (T           : Entity_Id;
7958       Def         : Node_Id;
7959       Derived_Def : Boolean := False) return Elist_Id
7960    is
7961       C        : constant Node_Id := Constraint (Def);
7962       Nb_Discr : constant Nat     := Number_Discriminants (T);
7963
7964       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
7965       --  Saves the expression corresponding to a given discriminant in T
7966
7967       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
7968       --  Return the Position number within array Discr_Expr of a discriminant
7969       --  D within the discriminant list of the discriminated type T.
7970
7971       ------------------
7972       -- Pos_Of_Discr --
7973       ------------------
7974
7975       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
7976          Disc : Entity_Id;
7977
7978       begin
7979          Disc := First_Discriminant (T);
7980          for J in Discr_Expr'Range loop
7981             if Disc = D then
7982                return J;
7983             end if;
7984
7985             Next_Discriminant (Disc);
7986          end loop;
7987
7988          --  Note: Since this function is called on discriminants that are
7989          --  known to belong to the discriminated type, falling through the
7990          --  loop with no match signals an internal compiler error.
7991
7992          raise Program_Error;
7993       end Pos_Of_Discr;
7994
7995       --  Declarations local to Build_Discriminant_Constraints
7996
7997       Discr : Entity_Id;
7998       E     : Entity_Id;
7999       Elist : constant Elist_Id := New_Elmt_List;
8000
8001       Constr   : Node_Id;
8002       Expr     : Node_Id;
8003       Id       : Node_Id;
8004       Position : Nat;
8005       Found    : Boolean;
8006
8007       Discrim_Present : Boolean := False;
8008
8009    --  Start of processing for Build_Discriminant_Constraints
8010
8011    begin
8012       --  The following loop will process positional associations only.
8013       --  For a positional association, the (single) discriminant is
8014       --  implicitly specified by position, in textual order (RM 3.7.2).
8015
8016       Discr  := First_Discriminant (T);
8017       Constr := First (Constraints (C));
8018       for D in Discr_Expr'Range loop
8019          exit when Nkind (Constr) = N_Discriminant_Association;
8020
8021          if No (Constr) then
8022             Error_Msg_N ("too few discriminants given in constraint", C);
8023             return New_Elmt_List;
8024
8025          elsif Nkind (Constr) = N_Range
8026            or else (Nkind (Constr) = N_Attribute_Reference
8027                      and then
8028                     Attribute_Name (Constr) = Name_Range)
8029          then
8030             Error_Msg_N
8031               ("a range is not a valid discriminant constraint", Constr);
8032             Discr_Expr (D) := Error;
8033
8034          else
8035             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
8036             Discr_Expr (D) := Constr;
8037          end if;
8038
8039          Next_Discriminant (Discr);
8040          Next (Constr);
8041       end loop;
8042
8043       if No (Discr) and then Present (Constr) then
8044          Error_Msg_N ("too many discriminants given in constraint", Constr);
8045          return New_Elmt_List;
8046       end if;
8047
8048       --  Named associations can be given in any order, but if both positional
8049       --  and named associations are used in the same discriminant constraint,
8050       --  then positional associations must occur first, at their normal
8051       --  position. Hence once a named association is used, the rest of the
8052       --  discriminant constraint must use only named associations.
8053
8054       while Present (Constr) loop
8055
8056          --  Positional association forbidden after a named association
8057
8058          if Nkind (Constr) /= N_Discriminant_Association then
8059             Error_Msg_N ("positional association follows named one", Constr);
8060             return New_Elmt_List;
8061
8062          --  Otherwise it is a named association
8063
8064          else
8065             --  E records the type of the discriminants in the named
8066             --  association. All the discriminants specified in the same name
8067             --  association must have the same type.
8068
8069             E := Empty;
8070
8071             --  Search the list of discriminants in T to see if the simple name
8072             --  given in the constraint matches any of them.
8073
8074             Id := First (Selector_Names (Constr));
8075             while Present (Id) loop
8076                Found := False;
8077
8078                --  If Original_Discriminant is present, we are processing a
8079                --  generic instantiation and this is an instance node. We need
8080                --  to find the name of the corresponding discriminant in the
8081                --  actual record type T and not the name of the discriminant in
8082                --  the generic formal. Example:
8083
8084                --    generic
8085                --       type G (D : int) is private;
8086                --    package P is
8087                --       subtype W is G (D => 1);
8088                --    end package;
8089                --    type Rec (X : int) is record ... end record;
8090                --    package Q is new P (G => Rec);
8091
8092                --  At the point of the instantiation, formal type G is Rec
8093                --  and therefore when reanalyzing "subtype W is G (D => 1);"
8094                --  which really looks like "subtype W is Rec (D => 1);" at
8095                --  the point of instantiation, we want to find the discriminant
8096                --  that corresponds to D in Rec, i.e. X.
8097
8098                if Present (Original_Discriminant (Id)) then
8099                   Discr := Find_Corresponding_Discriminant (Id, T);
8100                   Found := True;
8101
8102                else
8103                   Discr := First_Discriminant (T);
8104                   while Present (Discr) loop
8105                      if Chars (Discr) = Chars (Id) then
8106                         Found := True;
8107                         exit;
8108                      end if;
8109
8110                      Next_Discriminant (Discr);
8111                   end loop;
8112
8113                   if not Found then
8114                      Error_Msg_N ("& does not match any discriminant", Id);
8115                      return New_Elmt_List;
8116
8117                   --  The following is only useful for the benefit of generic
8118                   --  instances but it does not interfere with other
8119                   --  processing for the non-generic case so we do it in all
8120                   --  cases (for generics this statement is executed when
8121                   --  processing the generic definition, see comment at the
8122                   --  beginning of this if statement).
8123
8124                   else
8125                      Set_Original_Discriminant (Id, Discr);
8126                   end if;
8127                end if;
8128
8129                Position := Pos_Of_Discr (T, Discr);
8130
8131                if Present (Discr_Expr (Position)) then
8132                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
8133
8134                else
8135                   --  Each discriminant specified in the same named association
8136                   --  must be associated with a separate copy of the
8137                   --  corresponding expression.
8138
8139                   if Present (Next (Id)) then
8140                      Expr := New_Copy_Tree (Expression (Constr));
8141                      Set_Parent (Expr, Parent (Expression (Constr)));
8142                   else
8143                      Expr := Expression (Constr);
8144                   end if;
8145
8146                   Discr_Expr (Position) := Expr;
8147                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
8148                end if;
8149
8150                --  A discriminant association with more than one discriminant
8151                --  name is only allowed if the named discriminants are all of
8152                --  the same type (RM 3.7.1(8)).
8153
8154                if E = Empty then
8155                   E := Base_Type (Etype (Discr));
8156
8157                elsif Base_Type (Etype (Discr)) /= E then
8158                   Error_Msg_N
8159                     ("all discriminants in an association " &
8160                      "must have the same type", Id);
8161                end if;
8162
8163                Next (Id);
8164             end loop;
8165          end if;
8166
8167          Next (Constr);
8168       end loop;
8169
8170       --  A discriminant constraint must provide exactly one value for each
8171       --  discriminant of the type (RM 3.7.1(8)).
8172
8173       for J in Discr_Expr'Range loop
8174          if No (Discr_Expr (J)) then
8175             Error_Msg_N ("too few discriminants given in constraint", C);
8176             return New_Elmt_List;
8177          end if;
8178       end loop;
8179
8180       --  Determine if there are discriminant expressions in the constraint
8181
8182       for J in Discr_Expr'Range loop
8183          if Denotes_Discriminant
8184               (Discr_Expr (J), Check_Concurrent => True)
8185          then
8186             Discrim_Present := True;
8187          end if;
8188       end loop;
8189
8190       --  Build an element list consisting of the expressions given in the
8191       --  discriminant constraint and apply the appropriate checks. The list
8192       --  is constructed after resolving any named discriminant associations
8193       --  and therefore the expressions appear in the textual order of the
8194       --  discriminants.
8195
8196       Discr := First_Discriminant (T);
8197       for J in Discr_Expr'Range loop
8198          if Discr_Expr (J) /= Error then
8199             Append_Elmt (Discr_Expr (J), Elist);
8200
8201             --  If any of the discriminant constraints is given by a
8202             --  discriminant and we are in a derived type declaration we
8203             --  have a discriminant renaming. Establish link between new
8204             --  and old discriminant.
8205
8206             if Denotes_Discriminant (Discr_Expr (J)) then
8207                if Derived_Def then
8208                   Set_Corresponding_Discriminant
8209                     (Entity (Discr_Expr (J)), Discr);
8210                end if;
8211
8212             --  Force the evaluation of non-discriminant expressions.
8213             --  If we have found a discriminant in the constraint 3.4(26)
8214             --  and 3.8(18) demand that no range checks are performed are
8215             --  after evaluation. If the constraint is for a component
8216             --  definition that has a per-object constraint, expressions are
8217             --  evaluated but not checked either. In all other cases perform
8218             --  a range check.
8219
8220             else
8221                if Discrim_Present then
8222                   null;
8223
8224                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8225                  and then
8226                    Has_Per_Object_Constraint
8227                      (Defining_Identifier (Parent (Parent (Def))))
8228                then
8229                   null;
8230
8231                elsif Is_Access_Type (Etype (Discr)) then
8232                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8233
8234                else
8235                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8236                end if;
8237
8238                Force_Evaluation (Discr_Expr (J));
8239             end if;
8240
8241             --  Check that the designated type of an access discriminant's
8242             --  expression is not a class-wide type unless the discriminant's
8243             --  designated type is also class-wide.
8244
8245             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8246               and then not Is_Class_Wide_Type
8247                          (Designated_Type (Etype (Discr)))
8248               and then Etype (Discr_Expr (J)) /= Any_Type
8249               and then Is_Class_Wide_Type
8250                          (Designated_Type (Etype (Discr_Expr (J))))
8251             then
8252                Wrong_Type (Discr_Expr (J), Etype (Discr));
8253
8254             elsif Is_Access_Type (Etype (Discr))
8255               and then not Is_Access_Constant (Etype (Discr))
8256               and then Is_Access_Type (Etype (Discr_Expr (J)))
8257               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8258             then
8259                Error_Msg_NE
8260                  ("constraint for discriminant& must be access to variable",
8261                     Def, Discr);
8262             end if;
8263          end if;
8264
8265          Next_Discriminant (Discr);
8266       end loop;
8267
8268       return Elist;
8269    end Build_Discriminant_Constraints;
8270
8271    ---------------------------------
8272    -- Build_Discriminated_Subtype --
8273    ---------------------------------
8274
8275    procedure Build_Discriminated_Subtype
8276      (T           : Entity_Id;
8277       Def_Id      : Entity_Id;
8278       Elist       : Elist_Id;
8279       Related_Nod : Node_Id;
8280       For_Access  : Boolean := False)
8281    is
8282       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8283       Constrained : constant Boolean :=
8284                       (Has_Discrs
8285                          and then not Is_Empty_Elmt_List (Elist)
8286                          and then not Is_Class_Wide_Type (T))
8287                         or else Is_Constrained (T);
8288
8289    begin
8290       if Ekind (T) = E_Record_Type then
8291          if For_Access then
8292             Set_Ekind (Def_Id, E_Private_Subtype);
8293             Set_Is_For_Access_Subtype (Def_Id, True);
8294          else
8295             Set_Ekind (Def_Id, E_Record_Subtype);
8296          end if;
8297
8298          --  Inherit preelaboration flag from base, for types for which it
8299          --  may have been set: records, private types, protected types.
8300
8301          Set_Known_To_Have_Preelab_Init
8302            (Def_Id, Known_To_Have_Preelab_Init (T));
8303
8304       elsif Ekind (T) = E_Task_Type then
8305          Set_Ekind (Def_Id, E_Task_Subtype);
8306
8307       elsif Ekind (T) = E_Protected_Type then
8308          Set_Ekind (Def_Id, E_Protected_Subtype);
8309          Set_Known_To_Have_Preelab_Init
8310            (Def_Id, Known_To_Have_Preelab_Init (T));
8311
8312       elsif Is_Private_Type (T) then
8313          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8314          Set_Known_To_Have_Preelab_Init
8315            (Def_Id, Known_To_Have_Preelab_Init (T));
8316
8317       elsif Is_Class_Wide_Type (T) then
8318          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8319
8320       else
8321          --  Incomplete type. Attach subtype to list of dependents, to be
8322          --  completed with full view of parent type,  unless is it the
8323          --  designated subtype of a record component within an init_proc.
8324          --  This last case arises for a component of an access type whose
8325          --  designated type is incomplete (e.g. a Taft Amendment type).
8326          --  The designated subtype is within an inner scope, and needs no
8327          --  elaboration, because only the access type is needed in the
8328          --  initialization procedure.
8329
8330          Set_Ekind (Def_Id, Ekind (T));
8331
8332          if For_Access and then Within_Init_Proc then
8333             null;
8334          else
8335             Append_Elmt (Def_Id, Private_Dependents (T));
8336          end if;
8337       end if;
8338
8339       Set_Etype             (Def_Id, T);
8340       Init_Size_Align       (Def_Id);
8341       Set_Has_Discriminants (Def_Id, Has_Discrs);
8342       Set_Is_Constrained    (Def_Id, Constrained);
8343
8344       Set_First_Entity      (Def_Id, First_Entity   (T));
8345       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8346
8347       --  If the subtype is the completion of a private declaration, there may
8348       --  have been representation clauses for the partial view, and they must
8349       --  be preserved. Build_Derived_Type chains the inherited clauses with
8350       --  the ones appearing on the extension. If this comes from a subtype
8351       --  declaration, all clauses are inherited.
8352
8353       if No (First_Rep_Item (Def_Id)) then
8354          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8355       end if;
8356
8357       if Is_Tagged_Type (T) then
8358          Set_Is_Tagged_Type  (Def_Id);
8359          Make_Class_Wide_Type (Def_Id);
8360       end if;
8361
8362       Set_Stored_Constraint (Def_Id, No_Elist);
8363
8364       if Has_Discrs then
8365          Set_Discriminant_Constraint (Def_Id, Elist);
8366          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8367       end if;
8368
8369       if Is_Tagged_Type (T) then
8370
8371          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8372          --  concurrent record type (which has the list of primitive
8373          --  operations).
8374
8375          if Ada_Version >= Ada_2005
8376            and then Is_Concurrent_Type (T)
8377          then
8378             Set_Corresponding_Record_Type (Def_Id,
8379                Corresponding_Record_Type (T));
8380          else
8381             Set_Direct_Primitive_Operations (Def_Id,
8382               Direct_Primitive_Operations (T));
8383          end if;
8384
8385          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8386       end if;
8387
8388       --  Subtypes introduced by component declarations do not need to be
8389       --  marked as delayed, and do not get freeze nodes, because the semantics
8390       --  verifies that the parents of the subtypes are frozen before the
8391       --  enclosing record is frozen.
8392
8393       if not Is_Type (Scope (Def_Id)) then
8394          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8395
8396          if Is_Private_Type (T)
8397            and then Present (Full_View (T))
8398          then
8399             Conditional_Delay (Def_Id, Full_View (T));
8400          else
8401             Conditional_Delay (Def_Id, T);
8402          end if;
8403       end if;
8404
8405       if Is_Record_Type (T) then
8406          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8407
8408          if Has_Discrs
8409             and then not Is_Empty_Elmt_List (Elist)
8410             and then not For_Access
8411          then
8412             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8413          elsif not For_Access then
8414             Set_Cloned_Subtype (Def_Id, T);
8415          end if;
8416       end if;
8417    end Build_Discriminated_Subtype;
8418
8419    ---------------------------
8420    -- Build_Itype_Reference --
8421    ---------------------------
8422
8423    procedure Build_Itype_Reference
8424      (Ityp : Entity_Id;
8425       Nod  : Node_Id)
8426    is
8427       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8428    begin
8429       Set_Itype (IR, Ityp);
8430       Insert_After (Nod, IR);
8431    end Build_Itype_Reference;
8432
8433    ------------------------
8434    -- Build_Scalar_Bound --
8435    ------------------------
8436
8437    function Build_Scalar_Bound
8438      (Bound : Node_Id;
8439       Par_T : Entity_Id;
8440       Der_T : Entity_Id) return Node_Id
8441    is
8442       New_Bound : Entity_Id;
8443
8444    begin
8445       --  Note: not clear why this is needed, how can the original bound
8446       --  be unanalyzed at this point? and if it is, what business do we
8447       --  have messing around with it? and why is the base type of the
8448       --  parent type the right type for the resolution. It probably is
8449       --  not! It is OK for the new bound we are creating, but not for
8450       --  the old one??? Still if it never happens, no problem!
8451
8452       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8453
8454       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8455          New_Bound := New_Copy (Bound);
8456          Set_Etype (New_Bound, Der_T);
8457          Set_Analyzed (New_Bound);
8458
8459       elsif Is_Entity_Name (Bound) then
8460          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8461
8462       --  The following is almost certainly wrong. What business do we have
8463       --  relocating a node (Bound) that is presumably still attached to
8464       --  the tree elsewhere???
8465
8466       else
8467          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8468       end if;
8469
8470       Set_Etype (New_Bound, Der_T);
8471       return New_Bound;
8472    end Build_Scalar_Bound;
8473
8474    --------------------------------
8475    -- Build_Underlying_Full_View --
8476    --------------------------------
8477
8478    procedure Build_Underlying_Full_View
8479      (N   : Node_Id;
8480       Typ : Entity_Id;
8481       Par : Entity_Id)
8482    is
8483       Loc  : constant Source_Ptr := Sloc (N);
8484       Subt : constant Entity_Id :=
8485                Make_Defining_Identifier
8486                  (Loc, New_External_Name (Chars (Typ), 'S'));
8487
8488       Constr : Node_Id;
8489       Indic  : Node_Id;
8490       C      : Node_Id;
8491       Id     : Node_Id;
8492
8493       procedure Set_Discriminant_Name (Id : Node_Id);
8494       --  If the derived type has discriminants, they may rename discriminants
8495       --  of the parent. When building the full view of the parent, we need to
8496       --  recover the names of the original discriminants if the constraint is
8497       --  given by named associations.
8498
8499       ---------------------------
8500       -- Set_Discriminant_Name --
8501       ---------------------------
8502
8503       procedure Set_Discriminant_Name (Id : Node_Id) is
8504          Disc : Entity_Id;
8505
8506       begin
8507          Set_Original_Discriminant (Id, Empty);
8508
8509          if Has_Discriminants (Typ) then
8510             Disc := First_Discriminant (Typ);
8511             while Present (Disc) loop
8512                if Chars (Disc) = Chars (Id)
8513                  and then Present (Corresponding_Discriminant (Disc))
8514                then
8515                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
8516                end if;
8517                Next_Discriminant (Disc);
8518             end loop;
8519          end if;
8520       end Set_Discriminant_Name;
8521
8522    --  Start of processing for Build_Underlying_Full_View
8523
8524    begin
8525       if Nkind (N) = N_Full_Type_Declaration then
8526          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
8527
8528       elsif Nkind (N) = N_Subtype_Declaration then
8529          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
8530
8531       elsif Nkind (N) = N_Component_Declaration then
8532          Constr :=
8533            New_Copy_Tree
8534              (Constraint (Subtype_Indication (Component_Definition (N))));
8535
8536       else
8537          raise Program_Error;
8538       end if;
8539
8540       C := First (Constraints (Constr));
8541       while Present (C) loop
8542          if Nkind (C) = N_Discriminant_Association then
8543             Id := First (Selector_Names (C));
8544             while Present (Id) loop
8545                Set_Discriminant_Name (Id);
8546                Next (Id);
8547             end loop;
8548          end if;
8549
8550          Next (C);
8551       end loop;
8552
8553       Indic :=
8554         Make_Subtype_Declaration (Loc,
8555           Defining_Identifier => Subt,
8556           Subtype_Indication  =>
8557             Make_Subtype_Indication (Loc,
8558               Subtype_Mark => New_Reference_To (Par, Loc),
8559               Constraint   => New_Copy_Tree (Constr)));
8560
8561       --  If this is a component subtype for an outer itype, it is not
8562       --  a list member, so simply set the parent link for analysis: if
8563       --  the enclosing type does not need to be in a declarative list,
8564       --  neither do the components.
8565
8566       if Is_List_Member (N)
8567         and then Nkind (N) /= N_Component_Declaration
8568       then
8569          Insert_Before (N, Indic);
8570       else
8571          Set_Parent (Indic, Parent (N));
8572       end if;
8573
8574       Analyze (Indic);
8575       Set_Underlying_Full_View (Typ, Full_View (Subt));
8576    end Build_Underlying_Full_View;
8577
8578    -------------------------------
8579    -- Check_Abstract_Overriding --
8580    -------------------------------
8581
8582    procedure Check_Abstract_Overriding (T : Entity_Id) is
8583       Alias_Subp : Entity_Id;
8584       Elmt       : Elmt_Id;
8585       Op_List    : Elist_Id;
8586       Subp       : Entity_Id;
8587       Type_Def   : Node_Id;
8588
8589       procedure Check_Pragma_Implemented (Subp : Entity_Id);
8590       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
8591       --  which has pragma Implemented already set. Check whether Subp's entity
8592       --  kind conforms to the implementation kind of the overridden routine.
8593
8594       procedure Check_Pragma_Implemented
8595         (Subp       : Entity_Id;
8596          Iface_Subp : Entity_Id);
8597       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
8598       --  Iface_Subp and both entities have pragma Implemented already set on
8599       --  them. Check whether the two implementation kinds are conforming.
8600
8601       procedure Inherit_Pragma_Implemented
8602         (Subp       : Entity_Id;
8603          Iface_Subp : Entity_Id);
8604       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
8605       --  subprogram Iface_Subp which has been marked by pragma Implemented.
8606       --  Propagate the implementation kind of Iface_Subp to Subp.
8607
8608       ------------------------------
8609       -- Check_Pragma_Implemented --
8610       ------------------------------
8611
8612       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
8613          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
8614          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
8615          Contr_Typ   : Entity_Id;
8616
8617       begin
8618          --  Subp must have an alias since it is a hidden entity used to link
8619          --  an interface subprogram to its overriding counterpart.
8620
8621          pragma Assert (Present (Alias (Subp)));
8622
8623          --  Extract the type of the controlling formal
8624
8625          Contr_Typ := Etype (First_Formal (Alias (Subp)));
8626
8627          if Is_Concurrent_Record_Type (Contr_Typ) then
8628             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
8629          end if;
8630
8631          --  An interface subprogram whose implementation kind is By_Entry must
8632          --  be implemented by an entry.
8633
8634          if Impl_Kind = Name_By_Entry
8635            and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Entry
8636          then
8637             Error_Msg_Node_2 := Iface_Alias;
8638             Error_Msg_NE
8639               ("type & must implement abstract subprogram & with an entry",
8640                Alias (Subp), Contr_Typ);
8641
8642          elsif Impl_Kind = Name_By_Protected_Procedure then
8643
8644             --  An interface subprogram whose implementation kind is By_
8645             --  Protected_Procedure cannot be implemented by a primitive
8646             --  procedure of a task type.
8647
8648             if Ekind (Contr_Typ) /= E_Protected_Type then
8649                Error_Msg_Node_2 := Contr_Typ;
8650                Error_Msg_NE
8651                  ("interface subprogram & cannot be implemented by a " &
8652                   "primitive procedure of task type &", Alias (Subp),
8653                   Iface_Alias);
8654
8655             --  An interface subprogram whose implementation kind is By_
8656             --  Protected_Procedure must be implemented by a procedure.
8657
8658             elsif Is_Primitive_Wrapper (Alias (Subp))
8659               and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Procedure
8660             then
8661                Error_Msg_Node_2 := Iface_Alias;
8662                Error_Msg_NE
8663                  ("type & must implement abstract subprogram & with a " &
8664                   "procedure", Alias (Subp), Contr_Typ);
8665             end if;
8666          end if;
8667       end Check_Pragma_Implemented;
8668
8669       ------------------------------
8670       -- Check_Pragma_Implemented --
8671       ------------------------------
8672
8673       procedure Check_Pragma_Implemented
8674         (Subp       : Entity_Id;
8675          Iface_Subp : Entity_Id)
8676       is
8677          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
8678          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
8679
8680       begin
8681          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
8682          --  and overriding subprogram are different. In general this is an
8683          --  error except when the implementation kind of the overridden
8684          --  subprograms is By_Any.
8685
8686          if Iface_Kind /= Subp_Kind
8687            and then Iface_Kind /= Name_By_Any
8688          then
8689             if Iface_Kind = Name_By_Entry then
8690                Error_Msg_N
8691                  ("incompatible implementation kind, overridden subprogram " &
8692                   "is marked By_Entry", Subp);
8693             else
8694                Error_Msg_N
8695                  ("incompatible implementation kind, overridden subprogram " &
8696                   "is marked By_Protected_Procedure", Subp);
8697             end if;
8698          end if;
8699       end Check_Pragma_Implemented;
8700
8701       --------------------------------
8702       -- Inherit_Pragma_Implemented --
8703       --------------------------------
8704
8705       procedure Inherit_Pragma_Implemented
8706         (Subp       : Entity_Id;
8707          Iface_Subp : Entity_Id)
8708       is
8709          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
8710          Loc        : constant Source_Ptr := Sloc (Subp);
8711          Impl_Prag  : Node_Id;
8712
8713       begin
8714          --  Since the implementation kind is stored as a representation item
8715          --  rather than a flag, create a pragma node.
8716
8717          Impl_Prag :=
8718            Make_Pragma (Loc,
8719              Chars => Name_Implemented,
8720              Pragma_Argument_Associations => New_List (
8721                Make_Pragma_Argument_Association (Loc,
8722                  Expression =>
8723                    New_Reference_To (Subp, Loc)),
8724
8725                Make_Pragma_Argument_Association (Loc,
8726                  Expression => Make_Identifier (Loc, Iface_Kind))));
8727
8728          --  The pragma doesn't need to be analyzed because it is internally
8729          --  build. It is safe to directly register it as a rep item since we
8730          --  are only interested in the characters of the implementation kind.
8731
8732          Record_Rep_Item (Subp, Impl_Prag);
8733       end Inherit_Pragma_Implemented;
8734
8735    --  Start of processing for Check_Abstract_Overriding
8736
8737    begin
8738       Op_List := Primitive_Operations (T);
8739
8740       --  Loop to check primitive operations
8741
8742       Elmt := First_Elmt (Op_List);
8743       while Present (Elmt) loop
8744          Subp := Node (Elmt);
8745          Alias_Subp := Alias (Subp);
8746
8747          --  Inherited subprograms are identified by the fact that they do not
8748          --  come from source, and the associated source location is the
8749          --  location of the first subtype of the derived type.
8750
8751          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
8752          --  subprograms that "require overriding".
8753
8754          --  Special exception, do not complain about failure to override the
8755          --  stream routines _Input and _Output, as well as the primitive
8756          --  operations used in dispatching selects since we always provide
8757          --  automatic overridings for these subprograms.
8758
8759          --  Also ignore this rule for convention CIL since .NET libraries
8760          --  do bizarre things with interfaces???
8761
8762          --  The partial view of T may have been a private extension, for
8763          --  which inherited functions dispatching on result are abstract.
8764          --  If the full view is a null extension, there is no need for
8765          --  overriding in Ada2005, but wrappers need to be built for them
8766          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
8767
8768          if Is_Null_Extension (T)
8769            and then Has_Controlling_Result (Subp)
8770            and then Ada_Version >= Ada_2005
8771            and then Present (Alias_Subp)
8772            and then not Comes_From_Source (Subp)
8773            and then not Is_Abstract_Subprogram (Alias_Subp)
8774            and then not Is_Access_Type (Etype (Subp))
8775          then
8776             null;
8777
8778          --  Ada 2005 (AI-251): Internal entities of interfaces need no
8779          --  processing because this check is done with the aliased
8780          --  entity
8781
8782          elsif Present (Interface_Alias (Subp)) then
8783             null;
8784
8785          elsif (Is_Abstract_Subprogram (Subp)
8786                  or else Requires_Overriding (Subp)
8787                  or else
8788                    (Has_Controlling_Result (Subp)
8789                      and then Present (Alias_Subp)
8790                      and then not Comes_From_Source (Subp)
8791                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
8792            and then not Is_TSS (Subp, TSS_Stream_Input)
8793            and then not Is_TSS (Subp, TSS_Stream_Output)
8794            and then not Is_Abstract_Type (T)
8795            and then Convention (T) /= Convention_CIL
8796            and then not Is_Predefined_Interface_Primitive (Subp)
8797
8798             --  Ada 2005 (AI-251): Do not consider hidden entities associated
8799             --  with abstract interface types because the check will be done
8800             --  with the aliased entity (otherwise we generate a duplicated
8801             --  error message).
8802
8803            and then not Present (Interface_Alias (Subp))
8804          then
8805             if Present (Alias_Subp) then
8806
8807                --  Only perform the check for a derived subprogram when the
8808                --  type has an explicit record extension. This avoids incorrect
8809                --  flagging of abstract subprograms for the case of a type
8810                --  without an extension that is derived from a formal type
8811                --  with a tagged actual (can occur within a private part).
8812
8813                --  Ada 2005 (AI-391): In the case of an inherited function with
8814                --  a controlling result of the type, the rule does not apply if
8815                --  the type is a null extension (unless the parent function
8816                --  itself is abstract, in which case the function must still be
8817                --  be overridden). The expander will generate an overriding
8818                --  wrapper function calling the parent subprogram (see
8819                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
8820
8821                Type_Def := Type_Definition (Parent (T));
8822
8823                if Nkind (Type_Def) = N_Derived_Type_Definition
8824                  and then Present (Record_Extension_Part (Type_Def))
8825                  and then
8826                    (Ada_Version < Ada_2005
8827                       or else not Is_Null_Extension (T)
8828                       or else Ekind (Subp) = E_Procedure
8829                       or else not Has_Controlling_Result (Subp)
8830                       or else Is_Abstract_Subprogram (Alias_Subp)
8831                       or else Requires_Overriding (Subp)
8832                       or else Is_Access_Type (Etype (Subp)))
8833                then
8834                   --  Avoid reporting error in case of abstract predefined
8835                   --  primitive inherited from interface type because the
8836                   --  body of internally generated predefined primitives
8837                   --  of tagged types are generated later by Freeze_Type
8838
8839                   if Is_Interface (Root_Type (T))
8840                     and then Is_Abstract_Subprogram (Subp)
8841                     and then Is_Predefined_Dispatching_Operation (Subp)
8842                     and then not Comes_From_Source (Ultimate_Alias (Subp))
8843                   then
8844                      null;
8845
8846                   else
8847                      Error_Msg_NE
8848                        ("type must be declared abstract or & overridden",
8849                         T, Subp);
8850
8851                      --  Traverse the whole chain of aliased subprograms to
8852                      --  complete the error notification. This is especially
8853                      --  useful for traceability of the chain of entities when
8854                      --  the subprogram corresponds with an interface
8855                      --  subprogram (which may be defined in another package).
8856
8857                      if Present (Alias_Subp) then
8858                         declare
8859                            E : Entity_Id;
8860
8861                         begin
8862                            E := Subp;
8863                            while Present (Alias (E)) loop
8864                               Error_Msg_Sloc := Sloc (E);
8865                               Error_Msg_NE
8866                                 ("\& has been inherited #", T, Subp);
8867                               E := Alias (E);
8868                            end loop;
8869
8870                            Error_Msg_Sloc := Sloc (E);
8871                            Error_Msg_NE
8872                              ("\& has been inherited from subprogram #",
8873                               T, Subp);
8874                         end;
8875                      end if;
8876                   end if;
8877
8878                --  Ada 2005 (AI-345): Protected or task type implementing
8879                --  abstract interfaces.
8880
8881                elsif Is_Concurrent_Record_Type (T)
8882                  and then Present (Interfaces (T))
8883                then
8884                   --  The controlling formal of Subp must be of mode "out",
8885                   --  "in out" or an access-to-variable to be overridden.
8886
8887                   --  Error message below needs rewording (remember comma
8888                   --  in -gnatj mode) ???
8889
8890                   if Ekind (First_Formal (Subp)) = E_In_Parameter
8891                     and then Ekind (Subp) /= E_Function
8892                   then
8893                      if not Is_Predefined_Dispatching_Operation (Subp) then
8894                         Error_Msg_NE
8895                           ("first formal of & must be of mode `OUT`, " &
8896                            "`IN OUT` or access-to-variable", T, Subp);
8897                         Error_Msg_N
8898                           ("\to be overridden by protected procedure or " &
8899                            "entry (RM 9.4(11.9/2))", T);
8900                      end if;
8901
8902                   --  Some other kind of overriding failure
8903
8904                   else
8905                      Error_Msg_NE
8906                        ("interface subprogram & must be overridden",
8907                         T, Subp);
8908
8909                      --  Examine primitive operations of synchronized type,
8910                      --  to find homonyms that have the wrong profile.
8911
8912                      declare
8913                         Prim : Entity_Id;
8914
8915                      begin
8916                         Prim :=
8917                           First_Entity (Corresponding_Concurrent_Type (T));
8918                         while Present (Prim) loop
8919                            if Chars (Prim) = Chars (Subp) then
8920                               Error_Msg_NE
8921                                 ("profile is not type conformant with "
8922                                    & "prefixed view profile of "
8923                                    & "inherited operation&", Prim, Subp);
8924                            end if;
8925
8926                            Next_Entity (Prim);
8927                         end loop;
8928                      end;
8929                   end if;
8930                end if;
8931
8932             else
8933                Error_Msg_Node_2 := T;
8934                Error_Msg_N
8935                  ("abstract subprogram& not allowed for type&", Subp);
8936
8937                --  Also post unconditional warning on the type (unconditional
8938                --  so that if there are more than one of these cases, we get
8939                --  them all, and not just the first one).
8940
8941                Error_Msg_Node_2 := Subp;
8942                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
8943             end if;
8944          end if;
8945
8946          --  Ada 2012 (AI05-0030): Perform some checks related to pragma
8947          --  Implemented
8948
8949          --  Subp is an expander-generated procedure which maps an interface
8950          --  alias to a protected wrapper. The interface alias is flagged by
8951          --  pragma Implemented. Ensure that Subp is a procedure when the
8952          --  implementation kind is By_Protected_Procedure or an entry when
8953          --  By_Entry.
8954
8955          if Ada_Version >= Ada_2012
8956            and then Is_Hidden (Subp)
8957            and then Present (Interface_Alias (Subp))
8958            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
8959          then
8960             Check_Pragma_Implemented (Subp);
8961          end if;
8962
8963          --  Subp is an interface primitive which overrides another interface
8964          --  primitive marked with pragma Implemented.
8965
8966          if Ada_Version >= Ada_2012
8967            and then Present (Overridden_Operation (Subp))
8968            and then Has_Rep_Pragma
8969                       (Overridden_Operation (Subp), Name_Implemented)
8970          then
8971             --  If the overriding routine is also marked by Implemented, check
8972             --  that the two implementation kinds are conforming.
8973
8974             if Has_Rep_Pragma (Subp, Name_Implemented) then
8975                Check_Pragma_Implemented
8976                  (Subp       => Subp,
8977                   Iface_Subp => Overridden_Operation (Subp));
8978
8979             --  Otherwise the overriding routine inherits the implementation
8980             --  kind from the overridden subprogram.
8981
8982             else
8983                Inherit_Pragma_Implemented
8984                  (Subp       => Subp,
8985                   Iface_Subp => Overridden_Operation (Subp));
8986             end if;
8987          end if;
8988
8989          Next_Elmt (Elmt);
8990       end loop;
8991    end Check_Abstract_Overriding;
8992
8993    ------------------------------------------------
8994    -- Check_Access_Discriminant_Requires_Limited --
8995    ------------------------------------------------
8996
8997    procedure Check_Access_Discriminant_Requires_Limited
8998      (D   : Node_Id;
8999       Loc : Node_Id)
9000    is
9001    begin
9002       --  A discriminant_specification for an access discriminant shall appear
9003       --  only in the declaration for a task or protected type, or for a type
9004       --  with the reserved word 'limited' in its definition or in one of its
9005       --  ancestors (RM 3.7(10)).
9006
9007       --  AI-0063: The proper condition is that type must be immutably limited,
9008       --  or else be a partial view.
9009
9010       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
9011          if Is_Immutably_Limited_Type (Current_Scope)
9012            or else
9013              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
9014                and then Limited_Present (Parent (Current_Scope)))
9015          then
9016             null;
9017
9018          else
9019             Error_Msg_N
9020               ("access discriminants allowed only for limited types", Loc);
9021          end if;
9022       end if;
9023    end Check_Access_Discriminant_Requires_Limited;
9024
9025    -----------------------------------
9026    -- Check_Aliased_Component_Types --
9027    -----------------------------------
9028
9029    procedure Check_Aliased_Component_Types (T : Entity_Id) is
9030       C : Entity_Id;
9031
9032    begin
9033       --  ??? Also need to check components of record extensions, but not
9034       --  components of protected types (which are always limited).
9035
9036       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
9037       --  types to be unconstrained. This is safe because it is illegal to
9038       --  create access subtypes to such types with explicit discriminant
9039       --  constraints.
9040
9041       if not Is_Limited_Type (T) then
9042          if Ekind (T) = E_Record_Type then
9043             C := First_Component (T);
9044             while Present (C) loop
9045                if Is_Aliased (C)
9046                  and then Has_Discriminants (Etype (C))
9047                  and then not Is_Constrained (Etype (C))
9048                  and then not In_Instance_Body
9049                  and then Ada_Version < Ada_2005
9050                then
9051                   Error_Msg_N
9052                     ("aliased component must be constrained (RM 3.6(11))",
9053                       C);
9054                end if;
9055
9056                Next_Component (C);
9057             end loop;
9058
9059          elsif Ekind (T) = E_Array_Type then
9060             if Has_Aliased_Components (T)
9061               and then Has_Discriminants (Component_Type (T))
9062               and then not Is_Constrained (Component_Type (T))
9063               and then not In_Instance_Body
9064               and then Ada_Version < Ada_2005
9065             then
9066                Error_Msg_N
9067                  ("aliased component type must be constrained (RM 3.6(11))",
9068                     T);
9069             end if;
9070          end if;
9071       end if;
9072    end Check_Aliased_Component_Types;
9073
9074    ----------------------
9075    -- Check_Completion --
9076    ----------------------
9077
9078    procedure Check_Completion (Body_Id : Node_Id := Empty) is
9079       E : Entity_Id;
9080
9081       procedure Post_Error;
9082       --  Post error message for lack of completion for entity E
9083
9084       ----------------
9085       -- Post_Error --
9086       ----------------
9087
9088       procedure Post_Error is
9089
9090          procedure Missing_Body;
9091          --  Output missing body message
9092
9093          ------------------
9094          -- Missing_Body --
9095          ------------------
9096
9097          procedure Missing_Body is
9098          begin
9099             --  Spec is in same unit, so we can post on spec
9100
9101             if In_Same_Source_Unit (Body_Id, E) then
9102                Error_Msg_N ("missing body for &", E);
9103
9104             --  Spec is in a separate unit, so we have to post on the body
9105
9106             else
9107                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
9108             end if;
9109          end Missing_Body;
9110
9111       --  Start of processing for Post_Error
9112
9113       begin
9114          if not Comes_From_Source (E) then
9115
9116             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
9117                --  It may be an anonymous protected type created for a
9118                --  single variable. Post error on variable, if present.
9119
9120                declare
9121                   Var : Entity_Id;
9122
9123                begin
9124                   Var := First_Entity (Current_Scope);
9125                   while Present (Var) loop
9126                      exit when Etype (Var) = E
9127                        and then Comes_From_Source (Var);
9128
9129                      Next_Entity (Var);
9130                   end loop;
9131
9132                   if Present (Var) then
9133                      E := Var;
9134                   end if;
9135                end;
9136             end if;
9137          end if;
9138
9139          --  If a generated entity has no completion, then either previous
9140          --  semantic errors have disabled the expansion phase, or else we had
9141          --  missing subunits, or else we are compiling without expansion,
9142          --  or else something is very wrong.
9143
9144          if not Comes_From_Source (E) then
9145             pragma Assert
9146               (Serious_Errors_Detected > 0
9147                 or else Configurable_Run_Time_Violations > 0
9148                 or else Subunits_Missing
9149                 or else not Expander_Active);
9150             return;
9151
9152          --  Here for source entity
9153
9154          else
9155             --  Here if no body to post the error message, so we post the error
9156             --  on the declaration that has no completion. This is not really
9157             --  the right place to post it, think about this later ???
9158
9159             if No (Body_Id) then
9160                if Is_Type (E) then
9161                   Error_Msg_NE
9162                     ("missing full declaration for }", Parent (E), E);
9163                else
9164                   Error_Msg_NE ("missing body for &", Parent (E), E);
9165                end if;
9166
9167             --  Package body has no completion for a declaration that appears
9168             --  in the corresponding spec. Post error on the body, with a
9169             --  reference to the non-completed declaration.
9170
9171             else
9172                Error_Msg_Sloc := Sloc (E);
9173
9174                if Is_Type (E) then
9175                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
9176
9177                elsif Is_Overloadable (E)
9178                  and then Current_Entity_In_Scope (E) /= E
9179                then
9180                   --  It may be that the completion is mistyped and appears as
9181                   --  a distinct overloading of the entity.
9182
9183                   declare
9184                      Candidate : constant Entity_Id :=
9185                                    Current_Entity_In_Scope (E);
9186                      Decl      : constant Node_Id :=
9187                                    Unit_Declaration_Node (Candidate);
9188
9189                   begin
9190                      if Is_Overloadable (Candidate)
9191                        and then Ekind (Candidate) = Ekind (E)
9192                        and then Nkind (Decl) = N_Subprogram_Body
9193                        and then Acts_As_Spec (Decl)
9194                      then
9195                         Check_Type_Conformant (Candidate, E);
9196
9197                      else
9198                         Missing_Body;
9199                      end if;
9200                   end;
9201
9202                else
9203                   Missing_Body;
9204                end if;
9205             end if;
9206          end if;
9207       end Post_Error;
9208
9209    --  Start of processing for Check_Completion
9210
9211    begin
9212       E := First_Entity (Current_Scope);
9213       while Present (E) loop
9214          if Is_Intrinsic_Subprogram (E) then
9215             null;
9216
9217          --  The following situation requires special handling: a child unit
9218          --  that appears in the context clause of the body of its parent:
9219
9220          --    procedure Parent.Child (...);
9221
9222          --    with Parent.Child;
9223          --    package body Parent is
9224
9225          --  Here Parent.Child appears as a local entity, but should not be
9226          --  flagged as requiring completion, because it is a compilation
9227          --  unit.
9228
9229          --  Ignore missing completion for a subprogram that does not come from
9230          --  source (including the _Call primitive operation of RAS types,
9231          --  which has to have the flag Comes_From_Source for other purposes):
9232          --  we assume that the expander will provide the missing completion.
9233          --  In case of previous errors, other expansion actions that provide
9234          --  bodies for null procedures with not be invoked, so inhibit message
9235          --  in those cases.
9236          --  Note that E_Operator is not in the list that follows, because
9237          --  this kind is reserved for predefined operators, that are
9238          --  intrinsic and do not need completion.
9239
9240          elsif     Ekind (E) = E_Function
9241            or else Ekind (E) = E_Procedure
9242            or else Ekind (E) = E_Generic_Function
9243            or else Ekind (E) = E_Generic_Procedure
9244          then
9245             if Has_Completion (E) then
9246                null;
9247
9248             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
9249                null;
9250
9251             elsif Is_Subprogram (E)
9252               and then (not Comes_From_Source (E)
9253                           or else Chars (E) = Name_uCall)
9254             then
9255                null;
9256
9257             elsif
9258                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
9259             then
9260                null;
9261
9262             elsif Nkind (Parent (E)) = N_Procedure_Specification
9263               and then Null_Present (Parent (E))
9264               and then Serious_Errors_Detected > 0
9265             then
9266                null;
9267
9268             else
9269                Post_Error;
9270             end if;
9271
9272          elsif Is_Entry (E) then
9273             if not Has_Completion (E) and then
9274               (Ekind (Scope (E)) = E_Protected_Object
9275                 or else Ekind (Scope (E)) = E_Protected_Type)
9276             then
9277                Post_Error;
9278             end if;
9279
9280          elsif Is_Package_Or_Generic_Package (E) then
9281             if Unit_Requires_Body (E) then
9282                if not Has_Completion (E)
9283                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
9284                                                        N_Compilation_Unit
9285                then
9286                   Post_Error;
9287                end if;
9288
9289             elsif not Is_Child_Unit (E) then
9290                May_Need_Implicit_Body (E);
9291             end if;
9292
9293          elsif Ekind (E) = E_Incomplete_Type
9294            and then No (Underlying_Type (E))
9295          then
9296             Post_Error;
9297
9298          elsif (Ekind (E) = E_Task_Type or else
9299                 Ekind (E) = E_Protected_Type)
9300            and then not Has_Completion (E)
9301          then
9302             Post_Error;
9303
9304          --  A single task declared in the current scope is a constant, verify
9305          --  that the body of its anonymous type is in the same scope. If the
9306          --  task is defined elsewhere, this may be a renaming declaration for
9307          --  which no completion is needed.
9308
9309          elsif Ekind (E) = E_Constant
9310            and then Ekind (Etype (E)) = E_Task_Type
9311            and then not Has_Completion (Etype (E))
9312            and then Scope (Etype (E)) = Current_Scope
9313          then
9314             Post_Error;
9315
9316          elsif Ekind (E) = E_Protected_Object
9317            and then not Has_Completion (Etype (E))
9318          then
9319             Post_Error;
9320
9321          elsif Ekind (E) = E_Record_Type then
9322             if Is_Tagged_Type (E) then
9323                Check_Abstract_Overriding (E);
9324                Check_Conventions (E);
9325             end if;
9326
9327             Check_Aliased_Component_Types (E);
9328
9329          elsif Ekind (E) = E_Array_Type then
9330             Check_Aliased_Component_Types (E);
9331
9332          end if;
9333
9334          Next_Entity (E);
9335       end loop;
9336    end Check_Completion;
9337
9338    ----------------------------
9339    -- Check_Delta_Expression --
9340    ----------------------------
9341
9342    procedure Check_Delta_Expression (E : Node_Id) is
9343    begin
9344       if not (Is_Real_Type (Etype (E))) then
9345          Wrong_Type (E, Any_Real);
9346
9347       elsif not Is_OK_Static_Expression (E) then
9348          Flag_Non_Static_Expr
9349            ("non-static expression used for delta value!", E);
9350
9351       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9352          Error_Msg_N ("delta expression must be positive", E);
9353
9354       else
9355          return;
9356       end if;
9357
9358       --  If any of above errors occurred, then replace the incorrect
9359       --  expression by the real 0.1, which should prevent further errors.
9360
9361       Rewrite (E,
9362         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9363       Analyze_And_Resolve (E, Standard_Float);
9364    end Check_Delta_Expression;
9365
9366    -----------------------------
9367    -- Check_Digits_Expression --
9368    -----------------------------
9369
9370    procedure Check_Digits_Expression (E : Node_Id) is
9371    begin
9372       if not (Is_Integer_Type (Etype (E))) then
9373          Wrong_Type (E, Any_Integer);
9374
9375       elsif not Is_OK_Static_Expression (E) then
9376          Flag_Non_Static_Expr
9377            ("non-static expression used for digits value!", E);
9378
9379       elsif Expr_Value (E) <= 0 then
9380          Error_Msg_N ("digits value must be greater than zero", E);
9381
9382       else
9383          return;
9384       end if;
9385
9386       --  If any of above errors occurred, then replace the incorrect
9387       --  expression by the integer 1, which should prevent further errors.
9388
9389       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9390       Analyze_And_Resolve (E, Standard_Integer);
9391
9392    end Check_Digits_Expression;
9393
9394    --------------------------
9395    -- Check_Initialization --
9396    --------------------------
9397
9398    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9399    begin
9400       if Is_Limited_Type (T)
9401         and then not In_Instance
9402         and then not In_Inlined_Body
9403       then
9404          if not OK_For_Limited_Init (T, Exp) then
9405
9406             --  In GNAT mode, this is just a warning, to allow it to be evilly
9407             --  turned off. Otherwise it is a real error.
9408
9409             if GNAT_Mode then
9410                Error_Msg_N
9411                  ("?cannot initialize entities of limited type!", Exp);
9412
9413             elsif Ada_Version < Ada_2005 then
9414                Error_Msg_N
9415                  ("cannot initialize entities of limited type", Exp);
9416                Explain_Limited_Type (T, Exp);
9417
9418             else
9419                --  Specialize error message according to kind of illegal
9420                --  initial expression.
9421
9422                if Nkind (Exp) = N_Type_Conversion
9423                  and then Nkind (Expression (Exp)) = N_Function_Call
9424                then
9425                   Error_Msg_N
9426                     ("illegal context for call"
9427                       & " to function with limited result", Exp);
9428
9429                else
9430                   Error_Msg_N
9431                     ("initialization of limited object requires aggregate "
9432                       & "or function call",  Exp);
9433                end if;
9434             end if;
9435          end if;
9436       end if;
9437    end Check_Initialization;
9438
9439    ----------------------
9440    -- Check_Interfaces --
9441    ----------------------
9442
9443    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
9444       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
9445
9446       Iface       : Node_Id;
9447       Iface_Def   : Node_Id;
9448       Iface_Typ   : Entity_Id;
9449       Parent_Node : Node_Id;
9450
9451       Is_Task : Boolean := False;
9452       --  Set True if parent type or any progenitor is a task interface
9453
9454       Is_Protected : Boolean := False;
9455       --  Set True if parent type or any progenitor is a protected interface
9456
9457       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
9458       --  Check that a progenitor is compatible with declaration.
9459       --  Error is posted on Error_Node.
9460
9461       ------------------
9462       -- Check_Ifaces --
9463       ------------------
9464
9465       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
9466          Iface_Id : constant Entity_Id :=
9467                       Defining_Identifier (Parent (Iface_Def));
9468          Type_Def : Node_Id;
9469
9470       begin
9471          if Nkind (N) = N_Private_Extension_Declaration then
9472             Type_Def := N;
9473          else
9474             Type_Def := Type_Definition (N);
9475          end if;
9476
9477          if Is_Task_Interface (Iface_Id) then
9478             Is_Task := True;
9479
9480          elsif Is_Protected_Interface (Iface_Id) then
9481             Is_Protected := True;
9482          end if;
9483
9484          if Is_Synchronized_Interface (Iface_Id) then
9485
9486             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
9487             --  extension derived from a synchronized interface must explicitly
9488             --  be declared synchronized, because the full view will be a
9489             --  synchronized type.
9490
9491             if Nkind (N) = N_Private_Extension_Declaration then
9492                if not Synchronized_Present (N) then
9493                   Error_Msg_NE
9494                     ("private extension of& must be explicitly synchronized",
9495                       N, Iface_Id);
9496                end if;
9497
9498             --  However, by 3.9.4(16/2), a full type that is a record extension
9499             --  is never allowed to derive from a synchronized interface (note
9500             --  that interfaces must be excluded from this check, because those
9501             --  are represented by derived type definitions in some cases).
9502
9503             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9504               and then not Interface_Present (Type_Definition (N))
9505             then
9506                Error_Msg_N ("record extension cannot derive from synchronized"
9507                              & " interface", Error_Node);
9508             end if;
9509          end if;
9510
9511          --  Check that the characteristics of the progenitor are compatible
9512          --  with the explicit qualifier in the declaration.
9513          --  The check only applies to qualifiers that come from source.
9514          --  Limited_Present also appears in the declaration of corresponding
9515          --  records, and the check does not apply to them.
9516
9517          if Limited_Present (Type_Def)
9518            and then not
9519              Is_Concurrent_Record_Type (Defining_Identifier (N))
9520          then
9521             if Is_Limited_Interface (Parent_Type)
9522               and then not Is_Limited_Interface (Iface_Id)
9523             then
9524                Error_Msg_NE
9525                  ("progenitor& must be limited interface",
9526                    Error_Node, Iface_Id);
9527
9528             elsif
9529               (Task_Present (Iface_Def)
9530                 or else Protected_Present (Iface_Def)
9531                 or else Synchronized_Present (Iface_Def))
9532               and then Nkind (N) /= N_Private_Extension_Declaration
9533               and then not Error_Posted (N)
9534             then
9535                Error_Msg_NE
9536                  ("progenitor& must be limited interface",
9537                    Error_Node, Iface_Id);
9538             end if;
9539
9540          --  Protected interfaces can only inherit from limited, synchronized
9541          --  or protected interfaces.
9542
9543          elsif Nkind (N) = N_Full_Type_Declaration
9544            and then  Protected_Present (Type_Def)
9545          then
9546             if Limited_Present (Iface_Def)
9547               or else Synchronized_Present (Iface_Def)
9548               or else Protected_Present (Iface_Def)
9549             then
9550                null;
9551
9552             elsif Task_Present (Iface_Def) then
9553                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9554                             & " from task interface", Error_Node);
9555
9556             else
9557                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9558                             & " from non-limited interface", Error_Node);
9559             end if;
9560
9561          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
9562          --  limited and synchronized.
9563
9564          elsif Synchronized_Present (Type_Def) then
9565             if Limited_Present (Iface_Def)
9566               or else Synchronized_Present (Iface_Def)
9567             then
9568                null;
9569
9570             elsif Protected_Present (Iface_Def)
9571               and then Nkind (N) /= N_Private_Extension_Declaration
9572             then
9573                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9574                             & " from protected interface", Error_Node);
9575
9576             elsif Task_Present (Iface_Def)
9577               and then Nkind (N) /= N_Private_Extension_Declaration
9578             then
9579                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9580                             & " from task interface", Error_Node);
9581
9582             elsif not Is_Limited_Interface (Iface_Id) then
9583                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9584                             & " from non-limited interface", Error_Node);
9585             end if;
9586
9587          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
9588          --  synchronized or task interfaces.
9589
9590          elsif Nkind (N) = N_Full_Type_Declaration
9591            and then Task_Present (Type_Def)
9592          then
9593             if Limited_Present (Iface_Def)
9594               or else Synchronized_Present (Iface_Def)
9595               or else Task_Present (Iface_Def)
9596             then
9597                null;
9598
9599             elsif Protected_Present (Iface_Def) then
9600                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9601                             & " protected interface", Error_Node);
9602
9603             else
9604                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9605                             & " non-limited interface", Error_Node);
9606             end if;
9607          end if;
9608       end Check_Ifaces;
9609
9610    --  Start of processing for Check_Interfaces
9611
9612    begin
9613       if Is_Interface (Parent_Type) then
9614          if Is_Task_Interface (Parent_Type) then
9615             Is_Task := True;
9616
9617          elsif Is_Protected_Interface (Parent_Type) then
9618             Is_Protected := True;
9619          end if;
9620       end if;
9621
9622       if Nkind (N) = N_Private_Extension_Declaration then
9623
9624          --  Check that progenitors are compatible with declaration
9625
9626          Iface := First (Interface_List (Def));
9627          while Present (Iface) loop
9628             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9629
9630             Parent_Node := Parent (Base_Type (Iface_Typ));
9631             Iface_Def   := Type_Definition (Parent_Node);
9632
9633             if not Is_Interface (Iface_Typ) then
9634                Diagnose_Interface (Iface, Iface_Typ);
9635
9636             else
9637                Check_Ifaces (Iface_Def, Iface);
9638             end if;
9639
9640             Next (Iface);
9641          end loop;
9642
9643          if Is_Task and Is_Protected then
9644             Error_Msg_N
9645               ("type cannot derive from task and protected interface", N);
9646          end if;
9647
9648          return;
9649       end if;
9650
9651       --  Full type declaration of derived type.
9652       --  Check compatibility with parent if it is interface type
9653
9654       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9655         and then Is_Interface (Parent_Type)
9656       then
9657          Parent_Node := Parent (Parent_Type);
9658
9659          --  More detailed checks for interface varieties
9660
9661          Check_Ifaces
9662            (Iface_Def  => Type_Definition (Parent_Node),
9663             Error_Node => Subtype_Indication (Type_Definition (N)));
9664       end if;
9665
9666       Iface := First (Interface_List (Def));
9667       while Present (Iface) loop
9668          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9669
9670          Parent_Node := Parent (Base_Type (Iface_Typ));
9671          Iface_Def   := Type_Definition (Parent_Node);
9672
9673          if not Is_Interface (Iface_Typ) then
9674             Diagnose_Interface (Iface, Iface_Typ);
9675
9676          else
9677             --  "The declaration of a specific descendant of an interface
9678             --   type freezes the interface type" RM 13.14
9679
9680             Freeze_Before (N, Iface_Typ);
9681             Check_Ifaces (Iface_Def, Error_Node => Iface);
9682          end if;
9683
9684          Next (Iface);
9685       end loop;
9686
9687       if Is_Task and Is_Protected then
9688          Error_Msg_N
9689            ("type cannot derive from task and protected interface", N);
9690       end if;
9691    end Check_Interfaces;
9692
9693    ------------------------------------
9694    -- Check_Or_Process_Discriminants --
9695    ------------------------------------
9696
9697    --  If an incomplete or private type declaration was already given for the
9698    --  type, the discriminants may have already been processed if they were
9699    --  present on the incomplete declaration. In this case a full conformance
9700    --  check has been performed in Find_Type_Name, and we then recheck here
9701    --  some properties that can't be checked on the partial view alone.
9702    --  Otherwise we call Process_Discriminants.
9703
9704    procedure Check_Or_Process_Discriminants
9705      (N    : Node_Id;
9706       T    : Entity_Id;
9707       Prev : Entity_Id := Empty)
9708    is
9709    begin
9710       if Has_Discriminants (T) then
9711
9712          --  Discriminants are already set on T if they were already present
9713          --  on the partial view. Make them visible to component declarations.
9714
9715          declare
9716             D : Entity_Id;
9717             --  Discriminant on T (full view) referencing expr on partial view
9718
9719             Prev_D : Entity_Id;
9720             --  Entity of corresponding discriminant on partial view
9721
9722             New_D : Node_Id;
9723             --  Discriminant specification for full view, expression is the
9724             --  syntactic copy on full view (which has been checked for
9725             --  conformance with partial view), only used here to post error
9726             --  message.
9727
9728          begin
9729             D     := First_Discriminant (T);
9730             New_D := First (Discriminant_Specifications (N));
9731             while Present (D) loop
9732                Prev_D := Current_Entity (D);
9733                Set_Current_Entity (D);
9734                Set_Is_Immediately_Visible (D);
9735                Set_Homonym (D, Prev_D);
9736
9737                --  Handle the case where there is an untagged partial view and
9738                --  the full view is tagged: must disallow discriminants with
9739                --  defaults, unless compiling for Ada 2012, which allows a
9740                --  limited tagged type to have defaulted discriminants (see
9741                --  AI05-0214). However, suppress the error here if it was
9742                --  already reported on the default expression of the partial
9743                --  view.
9744
9745                if Is_Tagged_Type (T)
9746                     and then Present (Expression (Parent (D)))
9747                     and then (not Is_Limited_Type (Current_Scope)
9748                                or else Ada_Version < Ada_2012)
9749                     and then not Error_Posted (Expression (Parent (D)))
9750                then
9751                   if Ada_Version >= Ada_2012 then
9752                      Error_Msg_N
9753                        ("discriminants of nonlimited tagged type cannot have"
9754                           & " defaults",
9755                         Expression (New_D));
9756                   else
9757                      Error_Msg_N
9758                        ("discriminants of tagged type cannot have defaults",
9759                         Expression (New_D));
9760                   end if;
9761                end if;
9762
9763                --  Ada 2005 (AI-230): Access discriminant allowed in
9764                --  non-limited record types.
9765
9766                if Ada_Version < Ada_2005 then
9767
9768                   --  This restriction gets applied to the full type here. It
9769                   --  has already been applied earlier to the partial view.
9770
9771                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
9772                end if;
9773
9774                Next_Discriminant (D);
9775                Next (New_D);
9776             end loop;
9777          end;
9778
9779       elsif Present (Discriminant_Specifications (N)) then
9780          Process_Discriminants (N, Prev);
9781       end if;
9782    end Check_Or_Process_Discriminants;
9783
9784    ----------------------
9785    -- Check_Real_Bound --
9786    ----------------------
9787
9788    procedure Check_Real_Bound (Bound : Node_Id) is
9789    begin
9790       if not Is_Real_Type (Etype (Bound)) then
9791          Error_Msg_N
9792            ("bound in real type definition must be of real type", Bound);
9793
9794       elsif not Is_OK_Static_Expression (Bound) then
9795          Flag_Non_Static_Expr
9796            ("non-static expression used for real type bound!", Bound);
9797
9798       else
9799          return;
9800       end if;
9801
9802       Rewrite
9803         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
9804       Analyze (Bound);
9805       Resolve (Bound, Standard_Float);
9806    end Check_Real_Bound;
9807
9808    ------------------------------
9809    -- Complete_Private_Subtype --
9810    ------------------------------
9811
9812    procedure Complete_Private_Subtype
9813      (Priv        : Entity_Id;
9814       Full        : Entity_Id;
9815       Full_Base   : Entity_Id;
9816       Related_Nod : Node_Id)
9817    is
9818       Save_Next_Entity : Entity_Id;
9819       Save_Homonym     : Entity_Id;
9820
9821    begin
9822       --  Set semantic attributes for (implicit) private subtype completion.
9823       --  If the full type has no discriminants, then it is a copy of the full
9824       --  view of the base. Otherwise, it is a subtype of the base with a
9825       --  possible discriminant constraint. Save and restore the original
9826       --  Next_Entity field of full to ensure that the calls to Copy_Node
9827       --  do not corrupt the entity chain.
9828
9829       --  Note that the type of the full view is the same entity as the type of
9830       --  the partial view. In this fashion, the subtype has access to the
9831       --  correct view of the parent.
9832
9833       Save_Next_Entity := Next_Entity (Full);
9834       Save_Homonym     := Homonym (Priv);
9835
9836       case Ekind (Full_Base) is
9837          when E_Record_Type    |
9838               E_Record_Subtype |
9839               Class_Wide_Kind  |
9840               Private_Kind     |
9841               Task_Kind        |
9842               Protected_Kind   =>
9843             Copy_Node (Priv, Full);
9844
9845             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
9846             Set_First_Entity       (Full, First_Entity (Full_Base));
9847             Set_Last_Entity        (Full, Last_Entity (Full_Base));
9848
9849          when others =>
9850             Copy_Node (Full_Base, Full);
9851             Set_Chars          (Full, Chars (Priv));
9852             Conditional_Delay  (Full, Priv);
9853             Set_Sloc           (Full, Sloc (Priv));
9854       end case;
9855
9856       Set_Next_Entity (Full, Save_Next_Entity);
9857       Set_Homonym     (Full, Save_Homonym);
9858       Set_Associated_Node_For_Itype (Full, Related_Nod);
9859
9860       --  Set common attributes for all subtypes
9861
9862       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
9863
9864       --  The Etype of the full view is inconsistent. Gigi needs to see the
9865       --  structural full view,  which is what the current scheme gives:
9866       --  the Etype of the full view is the etype of the full base. However,
9867       --  if the full base is a derived type, the full view then looks like
9868       --  a subtype of the parent, not a subtype of the full base. If instead
9869       --  we write:
9870
9871       --       Set_Etype (Full, Full_Base);
9872
9873       --  then we get inconsistencies in the front-end (confusion between
9874       --  views). Several outstanding bugs are related to this ???
9875
9876       Set_Is_First_Subtype (Full, False);
9877       Set_Scope            (Full, Scope (Priv));
9878       Set_Size_Info        (Full, Full_Base);
9879       Set_RM_Size          (Full, RM_Size (Full_Base));
9880       Set_Is_Itype         (Full);
9881
9882       --  A subtype of a private-type-without-discriminants, whose full-view
9883       --  has discriminants with default expressions, is not constrained!
9884
9885       if not Has_Discriminants (Priv) then
9886          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
9887
9888          if Has_Discriminants (Full_Base) then
9889             Set_Discriminant_Constraint
9890               (Full, Discriminant_Constraint (Full_Base));
9891
9892             --  The partial view may have been indefinite, the full view
9893             --  might not be.
9894
9895             Set_Has_Unknown_Discriminants
9896               (Full, Has_Unknown_Discriminants (Full_Base));
9897          end if;
9898       end if;
9899
9900       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
9901       Set_Depends_On_Private (Full, Has_Private_Component (Full));
9902
9903       --  Freeze the private subtype entity if its parent is delayed, and not
9904       --  already frozen. We skip this processing if the type is an anonymous
9905       --  subtype of a record component, or is the corresponding record of a
9906       --  protected type, since ???
9907
9908       if not Is_Type (Scope (Full)) then
9909          Set_Has_Delayed_Freeze (Full,
9910            Has_Delayed_Freeze (Full_Base)
9911              and then (not Is_Frozen (Full_Base)));
9912       end if;
9913
9914       Set_Freeze_Node (Full, Empty);
9915       Set_Is_Frozen (Full, False);
9916       Set_Full_View (Priv, Full);
9917
9918       if Has_Discriminants (Full) then
9919          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
9920          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
9921
9922          if Has_Unknown_Discriminants (Full) then
9923             Set_Discriminant_Constraint (Full, No_Elist);
9924          end if;
9925       end if;
9926
9927       if Ekind (Full_Base) = E_Record_Type
9928         and then Has_Discriminants (Full_Base)
9929         and then Has_Discriminants (Priv) -- might not, if errors
9930         and then not Has_Unknown_Discriminants (Priv)
9931         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
9932       then
9933          Create_Constrained_Components
9934            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
9935
9936       --  If the full base is itself derived from private, build a congruent
9937       --  subtype of its underlying type, for use by the back end. For a
9938       --  constrained record component, the declaration cannot be placed on
9939       --  the component list, but it must nevertheless be built an analyzed, to
9940       --  supply enough information for Gigi to compute the size of component.
9941
9942       elsif Ekind (Full_Base) in Private_Kind
9943         and then Is_Derived_Type (Full_Base)
9944         and then Has_Discriminants (Full_Base)
9945         and then (Ekind (Current_Scope) /= E_Record_Subtype)
9946       then
9947          if not Is_Itype (Priv)
9948            and then
9949              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
9950          then
9951             Build_Underlying_Full_View
9952               (Parent (Priv), Full, Etype (Full_Base));
9953
9954          elsif Nkind (Related_Nod) = N_Component_Declaration then
9955             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
9956          end if;
9957
9958       elsif Is_Record_Type (Full_Base) then
9959
9960          --  Show Full is simply a renaming of Full_Base
9961
9962          Set_Cloned_Subtype (Full, Full_Base);
9963       end if;
9964
9965       --  It is unsafe to share to bounds of a scalar type, because the Itype
9966       --  is elaborated on demand, and if a bound is non-static then different
9967       --  orders of elaboration in different units will lead to different
9968       --  external symbols.
9969
9970       if Is_Scalar_Type (Full_Base) then
9971          Set_Scalar_Range (Full,
9972            Make_Range (Sloc (Related_Nod),
9973              Low_Bound  =>
9974                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
9975              High_Bound =>
9976                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
9977
9978          --  This completion inherits the bounds of the full parent, but if
9979          --  the parent is an unconstrained floating point type, so is the
9980          --  completion.
9981
9982          if Is_Floating_Point_Type (Full_Base) then
9983             Set_Includes_Infinities
9984              (Scalar_Range (Full), Has_Infinities (Full_Base));
9985          end if;
9986       end if;
9987
9988       --  ??? It seems that a lot of fields are missing that should be copied
9989       --  from Full_Base to Full. Here are some that are introduced in a
9990       --  non-disruptive way but a cleanup is necessary.
9991
9992       if Is_Tagged_Type (Full_Base) then
9993          Set_Is_Tagged_Type (Full);
9994          Set_Direct_Primitive_Operations (Full,
9995            Direct_Primitive_Operations (Full_Base));
9996
9997          --  Inherit class_wide type of full_base in case the partial view was
9998          --  not tagged. Otherwise it has already been created when the private
9999          --  subtype was analyzed.
10000
10001          if No (Class_Wide_Type (Full)) then
10002             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
10003          end if;
10004
10005       --  If this is a subtype of a protected or task type, constrain its
10006       --  corresponding record, unless this is a subtype without constraints,
10007       --  i.e. a simple renaming as with an actual subtype in an instance.
10008
10009       elsif Is_Concurrent_Type (Full_Base) then
10010          if Has_Discriminants (Full)
10011            and then Present (Corresponding_Record_Type (Full_Base))
10012            and then
10013              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
10014          then
10015             Set_Corresponding_Record_Type (Full,
10016               Constrain_Corresponding_Record
10017                 (Full, Corresponding_Record_Type (Full_Base),
10018                   Related_Nod, Full_Base));
10019
10020          else
10021             Set_Corresponding_Record_Type (Full,
10022               Corresponding_Record_Type (Full_Base));
10023          end if;
10024       end if;
10025
10026       --  Link rep item chain, and also setting of Has_Predicates from private
10027       --  subtype to full subtype, since we will need these on the full subtype
10028       --  to create the predicate function. Note that the full subtype may
10029       --  already have rep items, inherited from the full view of the base
10030       --  type, so we must be sure not to overwrite these entries.
10031
10032       declare
10033          Item      : Node_Id;
10034          Next_Item : Node_Id;
10035
10036       begin
10037          Item := First_Rep_Item (Full);
10038
10039          --  If no existing rep items on full type, we can just link directly
10040          --  to the list of items on the private type.
10041
10042          if No (Item) then
10043             Set_First_Rep_Item (Full, First_Rep_Item (Priv));
10044
10045          --  Else search to end of items currently linked to the full subtype
10046
10047          else
10048             loop
10049                Next_Item := Next_Rep_Item (Item);
10050                exit when No (Next_Item);
10051                Item := Next_Item;
10052             end loop;
10053
10054             --  And link the private type items at the end of the chain
10055
10056             Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
10057          end if;
10058       end;
10059
10060       --  Make sure Has_Predicates is set on full type if it is set on the
10061       --  private type. Note that it may already be set on the full type and
10062       --  if so, we don't want to unset it.
10063
10064       if Has_Predicates (Priv) then
10065          Set_Has_Predicates (Full);
10066       end if;
10067    end Complete_Private_Subtype;
10068
10069    ----------------------------
10070    -- Constant_Redeclaration --
10071    ----------------------------
10072
10073    procedure Constant_Redeclaration
10074      (Id : Entity_Id;
10075       N  : Node_Id;
10076       T  : out Entity_Id)
10077    is
10078       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
10079       Obj_Def : constant Node_Id := Object_Definition (N);
10080       New_T   : Entity_Id;
10081
10082       procedure Check_Possible_Deferred_Completion
10083         (Prev_Id      : Entity_Id;
10084          Prev_Obj_Def : Node_Id;
10085          Curr_Obj_Def : Node_Id);
10086       --  Determine whether the two object definitions describe the partial
10087       --  and the full view of a constrained deferred constant. Generate
10088       --  a subtype for the full view and verify that it statically matches
10089       --  the subtype of the partial view.
10090
10091       procedure Check_Recursive_Declaration (Typ : Entity_Id);
10092       --  If deferred constant is an access type initialized with an allocator,
10093       --  check whether there is an illegal recursion in the definition,
10094       --  through a default value of some record subcomponent. This is normally
10095       --  detected when generating init procs, but requires this additional
10096       --  mechanism when expansion is disabled.
10097
10098       ----------------------------------------
10099       -- Check_Possible_Deferred_Completion --
10100       ----------------------------------------
10101
10102       procedure Check_Possible_Deferred_Completion
10103         (Prev_Id      : Entity_Id;
10104          Prev_Obj_Def : Node_Id;
10105          Curr_Obj_Def : Node_Id)
10106       is
10107       begin
10108          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
10109            and then Present (Constraint (Prev_Obj_Def))
10110            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
10111            and then Present (Constraint (Curr_Obj_Def))
10112          then
10113             declare
10114                Loc    : constant Source_Ptr := Sloc (N);
10115                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
10116                Decl   : constant Node_Id    :=
10117                           Make_Subtype_Declaration (Loc,
10118                             Defining_Identifier => Def_Id,
10119                             Subtype_Indication  =>
10120                               Relocate_Node (Curr_Obj_Def));
10121
10122             begin
10123                Insert_Before_And_Analyze (N, Decl);
10124                Set_Etype (Id, Def_Id);
10125
10126                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
10127                   Error_Msg_Sloc := Sloc (Prev_Id);
10128                   Error_Msg_N ("subtype does not statically match deferred " &
10129                                "declaration#", N);
10130                end if;
10131             end;
10132          end if;
10133       end Check_Possible_Deferred_Completion;
10134
10135       ---------------------------------
10136       -- Check_Recursive_Declaration --
10137       ---------------------------------
10138
10139       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
10140          Comp : Entity_Id;
10141
10142       begin
10143          if Is_Record_Type (Typ) then
10144             Comp := First_Component (Typ);
10145             while Present (Comp) loop
10146                if Comes_From_Source (Comp) then
10147                   if Present (Expression (Parent (Comp)))
10148                     and then Is_Entity_Name (Expression (Parent (Comp)))
10149                     and then Entity (Expression (Parent (Comp))) = Prev
10150                   then
10151                      Error_Msg_Sloc := Sloc (Parent (Comp));
10152                      Error_Msg_NE
10153                        ("illegal circularity with declaration for&#",
10154                          N, Comp);
10155                      return;
10156
10157                   elsif Is_Record_Type (Etype (Comp)) then
10158                      Check_Recursive_Declaration (Etype (Comp));
10159                   end if;
10160                end if;
10161
10162                Next_Component (Comp);
10163             end loop;
10164          end if;
10165       end Check_Recursive_Declaration;
10166
10167    --  Start of processing for Constant_Redeclaration
10168
10169    begin
10170       if Nkind (Parent (Prev)) = N_Object_Declaration then
10171          if Nkind (Object_Definition
10172                      (Parent (Prev))) = N_Subtype_Indication
10173          then
10174             --  Find type of new declaration. The constraints of the two
10175             --  views must match statically, but there is no point in
10176             --  creating an itype for the full view.
10177
10178             if Nkind (Obj_Def) = N_Subtype_Indication then
10179                Find_Type (Subtype_Mark (Obj_Def));
10180                New_T := Entity (Subtype_Mark (Obj_Def));
10181
10182             else
10183                Find_Type (Obj_Def);
10184                New_T := Entity (Obj_Def);
10185             end if;
10186
10187             T := Etype (Prev);
10188
10189          else
10190             --  The full view may impose a constraint, even if the partial
10191             --  view does not, so construct the subtype.
10192
10193             New_T := Find_Type_Of_Object (Obj_Def, N);
10194             T     := New_T;
10195          end if;
10196
10197       else
10198          --  Current declaration is illegal, diagnosed below in Enter_Name
10199
10200          T := Empty;
10201          New_T := Any_Type;
10202       end if;
10203
10204       --  If previous full declaration or a renaming declaration exists, or if
10205       --  a homograph is present, let Enter_Name handle it, either with an
10206       --  error or with the removal of an overridden implicit subprogram.
10207
10208       if Ekind (Prev) /= E_Constant
10209         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
10210         or else Present (Expression (Parent (Prev)))
10211         or else Present (Full_View (Prev))
10212       then
10213          Enter_Name (Id);
10214
10215       --  Verify that types of both declarations match, or else that both types
10216       --  are anonymous access types whose designated subtypes statically match
10217       --  (as allowed in Ada 2005 by AI-385).
10218
10219       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
10220         and then
10221           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
10222              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
10223              or else Is_Access_Constant (Etype (New_T)) /=
10224                      Is_Access_Constant (Etype (Prev))
10225              or else Can_Never_Be_Null (Etype (New_T)) /=
10226                      Can_Never_Be_Null (Etype (Prev))
10227              or else Null_Exclusion_Present (Parent (Prev)) /=
10228                      Null_Exclusion_Present (Parent (Id))
10229              or else not Subtypes_Statically_Match
10230                            (Designated_Type (Etype (Prev)),
10231                             Designated_Type (Etype (New_T))))
10232       then
10233          Error_Msg_Sloc := Sloc (Prev);
10234          Error_Msg_N ("type does not match declaration#", N);
10235          Set_Full_View (Prev, Id);
10236          Set_Etype (Id, Any_Type);
10237
10238       elsif
10239         Null_Exclusion_Present (Parent (Prev))
10240           and then not Null_Exclusion_Present (N)
10241       then
10242          Error_Msg_Sloc := Sloc (Prev);
10243          Error_Msg_N ("null-exclusion does not match declaration#", N);
10244          Set_Full_View (Prev, Id);
10245          Set_Etype (Id, Any_Type);
10246
10247       --  If so, process the full constant declaration
10248
10249       else
10250          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
10251          --  the deferred declaration is constrained, then the subtype defined
10252          --  by the subtype_indication in the full declaration shall match it
10253          --  statically.
10254
10255          Check_Possible_Deferred_Completion
10256            (Prev_Id      => Prev,
10257             Prev_Obj_Def => Object_Definition (Parent (Prev)),
10258             Curr_Obj_Def => Obj_Def);
10259
10260          Set_Full_View (Prev, Id);
10261          Set_Is_Public (Id, Is_Public (Prev));
10262          Set_Is_Internal (Id);
10263          Append_Entity (Id, Current_Scope);
10264
10265          --  Check ALIASED present if present before (RM 7.4(7))
10266
10267          if Is_Aliased (Prev)
10268            and then not Aliased_Present (N)
10269          then
10270             Error_Msg_Sloc := Sloc (Prev);
10271             Error_Msg_N ("ALIASED required (see declaration#)", N);
10272          end if;
10273
10274          --  Check that placement is in private part and that the incomplete
10275          --  declaration appeared in the visible part.
10276
10277          if Ekind (Current_Scope) = E_Package
10278            and then not In_Private_Part (Current_Scope)
10279          then
10280             Error_Msg_Sloc := Sloc (Prev);
10281             Error_Msg_N
10282               ("full constant for declaration#"
10283                & " must be in private part", N);
10284
10285          elsif Ekind (Current_Scope) = E_Package
10286            and then
10287              List_Containing (Parent (Prev)) /=
10288                Visible_Declarations
10289                  (Specification (Unit_Declaration_Node (Current_Scope)))
10290          then
10291             Error_Msg_N
10292               ("deferred constant must be declared in visible part",
10293                  Parent (Prev));
10294          end if;
10295
10296          if Is_Access_Type (T)
10297            and then Nkind (Expression (N)) = N_Allocator
10298          then
10299             Check_Recursive_Declaration (Designated_Type (T));
10300          end if;
10301       end if;
10302    end Constant_Redeclaration;
10303
10304    ----------------------
10305    -- Constrain_Access --
10306    ----------------------
10307
10308    procedure Constrain_Access
10309      (Def_Id      : in out Entity_Id;
10310       S           : Node_Id;
10311       Related_Nod : Node_Id)
10312    is
10313       T             : constant Entity_Id := Entity (Subtype_Mark (S));
10314       Desig_Type    : constant Entity_Id := Designated_Type (T);
10315       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
10316       Constraint_OK : Boolean := True;
10317
10318       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
10319       --  Simple predicate to test for defaulted discriminants
10320       --  Shouldn't this be in sem_util???
10321
10322       ---------------------------------
10323       -- Has_Defaulted_Discriminants --
10324       ---------------------------------
10325
10326       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
10327       begin
10328          return Has_Discriminants (Typ)
10329           and then Present (First_Discriminant (Typ))
10330           and then Present
10331             (Discriminant_Default_Value (First_Discriminant (Typ)));
10332       end Has_Defaulted_Discriminants;
10333
10334    --  Start of processing for Constrain_Access
10335
10336    begin
10337       if Is_Array_Type (Desig_Type) then
10338          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
10339
10340       elsif (Is_Record_Type (Desig_Type)
10341               or else Is_Incomplete_Or_Private_Type (Desig_Type))
10342         and then not Is_Constrained (Desig_Type)
10343       then
10344          --  ??? The following code is a temporary kludge to ignore a
10345          --  discriminant constraint on access type if it is constraining
10346          --  the current record. Avoid creating the implicit subtype of the
10347          --  record we are currently compiling since right now, we cannot
10348          --  handle these. For now, just return the access type itself.
10349
10350          if Desig_Type = Current_Scope
10351            and then No (Def_Id)
10352          then
10353             Set_Ekind (Desig_Subtype, E_Record_Subtype);
10354             Def_Id := Entity (Subtype_Mark (S));
10355
10356             --  This call added to ensure that the constraint is analyzed
10357             --  (needed for a B test). Note that we still return early from
10358             --  this procedure to avoid recursive processing. ???
10359
10360             Constrain_Discriminated_Type
10361               (Desig_Subtype, S, Related_Nod, For_Access => True);
10362             return;
10363          end if;
10364
10365          if (Ekind (T) = E_General_Access_Type
10366               or else Ada_Version >= Ada_2005)
10367            and then Has_Private_Declaration (Desig_Type)
10368            and then In_Open_Scopes (Scope (Desig_Type))
10369            and then Has_Discriminants (Desig_Type)
10370          then
10371             --  Enforce rule that the constraint is illegal if there is
10372             --  an unconstrained view of the designated type. This means
10373             --  that the partial view (either a private type declaration or
10374             --  a derivation from a private type) has no discriminants.
10375             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
10376             --  by ACATS B371001).
10377
10378             --  Rule updated for Ada 2005: the private type is said to have
10379             --  a constrained partial view, given that objects of the type
10380             --  can be declared. Furthermore, the rule applies to all access
10381             --  types, unlike the rule concerning default discriminants.
10382
10383             declare
10384                Pack  : constant Node_Id :=
10385                          Unit_Declaration_Node (Scope (Desig_Type));
10386                Decls : List_Id;
10387                Decl  : Node_Id;
10388
10389             begin
10390                if Nkind (Pack) = N_Package_Declaration then
10391                   Decls := Visible_Declarations (Specification (Pack));
10392                   Decl := First (Decls);
10393                   while Present (Decl) loop
10394                      if (Nkind (Decl) = N_Private_Type_Declaration
10395                           and then
10396                             Chars (Defining_Identifier (Decl)) =
10397                                                      Chars (Desig_Type))
10398
10399                        or else
10400                         (Nkind (Decl) = N_Full_Type_Declaration
10401                           and then
10402                             Chars (Defining_Identifier (Decl)) =
10403                                                      Chars (Desig_Type)
10404                           and then Is_Derived_Type (Desig_Type)
10405                           and then
10406                             Has_Private_Declaration (Etype (Desig_Type)))
10407                      then
10408                         if No (Discriminant_Specifications (Decl)) then
10409                            Error_Msg_N
10410                             ("cannot constrain general access type if " &
10411                                "designated type has constrained partial view",
10412                                 S);
10413                         end if;
10414
10415                         exit;
10416                      end if;
10417
10418                      Next (Decl);
10419                   end loop;
10420                end if;
10421             end;
10422          end if;
10423
10424          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
10425            For_Access => True);
10426
10427       elsif (Is_Task_Type (Desig_Type)
10428               or else Is_Protected_Type (Desig_Type))
10429         and then not Is_Constrained (Desig_Type)
10430       then
10431          Constrain_Concurrent
10432            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
10433
10434       else
10435          Error_Msg_N ("invalid constraint on access type", S);
10436          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
10437          Constraint_OK := False;
10438       end if;
10439
10440       if No (Def_Id) then
10441          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
10442       else
10443          Set_Ekind (Def_Id, E_Access_Subtype);
10444       end if;
10445
10446       if Constraint_OK then
10447          Set_Etype (Def_Id, Base_Type (T));
10448
10449          if Is_Private_Type (Desig_Type) then
10450             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
10451          end if;
10452       else
10453          Set_Etype (Def_Id, Any_Type);
10454       end if;
10455
10456       Set_Size_Info                (Def_Id, T);
10457       Set_Is_Constrained           (Def_Id, Constraint_OK);
10458       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
10459       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
10460       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
10461
10462       Conditional_Delay (Def_Id, T);
10463
10464       --  AI-363 : Subtypes of general access types whose designated types have
10465       --  default discriminants are disallowed. In instances, the rule has to
10466       --  be checked against the actual, of which T is the subtype. In a
10467       --  generic body, the rule is checked assuming that the actual type has
10468       --  defaulted discriminants.
10469
10470       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
10471          if Ekind (Base_Type (T)) = E_General_Access_Type
10472            and then Has_Defaulted_Discriminants (Desig_Type)
10473          then
10474             if Ada_Version < Ada_2005 then
10475                Error_Msg_N
10476                  ("access subtype of general access type would not " &
10477                   "be allowed in Ada 2005?", S);
10478             else
10479                Error_Msg_N
10480                  ("access subtype of general access type not allowed", S);
10481             end if;
10482
10483             Error_Msg_N ("\discriminants have defaults", S);
10484
10485          elsif Is_Access_Type (T)
10486            and then Is_Generic_Type (Desig_Type)
10487            and then Has_Discriminants (Desig_Type)
10488            and then In_Package_Body (Current_Scope)
10489          then
10490             if Ada_Version < Ada_2005 then
10491                Error_Msg_N
10492                  ("access subtype would not be allowed in generic body " &
10493                   "in Ada 2005?", S);
10494             else
10495                Error_Msg_N
10496                  ("access subtype not allowed in generic body", S);
10497             end if;
10498
10499             Error_Msg_N
10500               ("\designated type is a discriminated formal", S);
10501          end if;
10502       end if;
10503    end Constrain_Access;
10504
10505    ---------------------
10506    -- Constrain_Array --
10507    ---------------------
10508
10509    procedure Constrain_Array
10510      (Def_Id      : in out Entity_Id;
10511       SI          : Node_Id;
10512       Related_Nod : Node_Id;
10513       Related_Id  : Entity_Id;
10514       Suffix      : Character)
10515    is
10516       C                     : constant Node_Id := Constraint (SI);
10517       Number_Of_Constraints : Nat := 0;
10518       Index                 : Node_Id;
10519       S, T                  : Entity_Id;
10520       Constraint_OK         : Boolean := True;
10521
10522    begin
10523       T := Entity (Subtype_Mark (SI));
10524
10525       if Ekind (T) in Access_Kind then
10526          T := Designated_Type (T);
10527       end if;
10528
10529       --  If an index constraint follows a subtype mark in a subtype indication
10530       --  then the type or subtype denoted by the subtype mark must not already
10531       --  impose an index constraint. The subtype mark must denote either an
10532       --  unconstrained array type or an access type whose designated type
10533       --  is such an array type... (RM 3.6.1)
10534
10535       if Is_Constrained (T) then
10536          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
10537          Constraint_OK := False;
10538
10539       else
10540          S := First (Constraints (C));
10541          while Present (S) loop
10542             Number_Of_Constraints := Number_Of_Constraints + 1;
10543             Next (S);
10544          end loop;
10545
10546          --  In either case, the index constraint must provide a discrete
10547          --  range for each index of the array type and the type of each
10548          --  discrete range must be the same as that of the corresponding
10549          --  index. (RM 3.6.1)
10550
10551          if Number_Of_Constraints /= Number_Dimensions (T) then
10552             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
10553             Constraint_OK := False;
10554
10555          else
10556             S := First (Constraints (C));
10557             Index := First_Index (T);
10558             Analyze (Index);
10559
10560             --  Apply constraints to each index type
10561
10562             for J in 1 .. Number_Of_Constraints loop
10563                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
10564                Next (Index);
10565                Next (S);
10566             end loop;
10567
10568          end if;
10569       end if;
10570
10571       if No (Def_Id) then
10572          Def_Id :=
10573            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
10574          Set_Parent (Def_Id, Related_Nod);
10575
10576       else
10577          Set_Ekind (Def_Id, E_Array_Subtype);
10578       end if;
10579
10580       Set_Size_Info      (Def_Id,                (T));
10581       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10582       Set_Etype          (Def_Id, Base_Type      (T));
10583
10584       if Constraint_OK then
10585          Set_First_Index (Def_Id, First (Constraints (C)));
10586       else
10587          Set_First_Index (Def_Id, First_Index (T));
10588       end if;
10589
10590       Set_Is_Constrained     (Def_Id, True);
10591       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
10592       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10593
10594       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
10595       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
10596
10597       --  A subtype does not inherit the packed_array_type of is parent. We
10598       --  need to initialize the attribute because if Def_Id is previously
10599       --  analyzed through a limited_with clause, it will have the attributes
10600       --  of an incomplete type, one of which is an Elist that overlaps the
10601       --  Packed_Array_Type field.
10602
10603       Set_Packed_Array_Type (Def_Id, Empty);
10604
10605       --  Build a freeze node if parent still needs one. Also make sure that
10606       --  the Depends_On_Private status is set because the subtype will need
10607       --  reprocessing at the time the base type does, and also we must set a
10608       --  conditional delay.
10609
10610       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
10611       Conditional_Delay (Def_Id, T);
10612    end Constrain_Array;
10613
10614    ------------------------------
10615    -- Constrain_Component_Type --
10616    ------------------------------
10617
10618    function Constrain_Component_Type
10619      (Comp            : Entity_Id;
10620       Constrained_Typ : Entity_Id;
10621       Related_Node    : Node_Id;
10622       Typ             : Entity_Id;
10623       Constraints     : Elist_Id) return Entity_Id
10624    is
10625       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
10626       Compon_Type : constant Entity_Id := Etype (Comp);
10627
10628       function Build_Constrained_Array_Type
10629         (Old_Type : Entity_Id) return Entity_Id;
10630       --  If Old_Type is an array type, one of whose indexes is constrained
10631       --  by a discriminant, build an Itype whose constraint replaces the
10632       --  discriminant with its value in the constraint.
10633
10634       function Build_Constrained_Discriminated_Type
10635         (Old_Type : Entity_Id) return Entity_Id;
10636       --  Ditto for record components
10637
10638       function Build_Constrained_Access_Type
10639         (Old_Type : Entity_Id) return Entity_Id;
10640       --  Ditto for access types. Makes use of previous two functions, to
10641       --  constrain designated type.
10642
10643       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
10644       --  T is an array or discriminated type, C is a list of constraints
10645       --  that apply to T. This routine builds the constrained subtype.
10646
10647       function Is_Discriminant (Expr : Node_Id) return Boolean;
10648       --  Returns True if Expr is a discriminant
10649
10650       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
10651       --  Find the value of discriminant Discrim in Constraint
10652
10653       -----------------------------------
10654       -- Build_Constrained_Access_Type --
10655       -----------------------------------
10656
10657       function Build_Constrained_Access_Type
10658         (Old_Type : Entity_Id) return Entity_Id
10659       is
10660          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
10661          Itype         : Entity_Id;
10662          Desig_Subtype : Entity_Id;
10663          Scop          : Entity_Id;
10664
10665       begin
10666          --  if the original access type was not embedded in the enclosing
10667          --  type definition, there is no need to produce a new access
10668          --  subtype. In fact every access type with an explicit constraint
10669          --  generates an itype whose scope is the enclosing record.
10670
10671          if not Is_Type (Scope (Old_Type)) then
10672             return Old_Type;
10673
10674          elsif Is_Array_Type (Desig_Type) then
10675             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
10676
10677          elsif Has_Discriminants (Desig_Type) then
10678
10679             --  This may be an access type to an enclosing record type for
10680             --  which we are constructing the constrained components. Return
10681             --  the enclosing record subtype. This is not always correct,
10682             --  but avoids infinite recursion. ???
10683
10684             Desig_Subtype := Any_Type;
10685
10686             for J in reverse 0 .. Scope_Stack.Last loop
10687                Scop := Scope_Stack.Table (J).Entity;
10688
10689                if Is_Type (Scop)
10690                  and then Base_Type (Scop) = Base_Type (Desig_Type)
10691                then
10692                   Desig_Subtype := Scop;
10693                end if;
10694
10695                exit when not Is_Type (Scop);
10696             end loop;
10697
10698             if Desig_Subtype = Any_Type then
10699                Desig_Subtype :=
10700                  Build_Constrained_Discriminated_Type (Desig_Type);
10701             end if;
10702
10703          else
10704             return Old_Type;
10705          end if;
10706
10707          if Desig_Subtype /= Desig_Type then
10708
10709             --  The Related_Node better be here or else we won't be able
10710             --  to attach new itypes to a node in the tree.
10711
10712             pragma Assert (Present (Related_Node));
10713
10714             Itype := Create_Itype (E_Access_Subtype, Related_Node);
10715
10716             Set_Etype                    (Itype, Base_Type      (Old_Type));
10717             Set_Size_Info                (Itype,                (Old_Type));
10718             Set_Directly_Designated_Type (Itype, Desig_Subtype);
10719             Set_Depends_On_Private       (Itype, Has_Private_Component
10720                                                                 (Old_Type));
10721             Set_Is_Access_Constant       (Itype, Is_Access_Constant
10722                                                                 (Old_Type));
10723
10724             --  The new itype needs freezing when it depends on a not frozen
10725             --  type and the enclosing subtype needs freezing.
10726
10727             if Has_Delayed_Freeze (Constrained_Typ)
10728               and then not Is_Frozen (Constrained_Typ)
10729             then
10730                Conditional_Delay (Itype, Base_Type (Old_Type));
10731             end if;
10732
10733             return Itype;
10734
10735          else
10736             return Old_Type;
10737          end if;
10738       end Build_Constrained_Access_Type;
10739
10740       ----------------------------------
10741       -- Build_Constrained_Array_Type --
10742       ----------------------------------
10743
10744       function Build_Constrained_Array_Type
10745         (Old_Type : Entity_Id) return Entity_Id
10746       is
10747          Lo_Expr     : Node_Id;
10748          Hi_Expr     : Node_Id;
10749          Old_Index   : Node_Id;
10750          Range_Node  : Node_Id;
10751          Constr_List : List_Id;
10752
10753          Need_To_Create_Itype : Boolean := False;
10754
10755       begin
10756          Old_Index := First_Index (Old_Type);
10757          while Present (Old_Index) loop
10758             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10759
10760             if Is_Discriminant (Lo_Expr)
10761               or else Is_Discriminant (Hi_Expr)
10762             then
10763                Need_To_Create_Itype := True;
10764             end if;
10765
10766             Next_Index (Old_Index);
10767          end loop;
10768
10769          if Need_To_Create_Itype then
10770             Constr_List := New_List;
10771
10772             Old_Index := First_Index (Old_Type);
10773             while Present (Old_Index) loop
10774                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10775
10776                if Is_Discriminant (Lo_Expr) then
10777                   Lo_Expr := Get_Discr_Value (Lo_Expr);
10778                end if;
10779
10780                if Is_Discriminant (Hi_Expr) then
10781                   Hi_Expr := Get_Discr_Value (Hi_Expr);
10782                end if;
10783
10784                Range_Node :=
10785                  Make_Range
10786                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
10787
10788                Append (Range_Node, To => Constr_List);
10789
10790                Next_Index (Old_Index);
10791             end loop;
10792
10793             return Build_Subtype (Old_Type, Constr_List);
10794
10795          else
10796             return Old_Type;
10797          end if;
10798       end Build_Constrained_Array_Type;
10799
10800       ------------------------------------------
10801       -- Build_Constrained_Discriminated_Type --
10802       ------------------------------------------
10803
10804       function Build_Constrained_Discriminated_Type
10805         (Old_Type : Entity_Id) return Entity_Id
10806       is
10807          Expr           : Node_Id;
10808          Constr_List    : List_Id;
10809          Old_Constraint : Elmt_Id;
10810
10811          Need_To_Create_Itype : Boolean := False;
10812
10813       begin
10814          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10815          while Present (Old_Constraint) loop
10816             Expr := Node (Old_Constraint);
10817
10818             if Is_Discriminant (Expr) then
10819                Need_To_Create_Itype := True;
10820             end if;
10821
10822             Next_Elmt (Old_Constraint);
10823          end loop;
10824
10825          if Need_To_Create_Itype then
10826             Constr_List := New_List;
10827
10828             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10829             while Present (Old_Constraint) loop
10830                Expr := Node (Old_Constraint);
10831
10832                if Is_Discriminant (Expr) then
10833                   Expr := Get_Discr_Value (Expr);
10834                end if;
10835
10836                Append (New_Copy_Tree (Expr), To => Constr_List);
10837
10838                Next_Elmt (Old_Constraint);
10839             end loop;
10840
10841             return Build_Subtype (Old_Type, Constr_List);
10842
10843          else
10844             return Old_Type;
10845          end if;
10846       end Build_Constrained_Discriminated_Type;
10847
10848       -------------------
10849       -- Build_Subtype --
10850       -------------------
10851
10852       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
10853          Indic       : Node_Id;
10854          Subtyp_Decl : Node_Id;
10855          Def_Id      : Entity_Id;
10856          Btyp        : Entity_Id := Base_Type (T);
10857
10858       begin
10859          --  The Related_Node better be here or else we won't be able to
10860          --  attach new itypes to a node in the tree.
10861
10862          pragma Assert (Present (Related_Node));
10863
10864          --  If the view of the component's type is incomplete or private
10865          --  with unknown discriminants, then the constraint must be applied
10866          --  to the full type.
10867
10868          if Has_Unknown_Discriminants (Btyp)
10869            and then Present (Underlying_Type (Btyp))
10870          then
10871             Btyp := Underlying_Type (Btyp);
10872          end if;
10873
10874          Indic :=
10875            Make_Subtype_Indication (Loc,
10876              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
10877              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
10878
10879          Def_Id := Create_Itype (Ekind (T), Related_Node);
10880
10881          Subtyp_Decl :=
10882            Make_Subtype_Declaration (Loc,
10883              Defining_Identifier => Def_Id,
10884              Subtype_Indication  => Indic);
10885
10886          Set_Parent (Subtyp_Decl, Parent (Related_Node));
10887
10888          --  Itypes must be analyzed with checks off (see package Itypes)
10889
10890          Analyze (Subtyp_Decl, Suppress => All_Checks);
10891
10892          return Def_Id;
10893       end Build_Subtype;
10894
10895       ---------------------
10896       -- Get_Discr_Value --
10897       ---------------------
10898
10899       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
10900          D : Entity_Id;
10901          E : Elmt_Id;
10902
10903       begin
10904          --  The discriminant may be declared for the type, in which case we
10905          --  find it by iterating over the list of discriminants. If the
10906          --  discriminant is inherited from a parent type, it appears as the
10907          --  corresponding discriminant of the current type. This will be the
10908          --  case when constraining an inherited component whose constraint is
10909          --  given by a discriminant of the parent.
10910
10911          D := First_Discriminant (Typ);
10912          E := First_Elmt (Constraints);
10913
10914          while Present (D) loop
10915             if D = Entity (Discrim)
10916               or else D = CR_Discriminant (Entity (Discrim))
10917               or else Corresponding_Discriminant (D) = Entity (Discrim)
10918             then
10919                return Node (E);
10920             end if;
10921
10922             Next_Discriminant (D);
10923             Next_Elmt (E);
10924          end loop;
10925
10926          --  The Corresponding_Discriminant mechanism is incomplete, because
10927          --  the correspondence between new and old discriminants is not one
10928          --  to one: one new discriminant can constrain several old ones. In
10929          --  that case, scan sequentially the stored_constraint, the list of
10930          --  discriminants of the parents, and the constraints.
10931          --  Previous code checked for the present of the Stored_Constraint
10932          --  list for the derived type, but did not use it at all. Should it
10933          --  be present when the component is a discriminated task type?
10934
10935          if Is_Derived_Type (Typ)
10936            and then Scope (Entity (Discrim)) = Etype (Typ)
10937          then
10938             D := First_Discriminant (Etype (Typ));
10939             E := First_Elmt (Constraints);
10940             while Present (D) loop
10941                if D = Entity (Discrim) then
10942                   return Node (E);
10943                end if;
10944
10945                Next_Discriminant (D);
10946                Next_Elmt (E);
10947             end loop;
10948          end if;
10949
10950          --  Something is wrong if we did not find the value
10951
10952          raise Program_Error;
10953       end Get_Discr_Value;
10954
10955       ---------------------
10956       -- Is_Discriminant --
10957       ---------------------
10958
10959       function Is_Discriminant (Expr : Node_Id) return Boolean is
10960          Discrim_Scope : Entity_Id;
10961
10962       begin
10963          if Denotes_Discriminant (Expr) then
10964             Discrim_Scope := Scope (Entity (Expr));
10965
10966             --  Either we have a reference to one of Typ's discriminants,
10967
10968             pragma Assert (Discrim_Scope = Typ
10969
10970                --  or to the discriminants of the parent type, in the case
10971                --  of a derivation of a tagged type with variants.
10972
10973                or else Discrim_Scope = Etype (Typ)
10974                or else Full_View (Discrim_Scope) = Etype (Typ)
10975
10976                --  or same as above for the case where the discriminants
10977                --  were declared in Typ's private view.
10978
10979                or else (Is_Private_Type (Discrim_Scope)
10980                         and then Chars (Discrim_Scope) = Chars (Typ))
10981
10982                --  or else we are deriving from the full view and the
10983                --  discriminant is declared in the private entity.
10984
10985                or else (Is_Private_Type (Typ)
10986                          and then Chars (Discrim_Scope) = Chars (Typ))
10987
10988                --  Or we are constrained the corresponding record of a
10989                --  synchronized type that completes a private declaration.
10990
10991                or else (Is_Concurrent_Record_Type (Typ)
10992                          and then
10993                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
10994
10995                --  or we have a class-wide type, in which case make sure the
10996                --  discriminant found belongs to the root type.
10997
10998                or else (Is_Class_Wide_Type (Typ)
10999                          and then Etype (Typ) = Discrim_Scope));
11000
11001             return True;
11002          end if;
11003
11004          --  In all other cases we have something wrong
11005
11006          return False;
11007       end Is_Discriminant;
11008
11009    --  Start of processing for Constrain_Component_Type
11010
11011    begin
11012       if Nkind (Parent (Comp)) = N_Component_Declaration
11013         and then Comes_From_Source (Parent (Comp))
11014         and then Comes_From_Source
11015           (Subtype_Indication (Component_Definition (Parent (Comp))))
11016         and then
11017           Is_Entity_Name
11018             (Subtype_Indication (Component_Definition (Parent (Comp))))
11019       then
11020          return Compon_Type;
11021
11022       elsif Is_Array_Type (Compon_Type) then
11023          return Build_Constrained_Array_Type (Compon_Type);
11024
11025       elsif Has_Discriminants (Compon_Type) then
11026          return Build_Constrained_Discriminated_Type (Compon_Type);
11027
11028       elsif Is_Access_Type (Compon_Type) then
11029          return Build_Constrained_Access_Type (Compon_Type);
11030
11031       else
11032          return Compon_Type;
11033       end if;
11034    end Constrain_Component_Type;
11035
11036    --------------------------
11037    -- Constrain_Concurrent --
11038    --------------------------
11039
11040    --  For concurrent types, the associated record value type carries the same
11041    --  discriminants, so when we constrain a concurrent type, we must constrain
11042    --  the corresponding record type as well.
11043
11044    procedure Constrain_Concurrent
11045      (Def_Id      : in out Entity_Id;
11046       SI          : Node_Id;
11047       Related_Nod : Node_Id;
11048       Related_Id  : Entity_Id;
11049       Suffix      : Character)
11050    is
11051       T_Ent : Entity_Id := Entity (Subtype_Mark (SI));
11052       T_Val : Entity_Id;
11053
11054    begin
11055       if Ekind (T_Ent) in Access_Kind then
11056          T_Ent := Designated_Type (T_Ent);
11057       end if;
11058
11059       T_Val := Corresponding_Record_Type (T_Ent);
11060
11061       if Present (T_Val) then
11062
11063          if No (Def_Id) then
11064             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11065          end if;
11066
11067          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11068
11069          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
11070          Set_Corresponding_Record_Type (Def_Id,
11071            Constrain_Corresponding_Record
11072              (Def_Id, T_Val, Related_Nod, Related_Id));
11073
11074       else
11075          --  If there is no associated record, expansion is disabled and this
11076          --  is a generic context. Create a subtype in any case, so that
11077          --  semantic analysis can proceed.
11078
11079          if No (Def_Id) then
11080             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11081          end if;
11082
11083          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11084       end if;
11085    end Constrain_Concurrent;
11086
11087    ------------------------------------
11088    -- Constrain_Corresponding_Record --
11089    ------------------------------------
11090
11091    function Constrain_Corresponding_Record
11092      (Prot_Subt   : Entity_Id;
11093       Corr_Rec    : Entity_Id;
11094       Related_Nod : Node_Id;
11095       Related_Id  : Entity_Id) return Entity_Id
11096    is
11097       T_Sub : constant Entity_Id :=
11098                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
11099
11100    begin
11101       Set_Etype             (T_Sub, Corr_Rec);
11102       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
11103       Set_Is_Constrained    (T_Sub, True);
11104       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
11105       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
11106
11107       --  As elsewhere, we do not want to create a freeze node for this itype
11108       --  if it is created for a constrained component of an enclosing record
11109       --  because references to outer discriminants will appear out of scope.
11110
11111       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
11112          Conditional_Delay (T_Sub, Corr_Rec);
11113       else
11114          Set_Is_Frozen (T_Sub);
11115       end if;
11116
11117       if Has_Discriminants (Prot_Subt) then -- False only if errors.
11118          Set_Discriminant_Constraint
11119            (T_Sub, Discriminant_Constraint (Prot_Subt));
11120          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
11121          Create_Constrained_Components
11122            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
11123       end if;
11124
11125       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
11126
11127       return T_Sub;
11128    end Constrain_Corresponding_Record;
11129
11130    -----------------------
11131    -- Constrain_Decimal --
11132    -----------------------
11133
11134    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
11135       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
11136       C           : constant Node_Id    := Constraint (S);
11137       Loc         : constant Source_Ptr := Sloc (C);
11138       Range_Expr  : Node_Id;
11139       Digits_Expr : Node_Id;
11140       Digits_Val  : Uint;
11141       Bound_Val   : Ureal;
11142
11143    begin
11144       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
11145
11146       if Nkind (C) = N_Range_Constraint then
11147          Range_Expr := Range_Expression (C);
11148          Digits_Val := Digits_Value (T);
11149
11150       else
11151          pragma Assert (Nkind (C) = N_Digits_Constraint);
11152          Digits_Expr := Digits_Expression (C);
11153          Analyze_And_Resolve (Digits_Expr, Any_Integer);
11154
11155          Check_Digits_Expression (Digits_Expr);
11156          Digits_Val := Expr_Value (Digits_Expr);
11157
11158          if Digits_Val > Digits_Value (T) then
11159             Error_Msg_N
11160                ("digits expression is incompatible with subtype", C);
11161             Digits_Val := Digits_Value (T);
11162          end if;
11163
11164          if Present (Range_Constraint (C)) then
11165             Range_Expr := Range_Expression (Range_Constraint (C));
11166          else
11167             Range_Expr := Empty;
11168          end if;
11169       end if;
11170
11171       Set_Etype            (Def_Id, Base_Type        (T));
11172       Set_Size_Info        (Def_Id,                  (T));
11173       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11174       Set_Delta_Value      (Def_Id, Delta_Value      (T));
11175       Set_Scale_Value      (Def_Id, Scale_Value      (T));
11176       Set_Small_Value      (Def_Id, Small_Value      (T));
11177       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
11178       Set_Digits_Value     (Def_Id, Digits_Val);
11179
11180       --  Manufacture range from given digits value if no range present
11181
11182       if No (Range_Expr) then
11183          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
11184          Range_Expr :=
11185            Make_Range (Loc,
11186              Low_Bound =>
11187                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
11188              High_Bound =>
11189                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
11190       end if;
11191
11192       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
11193       Set_Discrete_RM_Size (Def_Id);
11194
11195       --  Unconditionally delay the freeze, since we cannot set size
11196       --  information in all cases correctly until the freeze point.
11197
11198       Set_Has_Delayed_Freeze (Def_Id);
11199    end Constrain_Decimal;
11200
11201    ----------------------------------
11202    -- Constrain_Discriminated_Type --
11203    ----------------------------------
11204
11205    procedure Constrain_Discriminated_Type
11206      (Def_Id      : Entity_Id;
11207       S           : Node_Id;
11208       Related_Nod : Node_Id;
11209       For_Access  : Boolean := False)
11210    is
11211       E     : constant Entity_Id := Entity (Subtype_Mark (S));
11212       T     : Entity_Id;
11213       C     : Node_Id;
11214       Elist : Elist_Id := New_Elmt_List;
11215
11216       procedure Fixup_Bad_Constraint;
11217       --  This is called after finding a bad constraint, and after having
11218       --  posted an appropriate error message. The mission is to leave the
11219       --  entity T in as reasonable state as possible!
11220
11221       --------------------------
11222       -- Fixup_Bad_Constraint --
11223       --------------------------
11224
11225       procedure Fixup_Bad_Constraint is
11226       begin
11227          --  Set a reasonable Ekind for the entity. For an incomplete type,
11228          --  we can't do much, but for other types, we can set the proper
11229          --  corresponding subtype kind.
11230
11231          if Ekind (T) = E_Incomplete_Type then
11232             Set_Ekind (Def_Id, Ekind (T));
11233          else
11234             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
11235          end if;
11236
11237          --  Set Etype to the known type, to reduce chances of cascaded errors
11238
11239          Set_Etype (Def_Id, E);
11240          Set_Error_Posted (Def_Id);
11241       end Fixup_Bad_Constraint;
11242
11243    --  Start of processing for Constrain_Discriminated_Type
11244
11245    begin
11246       C := Constraint (S);
11247
11248       --  A discriminant constraint is only allowed in a subtype indication,
11249       --  after a subtype mark. This subtype mark must denote either a type
11250       --  with discriminants, or an access type whose designated type is a
11251       --  type with discriminants. A discriminant constraint specifies the
11252       --  values of these discriminants (RM 3.7.2(5)).
11253
11254       T := Base_Type (Entity (Subtype_Mark (S)));
11255
11256       if Ekind (T) in Access_Kind then
11257          T := Designated_Type (T);
11258       end if;
11259
11260       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
11261       --  Avoid generating an error for access-to-incomplete subtypes.
11262
11263       if Ada_Version >= Ada_2005
11264         and then Ekind (T) = E_Incomplete_Type
11265         and then Nkind (Parent (S)) = N_Subtype_Declaration
11266         and then not Is_Itype (Def_Id)
11267       then
11268          --  A little sanity check, emit an error message if the type
11269          --  has discriminants to begin with. Type T may be a regular
11270          --  incomplete type or imported via a limited with clause.
11271
11272          if Has_Discriminants (T)
11273            or else
11274              (From_With_Type (T)
11275                 and then Present (Non_Limited_View (T))
11276                 and then Nkind (Parent (Non_Limited_View (T))) =
11277                            N_Full_Type_Declaration
11278                 and then Present (Discriminant_Specifications
11279                           (Parent (Non_Limited_View (T)))))
11280          then
11281             Error_Msg_N
11282               ("(Ada 2005) incomplete subtype may not be constrained", C);
11283          else
11284             Error_Msg_N ("invalid constraint: type has no discriminant", C);
11285          end if;
11286
11287          Fixup_Bad_Constraint;
11288          return;
11289
11290       --  Check that the type has visible discriminants. The type may be
11291       --  a private type with unknown discriminants whose full view has
11292       --  discriminants which are invisible.
11293
11294       elsif not Has_Discriminants (T)
11295         or else
11296           (Has_Unknown_Discriminants (T)
11297              and then Is_Private_Type (T))
11298       then
11299          Error_Msg_N ("invalid constraint: type has no discriminant", C);
11300          Fixup_Bad_Constraint;
11301          return;
11302
11303       elsif Is_Constrained (E)
11304         or else (Ekind (E) = E_Class_Wide_Subtype
11305                   and then Present (Discriminant_Constraint (E)))
11306       then
11307          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
11308          Fixup_Bad_Constraint;
11309          return;
11310       end if;
11311
11312       --  T may be an unconstrained subtype (e.g. a generic actual).
11313       --  Constraint applies to the base type.
11314
11315       T := Base_Type (T);
11316
11317       Elist := Build_Discriminant_Constraints (T, S);
11318
11319       --  If the list returned was empty we had an error in building the
11320       --  discriminant constraint. We have also already signalled an error
11321       --  in the incomplete type case
11322
11323       if Is_Empty_Elmt_List (Elist) then
11324          Fixup_Bad_Constraint;
11325          return;
11326       end if;
11327
11328       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
11329    end Constrain_Discriminated_Type;
11330
11331    ---------------------------
11332    -- Constrain_Enumeration --
11333    ---------------------------
11334
11335    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
11336       T : constant Entity_Id := Entity (Subtype_Mark (S));
11337       C : constant Node_Id   := Constraint (S);
11338
11339    begin
11340       Set_Ekind (Def_Id, E_Enumeration_Subtype);
11341
11342       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
11343
11344       Set_Etype             (Def_Id, Base_Type         (T));
11345       Set_Size_Info         (Def_Id,                   (T));
11346       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
11347       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11348
11349       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11350
11351       Set_Discrete_RM_Size (Def_Id);
11352    end Constrain_Enumeration;
11353
11354    ----------------------
11355    -- Constrain_Float --
11356    ----------------------
11357
11358    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
11359       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11360       C    : Node_Id;
11361       D    : Node_Id;
11362       Rais : Node_Id;
11363
11364    begin
11365       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
11366
11367       Set_Etype          (Def_Id, Base_Type      (T));
11368       Set_Size_Info      (Def_Id,                (T));
11369       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11370
11371       --  Process the constraint
11372
11373       C := Constraint (S);
11374
11375       --  Digits constraint present
11376
11377       if Nkind (C) = N_Digits_Constraint then
11378          Check_Restriction (No_Obsolescent_Features, C);
11379
11380          if Warn_On_Obsolescent_Feature then
11381             Error_Msg_N
11382               ("subtype digits constraint is an " &
11383                "obsolescent feature (RM J.3(8))?", C);
11384          end if;
11385
11386          D := Digits_Expression (C);
11387          Analyze_And_Resolve (D, Any_Integer);
11388          Check_Digits_Expression (D);
11389          Set_Digits_Value (Def_Id, Expr_Value (D));
11390
11391          --  Check that digits value is in range. Obviously we can do this
11392          --  at compile time, but it is strictly a runtime check, and of
11393          --  course there is an ACVC test that checks this!
11394
11395          if Digits_Value (Def_Id) > Digits_Value (T) then
11396             Error_Msg_Uint_1 := Digits_Value (T);
11397             Error_Msg_N ("?digits value is too large, maximum is ^", D);
11398             Rais :=
11399               Make_Raise_Constraint_Error (Sloc (D),
11400                 Reason => CE_Range_Check_Failed);
11401             Insert_Action (Declaration_Node (Def_Id), Rais);
11402          end if;
11403
11404          C := Range_Constraint (C);
11405
11406       --  No digits constraint present
11407
11408       else
11409          Set_Digits_Value (Def_Id, Digits_Value (T));
11410       end if;
11411
11412       --  Range constraint present
11413
11414       if Nkind (C) = N_Range_Constraint then
11415          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11416
11417       --  No range constraint present
11418
11419       else
11420          pragma Assert (No (C));
11421          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11422       end if;
11423
11424       Set_Is_Constrained (Def_Id);
11425    end Constrain_Float;
11426
11427    ---------------------
11428    -- Constrain_Index --
11429    ---------------------
11430
11431    procedure Constrain_Index
11432      (Index        : Node_Id;
11433       S            : Node_Id;
11434       Related_Nod  : Node_Id;
11435       Related_Id   : Entity_Id;
11436       Suffix       : Character;
11437       Suffix_Index : Nat)
11438    is
11439       Def_Id : Entity_Id;
11440       R      : Node_Id := Empty;
11441       T      : constant Entity_Id := Etype (Index);
11442
11443    begin
11444       if Nkind (S) = N_Range
11445         or else
11446           (Nkind (S) = N_Attribute_Reference
11447             and then Attribute_Name (S) = Name_Range)
11448       then
11449          --  A Range attribute will transformed into N_Range by Resolve
11450
11451          Analyze (S);
11452          Set_Etype (S, T);
11453          R := S;
11454
11455          Process_Range_Expr_In_Decl (R, T, Empty_List);
11456
11457          if not Error_Posted (S)
11458            and then
11459              (Nkind (S) /= N_Range
11460                or else not Covers (T, (Etype (Low_Bound (S))))
11461                or else not Covers (T, (Etype (High_Bound (S)))))
11462          then
11463             if Base_Type (T) /= Any_Type
11464               and then Etype (Low_Bound (S)) /= Any_Type
11465               and then Etype (High_Bound (S)) /= Any_Type
11466             then
11467                Error_Msg_N ("range expected", S);
11468             end if;
11469          end if;
11470
11471       elsif Nkind (S) = N_Subtype_Indication then
11472
11473          --  The parser has verified that this is a discrete indication
11474
11475          Resolve_Discrete_Subtype_Indication (S, T);
11476          R := Range_Expression (Constraint (S));
11477
11478          --  Capture values of bounds and generate temporaries for them if
11479          --  needed, since checks may cause duplication of the expressions
11480          --  which must not be reevaluated.
11481
11482          if Expander_Active then
11483             Force_Evaluation (Low_Bound (R));
11484             Force_Evaluation (High_Bound (R));
11485          end if;
11486
11487       elsif Nkind (S) = N_Discriminant_Association then
11488
11489          --  Syntactically valid in subtype indication
11490
11491          Error_Msg_N ("invalid index constraint", S);
11492          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11493          return;
11494
11495       --  Subtype_Mark case, no anonymous subtypes to construct
11496
11497       else
11498          Analyze (S);
11499
11500          if Is_Entity_Name (S) then
11501             if not Is_Type (Entity (S)) then
11502                Error_Msg_N ("expect subtype mark for index constraint", S);
11503
11504             elsif Base_Type (Entity (S)) /= Base_Type (T) then
11505                Wrong_Type (S, Base_Type (T));
11506
11507             --  Check error of subtype with predicate in index constraint
11508
11509             else
11510                Bad_Predicated_Subtype_Use
11511                  ("subtype& has predicate, not allowed in index constraint",
11512                   S, Entity (S));
11513             end if;
11514
11515             return;
11516
11517          else
11518             Error_Msg_N ("invalid index constraint", S);
11519             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11520             return;
11521          end if;
11522       end if;
11523
11524       Def_Id :=
11525         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
11526
11527       Set_Etype (Def_Id, Base_Type (T));
11528
11529       if Is_Modular_Integer_Type (T) then
11530          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11531
11532       elsif Is_Integer_Type (T) then
11533          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11534
11535       else
11536          Set_Ekind (Def_Id, E_Enumeration_Subtype);
11537          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11538          Set_First_Literal     (Def_Id, First_Literal (T));
11539       end if;
11540
11541       Set_Size_Info      (Def_Id,                (T));
11542       Set_RM_Size        (Def_Id, RM_Size        (T));
11543       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11544
11545       Set_Scalar_Range   (Def_Id, R);
11546
11547       Set_Etype (S, Def_Id);
11548       Set_Discrete_RM_Size (Def_Id);
11549    end Constrain_Index;
11550
11551    -----------------------
11552    -- Constrain_Integer --
11553    -----------------------
11554
11555    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
11556       T : constant Entity_Id := Entity (Subtype_Mark (S));
11557       C : constant Node_Id   := Constraint (S);
11558
11559    begin
11560       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11561
11562       if Is_Modular_Integer_Type (T) then
11563          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11564       else
11565          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11566       end if;
11567
11568       Set_Etype            (Def_Id, Base_Type        (T));
11569       Set_Size_Info        (Def_Id,                  (T));
11570       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11571       Set_Discrete_RM_Size (Def_Id);
11572    end Constrain_Integer;
11573
11574    ------------------------------
11575    -- Constrain_Ordinary_Fixed --
11576    ------------------------------
11577
11578    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
11579       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11580       C    : Node_Id;
11581       D    : Node_Id;
11582       Rais : Node_Id;
11583
11584    begin
11585       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
11586       Set_Etype          (Def_Id, Base_Type        (T));
11587       Set_Size_Info      (Def_Id,                  (T));
11588       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
11589       Set_Small_Value    (Def_Id, Small_Value      (T));
11590
11591       --  Process the constraint
11592
11593       C := Constraint (S);
11594
11595       --  Delta constraint present
11596
11597       if Nkind (C) = N_Delta_Constraint then
11598          Check_Restriction (No_Obsolescent_Features, C);
11599
11600          if Warn_On_Obsolescent_Feature then
11601             Error_Msg_S
11602               ("subtype delta constraint is an " &
11603                "obsolescent feature (RM J.3(7))?");
11604          end if;
11605
11606          D := Delta_Expression (C);
11607          Analyze_And_Resolve (D, Any_Real);
11608          Check_Delta_Expression (D);
11609          Set_Delta_Value (Def_Id, Expr_Value_R (D));
11610
11611          --  Check that delta value is in range. Obviously we can do this
11612          --  at compile time, but it is strictly a runtime check, and of
11613          --  course there is an ACVC test that checks this!
11614
11615          if Delta_Value (Def_Id) < Delta_Value (T) then
11616             Error_Msg_N ("?delta value is too small", D);
11617             Rais :=
11618               Make_Raise_Constraint_Error (Sloc (D),
11619                 Reason => CE_Range_Check_Failed);
11620             Insert_Action (Declaration_Node (Def_Id), Rais);
11621          end if;
11622
11623          C := Range_Constraint (C);
11624
11625       --  No delta constraint present
11626
11627       else
11628          Set_Delta_Value (Def_Id, Delta_Value (T));
11629       end if;
11630
11631       --  Range constraint present
11632
11633       if Nkind (C) = N_Range_Constraint then
11634          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11635
11636       --  No range constraint present
11637
11638       else
11639          pragma Assert (No (C));
11640          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11641
11642       end if;
11643
11644       Set_Discrete_RM_Size (Def_Id);
11645
11646       --  Unconditionally delay the freeze, since we cannot set size
11647       --  information in all cases correctly until the freeze point.
11648
11649       Set_Has_Delayed_Freeze (Def_Id);
11650    end Constrain_Ordinary_Fixed;
11651
11652    -----------------------
11653    -- Contain_Interface --
11654    -----------------------
11655
11656    function Contain_Interface
11657      (Iface  : Entity_Id;
11658       Ifaces : Elist_Id) return Boolean
11659    is
11660       Iface_Elmt : Elmt_Id;
11661
11662    begin
11663       if Present (Ifaces) then
11664          Iface_Elmt := First_Elmt (Ifaces);
11665          while Present (Iface_Elmt) loop
11666             if Node (Iface_Elmt) = Iface then
11667                return True;
11668             end if;
11669
11670             Next_Elmt (Iface_Elmt);
11671          end loop;
11672       end if;
11673
11674       return False;
11675    end Contain_Interface;
11676
11677    ---------------------------
11678    -- Convert_Scalar_Bounds --
11679    ---------------------------
11680
11681    procedure Convert_Scalar_Bounds
11682      (N            : Node_Id;
11683       Parent_Type  : Entity_Id;
11684       Derived_Type : Entity_Id;
11685       Loc          : Source_Ptr)
11686    is
11687       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
11688
11689       Lo  : Node_Id;
11690       Hi  : Node_Id;
11691       Rng : Node_Id;
11692
11693    begin
11694       --  Defend against previous errors
11695
11696       if No (Scalar_Range (Derived_Type)) then
11697          return;
11698       end if;
11699
11700       Lo := Build_Scalar_Bound
11701               (Type_Low_Bound (Derived_Type),
11702                Parent_Type, Implicit_Base);
11703
11704       Hi := Build_Scalar_Bound
11705               (Type_High_Bound (Derived_Type),
11706                Parent_Type, Implicit_Base);
11707
11708       Rng :=
11709         Make_Range (Loc,
11710           Low_Bound  => Lo,
11711           High_Bound => Hi);
11712
11713       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
11714
11715       Set_Parent (Rng, N);
11716       Set_Scalar_Range (Derived_Type, Rng);
11717
11718       --  Analyze the bounds
11719
11720       Analyze_And_Resolve (Lo, Implicit_Base);
11721       Analyze_And_Resolve (Hi, Implicit_Base);
11722
11723       --  Analyze the range itself, except that we do not analyze it if
11724       --  the bounds are real literals, and we have a fixed-point type.
11725       --  The reason for this is that we delay setting the bounds in this
11726       --  case till we know the final Small and Size values (see circuit
11727       --  in Freeze.Freeze_Fixed_Point_Type for further details).
11728
11729       if Is_Fixed_Point_Type (Parent_Type)
11730         and then Nkind (Lo) = N_Real_Literal
11731         and then Nkind (Hi) = N_Real_Literal
11732       then
11733          return;
11734
11735       --  Here we do the analysis of the range
11736
11737       --  Note: we do this manually, since if we do a normal Analyze and
11738       --  Resolve call, there are problems with the conversions used for
11739       --  the derived type range.
11740
11741       else
11742          Set_Etype    (Rng, Implicit_Base);
11743          Set_Analyzed (Rng, True);
11744       end if;
11745    end Convert_Scalar_Bounds;
11746
11747    -------------------
11748    -- Copy_And_Swap --
11749    -------------------
11750
11751    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
11752    begin
11753       --  Initialize new full declaration entity by copying the pertinent
11754       --  fields of the corresponding private declaration entity.
11755
11756       --  We temporarily set Ekind to a value appropriate for a type to
11757       --  avoid assert failures in Einfo from checking for setting type
11758       --  attributes on something that is not a type. Ekind (Priv) is an
11759       --  appropriate choice, since it allowed the attributes to be set
11760       --  in the first place. This Ekind value will be modified later.
11761
11762       Set_Ekind (Full, Ekind (Priv));
11763
11764       --  Also set Etype temporarily to Any_Type, again, in the absence
11765       --  of errors, it will be properly reset, and if there are errors,
11766       --  then we want a value of Any_Type to remain.
11767
11768       Set_Etype (Full, Any_Type);
11769
11770       --  Now start copying attributes
11771
11772       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
11773
11774       if Has_Discriminants (Full) then
11775          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
11776          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
11777       end if;
11778
11779       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
11780       Set_Homonym                    (Full, Homonym                 (Priv));
11781       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
11782       Set_Is_Public                  (Full, Is_Public               (Priv));
11783       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
11784       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
11785       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
11786       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
11787       Set_Has_Pragma_Unreferenced_Objects
11788                                      (Full, Has_Pragma_Unreferenced_Objects
11789                                                                     (Priv));
11790
11791       Conditional_Delay              (Full,                          Priv);
11792
11793       if Is_Tagged_Type (Full) then
11794          Set_Direct_Primitive_Operations (Full,
11795            Direct_Primitive_Operations (Priv));
11796
11797          if Is_Base_Type (Priv) then
11798             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
11799          end if;
11800       end if;
11801
11802       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
11803       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
11804       Set_Scope                      (Full, Scope                   (Priv));
11805       Set_Next_Entity                (Full, Next_Entity             (Priv));
11806       Set_First_Entity               (Full, First_Entity            (Priv));
11807       Set_Last_Entity                (Full, Last_Entity             (Priv));
11808
11809       --  If access types have been recorded for later handling, keep them in
11810       --  the full view so that they get handled when the full view freeze
11811       --  node is expanded.
11812
11813       if Present (Freeze_Node (Priv))
11814         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
11815       then
11816          Ensure_Freeze_Node (Full);
11817          Set_Access_Types_To_Process
11818            (Freeze_Node (Full),
11819             Access_Types_To_Process (Freeze_Node (Priv)));
11820       end if;
11821
11822       --  Swap the two entities. Now Private is the full type entity and Full
11823       --  is the private one. They will be swapped back at the end of the
11824       --  private part. This swapping ensures that the entity that is visible
11825       --  in the private part is the full declaration.
11826
11827       Exchange_Entities (Priv, Full);
11828       Append_Entity (Full, Scope (Full));
11829    end Copy_And_Swap;
11830
11831    -------------------------------------
11832    -- Copy_Array_Base_Type_Attributes --
11833    -------------------------------------
11834
11835    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
11836    begin
11837       Set_Component_Alignment      (T1, Component_Alignment      (T2));
11838       Set_Component_Type           (T1, Component_Type           (T2));
11839       Set_Component_Size           (T1, Component_Size           (T2));
11840       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
11841       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
11842       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
11843       Set_Has_Task                 (T1, Has_Task                 (T2));
11844       Set_Is_Packed                (T1, Is_Packed                (T2));
11845       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
11846       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
11847       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
11848    end Copy_Array_Base_Type_Attributes;
11849
11850    -----------------------------------
11851    -- Copy_Array_Subtype_Attributes --
11852    -----------------------------------
11853
11854    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
11855    begin
11856       Set_Size_Info (T1, T2);
11857
11858       Set_First_Index          (T1, First_Index           (T2));
11859       Set_Is_Aliased           (T1, Is_Aliased            (T2));
11860       Set_Is_Atomic            (T1, Is_Atomic             (T2));
11861       Set_Is_Volatile          (T1, Is_Volatile           (T2));
11862       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
11863       Set_Is_Constrained       (T1, Is_Constrained        (T2));
11864       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
11865       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
11866       Set_Convention           (T1, Convention            (T2));
11867       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
11868       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
11869       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
11870    end Copy_Array_Subtype_Attributes;
11871
11872    -----------------------------------
11873    -- Create_Constrained_Components --
11874    -----------------------------------
11875
11876    procedure Create_Constrained_Components
11877      (Subt        : Entity_Id;
11878       Decl_Node   : Node_Id;
11879       Typ         : Entity_Id;
11880       Constraints : Elist_Id)
11881    is
11882       Loc         : constant Source_Ptr := Sloc (Subt);
11883       Comp_List   : constant Elist_Id   := New_Elmt_List;
11884       Parent_Type : constant Entity_Id  := Etype (Typ);
11885       Assoc_List  : constant List_Id    := New_List;
11886       Discr_Val   : Elmt_Id;
11887       Errors      : Boolean;
11888       New_C       : Entity_Id;
11889       Old_C       : Entity_Id;
11890       Is_Static   : Boolean := True;
11891
11892       procedure Collect_Fixed_Components (Typ : Entity_Id);
11893       --  Collect parent type components that do not appear in a variant part
11894
11895       procedure Create_All_Components;
11896       --  Iterate over Comp_List to create the components of the subtype
11897
11898       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
11899       --  Creates a new component from Old_Compon, copying all the fields from
11900       --  it, including its Etype, inserts the new component in the Subt entity
11901       --  chain and returns the new component.
11902
11903       function Is_Variant_Record (T : Entity_Id) return Boolean;
11904       --  If true, and discriminants are static, collect only components from
11905       --  variants selected by discriminant values.
11906
11907       ------------------------------
11908       -- Collect_Fixed_Components --
11909       ------------------------------
11910
11911       procedure Collect_Fixed_Components (Typ : Entity_Id) is
11912       begin
11913       --  Build association list for discriminants, and find components of the
11914       --  variant part selected by the values of the discriminants.
11915
11916          Old_C := First_Discriminant (Typ);
11917          Discr_Val := First_Elmt (Constraints);
11918          while Present (Old_C) loop
11919             Append_To (Assoc_List,
11920               Make_Component_Association (Loc,
11921                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
11922                  Expression => New_Copy (Node (Discr_Val))));
11923
11924             Next_Elmt (Discr_Val);
11925             Next_Discriminant (Old_C);
11926          end loop;
11927
11928          --  The tag, and the possible parent and controller components
11929          --  are unconditionally in the subtype.
11930
11931          if Is_Tagged_Type (Typ)
11932            or else Has_Controlled_Component (Typ)
11933          then
11934             Old_C := First_Component (Typ);
11935             while Present (Old_C) loop
11936                if Chars ((Old_C)) = Name_uTag
11937                  or else Chars ((Old_C)) = Name_uParent
11938                  or else Chars ((Old_C)) = Name_uController
11939                then
11940                   Append_Elmt (Old_C, Comp_List);
11941                end if;
11942
11943                Next_Component (Old_C);
11944             end loop;
11945          end if;
11946       end Collect_Fixed_Components;
11947
11948       ---------------------------
11949       -- Create_All_Components --
11950       ---------------------------
11951
11952       procedure Create_All_Components is
11953          Comp : Elmt_Id;
11954
11955       begin
11956          Comp := First_Elmt (Comp_List);
11957          while Present (Comp) loop
11958             Old_C := Node (Comp);
11959             New_C := Create_Component (Old_C);
11960
11961             Set_Etype
11962               (New_C,
11963                Constrain_Component_Type
11964                  (Old_C, Subt, Decl_Node, Typ, Constraints));
11965             Set_Is_Public (New_C, Is_Public (Subt));
11966
11967             Next_Elmt (Comp);
11968          end loop;
11969       end Create_All_Components;
11970
11971       ----------------------
11972       -- Create_Component --
11973       ----------------------
11974
11975       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
11976          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
11977
11978       begin
11979          if Ekind (Old_Compon) = E_Discriminant
11980            and then Is_Completely_Hidden (Old_Compon)
11981          then
11982             --  This is a shadow discriminant created for a discriminant of
11983             --  the parent type, which needs to be present in the subtype.
11984             --  Give the shadow discriminant an internal name that cannot
11985             --  conflict with that of visible components.
11986
11987             Set_Chars (New_Compon, New_Internal_Name ('C'));
11988          end if;
11989
11990          --  Set the parent so we have a proper link for freezing etc. This is
11991          --  not a real parent pointer, since of course our parent does not own
11992          --  up to us and reference us, we are an illegitimate child of the
11993          --  original parent!
11994
11995          Set_Parent (New_Compon, Parent (Old_Compon));
11996
11997          --  If the old component's Esize was already determined and is a
11998          --  static value, then the new component simply inherits it. Otherwise
11999          --  the old component's size may require run-time determination, but
12000          --  the new component's size still might be statically determinable
12001          --  (if, for example it has a static constraint). In that case we want
12002          --  Layout_Type to recompute the component's size, so we reset its
12003          --  size and positional fields.
12004
12005          if Frontend_Layout_On_Target
12006            and then not Known_Static_Esize (Old_Compon)
12007          then
12008             Set_Esize (New_Compon, Uint_0);
12009             Init_Normalized_First_Bit    (New_Compon);
12010             Init_Normalized_Position     (New_Compon);
12011             Init_Normalized_Position_Max (New_Compon);
12012          end if;
12013
12014          --  We do not want this node marked as Comes_From_Source, since
12015          --  otherwise it would get first class status and a separate cross-
12016          --  reference line would be generated. Illegitimate children do not
12017          --  rate such recognition.
12018
12019          Set_Comes_From_Source (New_Compon, False);
12020
12021          --  But it is a real entity, and a birth certificate must be properly
12022          --  registered by entering it into the entity list.
12023
12024          Enter_Name (New_Compon);
12025
12026          return New_Compon;
12027       end Create_Component;
12028
12029       -----------------------
12030       -- Is_Variant_Record --
12031       -----------------------
12032
12033       function Is_Variant_Record (T : Entity_Id) return Boolean is
12034       begin
12035          return Nkind (Parent (T)) = N_Full_Type_Declaration
12036            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
12037            and then Present (Component_List (Type_Definition (Parent (T))))
12038            and then
12039              Present
12040                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
12041       end Is_Variant_Record;
12042
12043    --  Start of processing for Create_Constrained_Components
12044
12045    begin
12046       pragma Assert (Subt /= Base_Type (Subt));
12047       pragma Assert (Typ = Base_Type (Typ));
12048
12049       Set_First_Entity (Subt, Empty);
12050       Set_Last_Entity  (Subt, Empty);
12051
12052       --  Check whether constraint is fully static, in which case we can
12053       --  optimize the list of components.
12054
12055       Discr_Val := First_Elmt (Constraints);
12056       while Present (Discr_Val) loop
12057          if not Is_OK_Static_Expression (Node (Discr_Val)) then
12058             Is_Static := False;
12059             exit;
12060          end if;
12061
12062          Next_Elmt (Discr_Val);
12063       end loop;
12064
12065       Set_Has_Static_Discriminants (Subt, Is_Static);
12066
12067       Push_Scope (Subt);
12068
12069       --  Inherit the discriminants of the parent type
12070
12071       Add_Discriminants : declare
12072          Num_Disc : Int;
12073          Num_Gird : Int;
12074
12075       begin
12076          Num_Disc := 0;
12077          Old_C := First_Discriminant (Typ);
12078
12079          while Present (Old_C) loop
12080             Num_Disc := Num_Disc + 1;
12081             New_C := Create_Component (Old_C);
12082             Set_Is_Public (New_C, Is_Public (Subt));
12083             Next_Discriminant (Old_C);
12084          end loop;
12085
12086          --  For an untagged derived subtype, the number of discriminants may
12087          --  be smaller than the number of inherited discriminants, because
12088          --  several of them may be renamed by a single new discriminant or
12089          --  constrained. In this case, add the hidden discriminants back into
12090          --  the subtype, because they need to be present if the optimizer of
12091          --  the GCC 4.x back-end decides to break apart assignments between
12092          --  objects using the parent view into member-wise assignments.
12093
12094          Num_Gird := 0;
12095
12096          if Is_Derived_Type (Typ)
12097            and then not Is_Tagged_Type (Typ)
12098          then
12099             Old_C := First_Stored_Discriminant (Typ);
12100
12101             while Present (Old_C) loop
12102                Num_Gird := Num_Gird + 1;
12103                Next_Stored_Discriminant (Old_C);
12104             end loop;
12105          end if;
12106
12107          if Num_Gird > Num_Disc then
12108
12109             --  Find out multiple uses of new discriminants, and add hidden
12110             --  components for the extra renamed discriminants. We recognize
12111             --  multiple uses through the Corresponding_Discriminant of a
12112             --  new discriminant: if it constrains several old discriminants,
12113             --  this field points to the last one in the parent type. The
12114             --  stored discriminants of the derived type have the same name
12115             --  as those of the parent.
12116
12117             declare
12118                Constr    : Elmt_Id;
12119                New_Discr : Entity_Id;
12120                Old_Discr : Entity_Id;
12121
12122             begin
12123                Constr    := First_Elmt (Stored_Constraint (Typ));
12124                Old_Discr := First_Stored_Discriminant (Typ);
12125                while Present (Constr) loop
12126                   if Is_Entity_Name (Node (Constr))
12127                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
12128                   then
12129                      New_Discr := Entity (Node (Constr));
12130
12131                      if Chars (Corresponding_Discriminant (New_Discr)) /=
12132                         Chars (Old_Discr)
12133                      then
12134                         --  The new discriminant has been used to rename a
12135                         --  subsequent old discriminant. Introduce a shadow
12136                         --  component for the current old discriminant.
12137
12138                         New_C := Create_Component (Old_Discr);
12139                         Set_Original_Record_Component (New_C, Old_Discr);
12140                      end if;
12141
12142                   else
12143                      --  The constraint has eliminated the old discriminant.
12144                      --  Introduce a shadow component.
12145
12146                      New_C := Create_Component (Old_Discr);
12147                      Set_Original_Record_Component (New_C, Old_Discr);
12148                   end if;
12149
12150                   Next_Elmt (Constr);
12151                   Next_Stored_Discriminant (Old_Discr);
12152                end loop;
12153             end;
12154          end if;
12155       end Add_Discriminants;
12156
12157       if Is_Static
12158         and then Is_Variant_Record (Typ)
12159       then
12160          Collect_Fixed_Components (Typ);
12161
12162          Gather_Components (
12163            Typ,
12164            Component_List (Type_Definition (Parent (Typ))),
12165            Governed_By   => Assoc_List,
12166            Into          => Comp_List,
12167            Report_Errors => Errors);
12168          pragma Assert (not Errors);
12169
12170          Create_All_Components;
12171
12172       --  If the subtype declaration is created for a tagged type derivation
12173       --  with constraints, we retrieve the record definition of the parent
12174       --  type to select the components of the proper variant.
12175
12176       elsif Is_Static
12177         and then Is_Tagged_Type (Typ)
12178         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
12179         and then
12180           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
12181         and then Is_Variant_Record (Parent_Type)
12182       then
12183          Collect_Fixed_Components (Typ);
12184
12185          Gather_Components (
12186            Typ,
12187            Component_List (Type_Definition (Parent (Parent_Type))),
12188            Governed_By   => Assoc_List,
12189            Into          => Comp_List,
12190            Report_Errors => Errors);
12191          pragma Assert (not Errors);
12192
12193          --  If the tagged derivation has a type extension, collect all the
12194          --  new components therein.
12195
12196          if Present
12197               (Record_Extension_Part (Type_Definition (Parent (Typ))))
12198          then
12199             Old_C := First_Component (Typ);
12200             while Present (Old_C) loop
12201                if Original_Record_Component (Old_C) = Old_C
12202                 and then Chars (Old_C) /= Name_uTag
12203                 and then Chars (Old_C) /= Name_uParent
12204                 and then Chars (Old_C) /= Name_uController
12205                then
12206                   Append_Elmt (Old_C, Comp_List);
12207                end if;
12208
12209                Next_Component (Old_C);
12210             end loop;
12211          end if;
12212
12213          Create_All_Components;
12214
12215       else
12216          --  If discriminants are not static, or if this is a multi-level type
12217          --  extension, we have to include all components of the parent type.
12218
12219          Old_C := First_Component (Typ);
12220          while Present (Old_C) loop
12221             New_C := Create_Component (Old_C);
12222
12223             Set_Etype
12224               (New_C,
12225                Constrain_Component_Type
12226                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12227             Set_Is_Public (New_C, Is_Public (Subt));
12228
12229             Next_Component (Old_C);
12230          end loop;
12231       end if;
12232
12233       End_Scope;
12234    end Create_Constrained_Components;
12235
12236    ------------------------------------------
12237    -- Decimal_Fixed_Point_Type_Declaration --
12238    ------------------------------------------
12239
12240    procedure Decimal_Fixed_Point_Type_Declaration
12241      (T   : Entity_Id;
12242       Def : Node_Id)
12243    is
12244       Loc           : constant Source_Ptr := Sloc (Def);
12245       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
12246       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
12247       Implicit_Base : Entity_Id;
12248       Digs_Val      : Uint;
12249       Delta_Val     : Ureal;
12250       Scale_Val     : Uint;
12251       Bound_Val     : Ureal;
12252
12253    begin
12254       Check_Restriction (No_Fixed_Point, Def);
12255
12256       --  Create implicit base type
12257
12258       Implicit_Base :=
12259         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
12260       Set_Etype (Implicit_Base, Implicit_Base);
12261
12262       --  Analyze and process delta expression
12263
12264       Analyze_And_Resolve (Delta_Expr, Universal_Real);
12265
12266       Check_Delta_Expression (Delta_Expr);
12267       Delta_Val := Expr_Value_R (Delta_Expr);
12268
12269       --  Check delta is power of 10, and determine scale value from it
12270
12271       declare
12272          Val : Ureal;
12273
12274       begin
12275          Scale_Val := Uint_0;
12276          Val := Delta_Val;
12277
12278          if Val < Ureal_1 then
12279             while Val < Ureal_1 loop
12280                Val := Val * Ureal_10;
12281                Scale_Val := Scale_Val + 1;
12282             end loop;
12283
12284             if Scale_Val > 18 then
12285                Error_Msg_N ("scale exceeds maximum value of 18", Def);
12286                Scale_Val := UI_From_Int (+18);
12287             end if;
12288
12289          else
12290             while Val > Ureal_1 loop
12291                Val := Val / Ureal_10;
12292                Scale_Val := Scale_Val - 1;
12293             end loop;
12294
12295             if Scale_Val < -18 then
12296                Error_Msg_N ("scale is less than minimum value of -18", Def);
12297                Scale_Val := UI_From_Int (-18);
12298             end if;
12299          end if;
12300
12301          if Val /= Ureal_1 then
12302             Error_Msg_N ("delta expression must be a power of 10", Def);
12303             Delta_Val := Ureal_10 ** (-Scale_Val);
12304          end if;
12305       end;
12306
12307       --  Set delta, scale and small (small = delta for decimal type)
12308
12309       Set_Delta_Value (Implicit_Base, Delta_Val);
12310       Set_Scale_Value (Implicit_Base, Scale_Val);
12311       Set_Small_Value (Implicit_Base, Delta_Val);
12312
12313       --  Analyze and process digits expression
12314
12315       Analyze_And_Resolve (Digs_Expr, Any_Integer);
12316       Check_Digits_Expression (Digs_Expr);
12317       Digs_Val := Expr_Value (Digs_Expr);
12318
12319       if Digs_Val > 18 then
12320          Digs_Val := UI_From_Int (+18);
12321          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
12322       end if;
12323
12324       Set_Digits_Value (Implicit_Base, Digs_Val);
12325       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
12326
12327       --  Set range of base type from digits value for now. This will be
12328       --  expanded to represent the true underlying base range by Freeze.
12329
12330       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
12331
12332       --  Note: We leave size as zero for now, size will be set at freeze
12333       --  time. We have to do this for ordinary fixed-point, because the size
12334       --  depends on the specified small, and we might as well do the same for
12335       --  decimal fixed-point.
12336
12337       pragma Assert (Esize (Implicit_Base) = Uint_0);
12338
12339       --  If there are bounds given in the declaration use them as the
12340       --  bounds of the first named subtype.
12341
12342       if Present (Real_Range_Specification (Def)) then
12343          declare
12344             RRS      : constant Node_Id := Real_Range_Specification (Def);
12345             Low      : constant Node_Id := Low_Bound (RRS);
12346             High     : constant Node_Id := High_Bound (RRS);
12347             Low_Val  : Ureal;
12348             High_Val : Ureal;
12349
12350          begin
12351             Analyze_And_Resolve (Low, Any_Real);
12352             Analyze_And_Resolve (High, Any_Real);
12353             Check_Real_Bound (Low);
12354             Check_Real_Bound (High);
12355             Low_Val := Expr_Value_R (Low);
12356             High_Val := Expr_Value_R (High);
12357
12358             if Low_Val < (-Bound_Val) then
12359                Error_Msg_N
12360                  ("range low bound too small for digits value", Low);
12361                Low_Val := -Bound_Val;
12362             end if;
12363
12364             if High_Val > Bound_Val then
12365                Error_Msg_N
12366                  ("range high bound too large for digits value", High);
12367                High_Val := Bound_Val;
12368             end if;
12369
12370             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
12371          end;
12372
12373       --  If no explicit range, use range that corresponds to given
12374       --  digits value. This will end up as the final range for the
12375       --  first subtype.
12376
12377       else
12378          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
12379       end if;
12380
12381       --  Complete entity for first subtype
12382
12383       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
12384       Set_Etype          (T, Implicit_Base);
12385       Set_Size_Info      (T, Implicit_Base);
12386       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
12387       Set_Digits_Value   (T, Digs_Val);
12388       Set_Delta_Value    (T, Delta_Val);
12389       Set_Small_Value    (T, Delta_Val);
12390       Set_Scale_Value    (T, Scale_Val);
12391       Set_Is_Constrained (T);
12392    end Decimal_Fixed_Point_Type_Declaration;
12393
12394    -----------------------------------
12395    -- Derive_Progenitor_Subprograms --
12396    -----------------------------------
12397
12398    procedure Derive_Progenitor_Subprograms
12399      (Parent_Type : Entity_Id;
12400       Tagged_Type : Entity_Id)
12401    is
12402       E          : Entity_Id;
12403       Elmt       : Elmt_Id;
12404       Iface      : Entity_Id;
12405       Iface_Elmt : Elmt_Id;
12406       Iface_Subp : Entity_Id;
12407       New_Subp   : Entity_Id := Empty;
12408       Prim_Elmt  : Elmt_Id;
12409       Subp       : Entity_Id;
12410       Typ        : Entity_Id;
12411
12412    begin
12413       pragma Assert (Ada_Version >= Ada_2005
12414         and then Is_Record_Type (Tagged_Type)
12415         and then Is_Tagged_Type (Tagged_Type)
12416         and then Has_Interfaces (Tagged_Type));
12417
12418       --  Step 1: Transfer to the full-view primitives associated with the
12419       --  partial-view that cover interface primitives. Conceptually this
12420       --  work should be done later by Process_Full_View; done here to
12421       --  simplify its implementation at later stages. It can be safely
12422       --  done here because interfaces must be visible in the partial and
12423       --  private view (RM 7.3(7.3/2)).
12424
12425       --  Small optimization: This work is only required if the parent is
12426       --  abstract. If the tagged type is not abstract, it cannot have
12427       --  abstract primitives (the only entities in the list of primitives of
12428       --  non-abstract tagged types that can reference abstract primitives
12429       --  through its Alias attribute are the internal entities that have
12430       --  attribute Interface_Alias, and these entities are generated later
12431       --  by Add_Internal_Interface_Entities).
12432
12433       if In_Private_Part (Current_Scope)
12434         and then Is_Abstract_Type (Parent_Type)
12435       then
12436          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
12437          while Present (Elmt) loop
12438             Subp := Node (Elmt);
12439
12440             --  At this stage it is not possible to have entities in the list
12441             --  of primitives that have attribute Interface_Alias
12442
12443             pragma Assert (No (Interface_Alias (Subp)));
12444
12445             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
12446
12447             if Is_Interface (Typ) then
12448                E := Find_Primitive_Covering_Interface
12449                       (Tagged_Type => Tagged_Type,
12450                        Iface_Prim  => Subp);
12451
12452                if Present (E)
12453                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
12454                then
12455                   Replace_Elmt (Elmt, E);
12456                   Remove_Homonym (Subp);
12457                end if;
12458             end if;
12459
12460             Next_Elmt (Elmt);
12461          end loop;
12462       end if;
12463
12464       --  Step 2: Add primitives of progenitors that are not implemented by
12465       --  parents of Tagged_Type
12466
12467       if Present (Interfaces (Base_Type (Tagged_Type))) then
12468          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
12469          while Present (Iface_Elmt) loop
12470             Iface := Node (Iface_Elmt);
12471
12472             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
12473             while Present (Prim_Elmt) loop
12474                Iface_Subp := Node (Prim_Elmt);
12475
12476                --  Exclude derivation of predefined primitives except those
12477                --  that come from source. Required to catch declarations of
12478                --  equality operators of interfaces. For example:
12479
12480                --     type Iface is interface;
12481                --     function "=" (Left, Right : Iface) return Boolean;
12482
12483                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
12484                  or else Comes_From_Source (Iface_Subp)
12485                then
12486                   E := Find_Primitive_Covering_Interface
12487                          (Tagged_Type => Tagged_Type,
12488                           Iface_Prim  => Iface_Subp);
12489
12490                   --  If not found we derive a new primitive leaving its alias
12491                   --  attribute referencing the interface primitive
12492
12493                   if No (E) then
12494                      Derive_Subprogram
12495                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12496
12497                   --  Ada 2012 (AI05-0197): If the covering primitive's name
12498                   --  differs from the name of the interface primitive then it
12499                   --  is a private primitive inherited from a parent type. In
12500                   --  such case, given that Tagged_Type covers the interface,
12501                   --  the inherited private primitive becomes visible. For such
12502                   --  purpose we add a new entity that renames the inherited
12503                   --  private primitive.
12504
12505                   elsif Chars (E) /= Chars (Iface_Subp) then
12506                      pragma Assert (Has_Suffix (E, 'P'));
12507                      Derive_Subprogram
12508                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12509                      Set_Alias (New_Subp, E);
12510                      Set_Is_Abstract_Subprogram (New_Subp,
12511                        Is_Abstract_Subprogram (E));
12512
12513                   --  Propagate to the full view interface entities associated
12514                   --  with the partial view
12515
12516                   elsif In_Private_Part (Current_Scope)
12517                     and then Present (Alias (E))
12518                     and then Alias (E) = Iface_Subp
12519                     and then
12520                       List_Containing (Parent (E)) /=
12521                         Private_Declarations
12522                           (Specification
12523                             (Unit_Declaration_Node (Current_Scope)))
12524                   then
12525                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
12526                   end if;
12527                end if;
12528
12529                Next_Elmt (Prim_Elmt);
12530             end loop;
12531
12532             Next_Elmt (Iface_Elmt);
12533          end loop;
12534       end if;
12535    end Derive_Progenitor_Subprograms;
12536
12537    -----------------------
12538    -- Derive_Subprogram --
12539    -----------------------
12540
12541    procedure Derive_Subprogram
12542      (New_Subp     : in out Entity_Id;
12543       Parent_Subp  : Entity_Id;
12544       Derived_Type : Entity_Id;
12545       Parent_Type  : Entity_Id;
12546       Actual_Subp  : Entity_Id := Empty)
12547    is
12548       Formal : Entity_Id;
12549       --  Formal parameter of parent primitive operation
12550
12551       Formal_Of_Actual : Entity_Id;
12552       --  Formal parameter of actual operation, when the derivation is to
12553       --  create a renaming for a primitive operation of an actual in an
12554       --  instantiation.
12555
12556       New_Formal : Entity_Id;
12557       --  Formal of inherited operation
12558
12559       Visible_Subp : Entity_Id := Parent_Subp;
12560
12561       function Is_Private_Overriding return Boolean;
12562       --  If Subp is a private overriding of a visible operation, the inherited
12563       --  operation derives from the overridden op (even though its body is the
12564       --  overriding one) and the inherited operation is visible now. See
12565       --  sem_disp to see the full details of the handling of the overridden
12566       --  subprogram, which is removed from the list of primitive operations of
12567       --  the type. The overridden subprogram is saved locally in Visible_Subp,
12568       --  and used to diagnose abstract operations that need overriding in the
12569       --  derived type.
12570
12571       procedure Replace_Type (Id, New_Id : Entity_Id);
12572       --  When the type is an anonymous access type, create a new access type
12573       --  designating the derived type.
12574
12575       procedure Set_Derived_Name;
12576       --  This procedure sets the appropriate Chars name for New_Subp. This
12577       --  is normally just a copy of the parent name. An exception arises for
12578       --  type support subprograms, where the name is changed to reflect the
12579       --  name of the derived type, e.g. if type foo is derived from type bar,
12580       --  then a procedure barDA is derived with a name fooDA.
12581
12582       ---------------------------
12583       -- Is_Private_Overriding --
12584       ---------------------------
12585
12586       function Is_Private_Overriding return Boolean is
12587          Prev : Entity_Id;
12588
12589       begin
12590          --  If the parent is not a dispatching operation there is no
12591          --  need to investigate overridings
12592
12593          if not Is_Dispatching_Operation (Parent_Subp) then
12594             return False;
12595          end if;
12596
12597          --  The visible operation that is overridden is a homonym of the
12598          --  parent subprogram. We scan the homonym chain to find the one
12599          --  whose alias is the subprogram we are deriving.
12600
12601          Prev := Current_Entity (Parent_Subp);
12602          while Present (Prev) loop
12603             if Ekind (Prev) = Ekind (Parent_Subp)
12604               and then Alias (Prev) = Parent_Subp
12605               and then Scope (Parent_Subp) = Scope (Prev)
12606               and then not Is_Hidden (Prev)
12607             then
12608                Visible_Subp := Prev;
12609                return True;
12610             end if;
12611
12612             Prev := Homonym (Prev);
12613          end loop;
12614
12615          return False;
12616       end Is_Private_Overriding;
12617
12618       ------------------
12619       -- Replace_Type --
12620       ------------------
12621
12622       procedure Replace_Type (Id, New_Id : Entity_Id) is
12623          Acc_Type : Entity_Id;
12624          Par      : constant Node_Id := Parent (Derived_Type);
12625
12626       begin
12627          --  When the type is an anonymous access type, create a new access
12628          --  type designating the derived type. This itype must be elaborated
12629          --  at the point of the derivation, not on subsequent calls that may
12630          --  be out of the proper scope for Gigi, so we insert a reference to
12631          --  it after the derivation.
12632
12633          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
12634             declare
12635                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
12636
12637             begin
12638                if Ekind (Desig_Typ) = E_Record_Type_With_Private
12639                  and then Present (Full_View (Desig_Typ))
12640                  and then not Is_Private_Type (Parent_Type)
12641                then
12642                   Desig_Typ := Full_View (Desig_Typ);
12643                end if;
12644
12645                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
12646
12647                   --  Ada 2005 (AI-251): Handle also derivations of abstract
12648                   --  interface primitives.
12649
12650                  or else (Is_Interface (Desig_Typ)
12651                           and then not Is_Class_Wide_Type (Desig_Typ))
12652                then
12653                   Acc_Type := New_Copy (Etype (Id));
12654                   Set_Etype (Acc_Type, Acc_Type);
12655                   Set_Scope (Acc_Type, New_Subp);
12656
12657                   --  Compute size of anonymous access type
12658
12659                   if Is_Array_Type (Desig_Typ)
12660                     and then not Is_Constrained (Desig_Typ)
12661                   then
12662                      Init_Size (Acc_Type, 2 * System_Address_Size);
12663                   else
12664                      Init_Size (Acc_Type, System_Address_Size);
12665                   end if;
12666
12667                   Init_Alignment (Acc_Type);
12668                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
12669
12670                   Set_Etype (New_Id, Acc_Type);
12671                   Set_Scope (New_Id, New_Subp);
12672
12673                   --  Create a reference to it
12674                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
12675
12676                else
12677                   Set_Etype (New_Id, Etype (Id));
12678                end if;
12679             end;
12680
12681          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
12682            or else
12683              (Ekind (Etype (Id)) = E_Record_Type_With_Private
12684                and then Present (Full_View (Etype (Id)))
12685                and then
12686                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
12687          then
12688             --  Constraint checks on formals are generated during expansion,
12689             --  based on the signature of the original subprogram. The bounds
12690             --  of the derived type are not relevant, and thus we can use
12691             --  the base type for the formals. However, the return type may be
12692             --  used in a context that requires that the proper static bounds
12693             --  be used (a case statement, for example)  and for those cases
12694             --  we must use the derived type (first subtype), not its base.
12695
12696             --  If the derived_type_definition has no constraints, we know that
12697             --  the derived type has the same constraints as the first subtype
12698             --  of the parent, and we can also use it rather than its base,
12699             --  which can lead to more efficient code.
12700
12701             if Etype (Id) = Parent_Type then
12702                if Is_Scalar_Type (Parent_Type)
12703                  and then
12704                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
12705                then
12706                   Set_Etype (New_Id, Derived_Type);
12707
12708                elsif Nkind (Par) = N_Full_Type_Declaration
12709                  and then
12710                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
12711                  and then
12712                    Is_Entity_Name
12713                      (Subtype_Indication (Type_Definition (Par)))
12714                then
12715                   Set_Etype (New_Id, Derived_Type);
12716
12717                else
12718                   Set_Etype (New_Id, Base_Type (Derived_Type));
12719                end if;
12720
12721             else
12722                Set_Etype (New_Id, Base_Type (Derived_Type));
12723             end if;
12724
12725          else
12726             Set_Etype (New_Id, Etype (Id));
12727          end if;
12728       end Replace_Type;
12729
12730       ----------------------
12731       -- Set_Derived_Name --
12732       ----------------------
12733
12734       procedure Set_Derived_Name is
12735          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
12736       begin
12737          if Nm = TSS_Null then
12738             Set_Chars (New_Subp, Chars (Parent_Subp));
12739          else
12740             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
12741          end if;
12742       end Set_Derived_Name;
12743
12744    --  Start of processing for Derive_Subprogram
12745
12746    begin
12747       New_Subp :=
12748          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
12749       Set_Ekind (New_Subp, Ekind (Parent_Subp));
12750
12751       --  Check whether the inherited subprogram is a private operation that
12752       --  should be inherited but not yet made visible. Such subprograms can
12753       --  become visible at a later point (e.g., the private part of a public
12754       --  child unit) via Declare_Inherited_Private_Subprograms. If the
12755       --  following predicate is true, then this is not such a private
12756       --  operation and the subprogram simply inherits the name of the parent
12757       --  subprogram. Note the special check for the names of controlled
12758       --  operations, which are currently exempted from being inherited with
12759       --  a hidden name because they must be findable for generation of
12760       --  implicit run-time calls.
12761
12762       if not Is_Hidden (Parent_Subp)
12763         or else Is_Internal (Parent_Subp)
12764         or else Is_Private_Overriding
12765         or else Is_Internal_Name (Chars (Parent_Subp))
12766         or else Chars (Parent_Subp) = Name_Initialize
12767         or else Chars (Parent_Subp) = Name_Adjust
12768         or else Chars (Parent_Subp) = Name_Finalize
12769       then
12770          Set_Derived_Name;
12771
12772       --  An inherited dispatching equality will be overridden by an internally
12773       --  generated one, or by an explicit one, so preserve its name and thus
12774       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
12775       --  private operation it may become invisible if the full view has
12776       --  progenitors, and the dispatch table will be malformed.
12777       --  We check that the type is limited to handle the anomalous declaration
12778       --  of Limited_Controlled, which is derived from a non-limited type, and
12779       --  which is handled specially elsewhere as well.
12780
12781       elsif Chars (Parent_Subp) = Name_Op_Eq
12782         and then Is_Dispatching_Operation (Parent_Subp)
12783         and then Etype (Parent_Subp) = Standard_Boolean
12784         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
12785         and then
12786           Etype (First_Formal (Parent_Subp)) =
12787             Etype (Next_Formal (First_Formal (Parent_Subp)))
12788       then
12789          Set_Derived_Name;
12790
12791       --  If parent is hidden, this can be a regular derivation if the
12792       --  parent is immediately visible in a non-instantiating context,
12793       --  or if we are in the private part of an instance. This test
12794       --  should still be refined ???
12795
12796       --  The test for In_Instance_Not_Visible avoids inheriting the derived
12797       --  operation as a non-visible operation in cases where the parent
12798       --  subprogram might not be visible now, but was visible within the
12799       --  original generic, so it would be wrong to make the inherited
12800       --  subprogram non-visible now. (Not clear if this test is fully
12801       --  correct; are there any cases where we should declare the inherited
12802       --  operation as not visible to avoid it being overridden, e.g., when
12803       --  the parent type is a generic actual with private primitives ???)
12804
12805       --  (they should be treated the same as other private inherited
12806       --  subprograms, but it's not clear how to do this cleanly). ???
12807
12808       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
12809               and then Is_Immediately_Visible (Parent_Subp)
12810               and then not In_Instance)
12811         or else In_Instance_Not_Visible
12812       then
12813          Set_Derived_Name;
12814
12815       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
12816       --  overrides an interface primitive because interface primitives
12817       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
12818
12819       elsif Ada_Version >= Ada_2005
12820          and then Is_Dispatching_Operation (Parent_Subp)
12821          and then Covers_Some_Interface (Parent_Subp)
12822       then
12823          Set_Derived_Name;
12824
12825       --  Otherwise, the type is inheriting a private operation, so enter
12826       --  it with a special name so it can't be overridden.
12827
12828       else
12829          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
12830       end if;
12831
12832       Set_Parent (New_Subp, Parent (Derived_Type));
12833
12834       if Present (Actual_Subp) then
12835          Replace_Type (Actual_Subp, New_Subp);
12836       else
12837          Replace_Type (Parent_Subp, New_Subp);
12838       end if;
12839
12840       Conditional_Delay (New_Subp, Parent_Subp);
12841
12842       --  If we are creating a renaming for a primitive operation of an
12843       --  actual of a generic derived type, we must examine the signature
12844       --  of the actual primitive, not that of the generic formal, which for
12845       --  example may be an interface. However the name and initial value
12846       --  of the inherited operation are those of the formal primitive.
12847
12848       Formal := First_Formal (Parent_Subp);
12849
12850       if Present (Actual_Subp) then
12851          Formal_Of_Actual := First_Formal (Actual_Subp);
12852       else
12853          Formal_Of_Actual := Empty;
12854       end if;
12855
12856       while Present (Formal) loop
12857          New_Formal := New_Copy (Formal);
12858
12859          --  Normally we do not go copying parents, but in the case of
12860          --  formals, we need to link up to the declaration (which is the
12861          --  parameter specification), and it is fine to link up to the
12862          --  original formal's parameter specification in this case.
12863
12864          Set_Parent (New_Formal, Parent (Formal));
12865          Append_Entity (New_Formal, New_Subp);
12866
12867          if Present (Formal_Of_Actual) then
12868             Replace_Type (Formal_Of_Actual, New_Formal);
12869             Next_Formal (Formal_Of_Actual);
12870          else
12871             Replace_Type (Formal, New_Formal);
12872          end if;
12873
12874          Next_Formal (Formal);
12875       end loop;
12876
12877       --  If this derivation corresponds to a tagged generic actual, then
12878       --  primitive operations rename those of the actual. Otherwise the
12879       --  primitive operations rename those of the parent type, If the parent
12880       --  renames an intrinsic operator, so does the new subprogram. We except
12881       --  concatenation, which is always properly typed, and does not get
12882       --  expanded as other intrinsic operations.
12883
12884       if No (Actual_Subp) then
12885          if Is_Intrinsic_Subprogram (Parent_Subp) then
12886             Set_Is_Intrinsic_Subprogram (New_Subp);
12887
12888             if Present (Alias (Parent_Subp))
12889               and then Chars (Parent_Subp) /= Name_Op_Concat
12890             then
12891                Set_Alias (New_Subp, Alias (Parent_Subp));
12892             else
12893                Set_Alias (New_Subp, Parent_Subp);
12894             end if;
12895
12896          else
12897             Set_Alias (New_Subp, Parent_Subp);
12898          end if;
12899
12900       else
12901          Set_Alias (New_Subp, Actual_Subp);
12902       end if;
12903
12904       --  Derived subprograms of a tagged type must inherit the convention
12905       --  of the parent subprogram (a requirement of AI-117). Derived
12906       --  subprograms of untagged types simply get convention Ada by default.
12907
12908       if Is_Tagged_Type (Derived_Type) then
12909          Set_Convention (New_Subp, Convention (Parent_Subp));
12910       end if;
12911
12912       --  Predefined controlled operations retain their name even if the parent
12913       --  is hidden (see above), but they are not primitive operations if the
12914       --  ancestor is not visible, for example if the parent is a private
12915       --  extension completed with a controlled extension. Note that a full
12916       --  type that is controlled can break privacy: the flag Is_Controlled is
12917       --  set on both views of the type.
12918
12919       if Is_Controlled (Parent_Type)
12920         and then
12921           (Chars (Parent_Subp) = Name_Initialize
12922             or else Chars (Parent_Subp) = Name_Adjust
12923             or else Chars (Parent_Subp) = Name_Finalize)
12924         and then Is_Hidden (Parent_Subp)
12925         and then not Is_Visibly_Controlled (Parent_Type)
12926       then
12927          Set_Is_Hidden (New_Subp);
12928       end if;
12929
12930       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
12931       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
12932
12933       if Ekind (Parent_Subp) = E_Procedure then
12934          Set_Is_Valued_Procedure
12935            (New_Subp, Is_Valued_Procedure (Parent_Subp));
12936       else
12937          Set_Has_Controlling_Result
12938            (New_Subp, Has_Controlling_Result (Parent_Subp));
12939       end if;
12940
12941       --  No_Return must be inherited properly. If this is overridden in the
12942       --  case of a dispatching operation, then a check is made in Sem_Disp
12943       --  that the overriding operation is also No_Return (no such check is
12944       --  required for the case of non-dispatching operation.
12945
12946       Set_No_Return (New_Subp, No_Return (Parent_Subp));
12947
12948       --  A derived function with a controlling result is abstract. If the
12949       --  Derived_Type is a nonabstract formal generic derived type, then
12950       --  inherited operations are not abstract: the required check is done at
12951       --  instantiation time. If the derivation is for a generic actual, the
12952       --  function is not abstract unless the actual is.
12953
12954       if Is_Generic_Type (Derived_Type)
12955         and then not Is_Abstract_Type (Derived_Type)
12956       then
12957          null;
12958
12959       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
12960       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
12961
12962       elsif Ada_Version >= Ada_2005
12963         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12964                    or else (Is_Tagged_Type (Derived_Type)
12965                             and then Etype (New_Subp) = Derived_Type
12966                             and then not Is_Null_Extension (Derived_Type))
12967                    or else (Is_Tagged_Type (Derived_Type)
12968                             and then Ekind (Etype (New_Subp)) =
12969                                                        E_Anonymous_Access_Type
12970                             and then Designated_Type (Etype (New_Subp)) =
12971                                                        Derived_Type
12972                             and then not Is_Null_Extension (Derived_Type)))
12973         and then No (Actual_Subp)
12974       then
12975          if not Is_Tagged_Type (Derived_Type)
12976            or else Is_Abstract_Type (Derived_Type)
12977            or else Is_Abstract_Subprogram (Alias (New_Subp))
12978          then
12979             Set_Is_Abstract_Subprogram (New_Subp);
12980          else
12981             Set_Requires_Overriding (New_Subp);
12982          end if;
12983
12984       elsif Ada_Version < Ada_2005
12985         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12986                    or else (Is_Tagged_Type (Derived_Type)
12987                              and then Etype (New_Subp) = Derived_Type
12988                              and then No (Actual_Subp)))
12989       then
12990          Set_Is_Abstract_Subprogram (New_Subp);
12991
12992       --  AI05-0097 : an inherited operation that dispatches on result is
12993       --  abstract if the derived type is abstract, even if the parent type
12994       --  is concrete and the derived type is a null extension.
12995
12996       elsif Has_Controlling_Result (Alias (New_Subp))
12997         and then Is_Abstract_Type (Etype (New_Subp))
12998       then
12999          Set_Is_Abstract_Subprogram (New_Subp);
13000
13001       --  Finally, if the parent type is abstract we must verify that all
13002       --  inherited operations are either non-abstract or overridden, or that
13003       --  the derived type itself is abstract (this check is performed at the
13004       --  end of a package declaration, in Check_Abstract_Overriding). A
13005       --  private overriding in the parent type will not be visible in the
13006       --  derivation if we are not in an inner package or in a child unit of
13007       --  the parent type, in which case the abstractness of the inherited
13008       --  operation is carried to the new subprogram.
13009
13010       elsif Is_Abstract_Type (Parent_Type)
13011         and then not In_Open_Scopes (Scope (Parent_Type))
13012         and then Is_Private_Overriding
13013         and then Is_Abstract_Subprogram (Visible_Subp)
13014       then
13015          if No (Actual_Subp) then
13016             Set_Alias (New_Subp, Visible_Subp);
13017             Set_Is_Abstract_Subprogram (New_Subp, True);
13018
13019          else
13020             --  If this is a derivation for an instance of a formal derived
13021             --  type, abstractness comes from the primitive operation of the
13022             --  actual, not from the operation inherited from the ancestor.
13023
13024             Set_Is_Abstract_Subprogram
13025               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
13026          end if;
13027       end if;
13028
13029       New_Overloaded_Entity (New_Subp, Derived_Type);
13030
13031       --  Check for case of a derived subprogram for the instantiation of a
13032       --  formal derived tagged type, if so mark the subprogram as dispatching
13033       --  and inherit the dispatching attributes of the parent subprogram. The
13034       --  derived subprogram is effectively renaming of the actual subprogram,
13035       --  so it needs to have the same attributes as the actual.
13036
13037       if Present (Actual_Subp)
13038         and then Is_Dispatching_Operation (Parent_Subp)
13039       then
13040          Set_Is_Dispatching_Operation (New_Subp);
13041
13042          if Present (DTC_Entity (Parent_Subp)) then
13043             Set_DTC_Entity (New_Subp, DTC_Entity (Parent_Subp));
13044             Set_DT_Position (New_Subp, DT_Position (Parent_Subp));
13045          end if;
13046       end if;
13047
13048       --  Indicate that a derived subprogram does not require a body and that
13049       --  it does not require processing of default expressions.
13050
13051       Set_Has_Completion (New_Subp);
13052       Set_Default_Expressions_Processed (New_Subp);
13053
13054       if Ekind (New_Subp) = E_Function then
13055          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
13056       end if;
13057    end Derive_Subprogram;
13058
13059    ------------------------
13060    -- Derive_Subprograms --
13061    ------------------------
13062
13063    procedure Derive_Subprograms
13064      (Parent_Type    : Entity_Id;
13065       Derived_Type   : Entity_Id;
13066       Generic_Actual : Entity_Id := Empty)
13067    is
13068       Op_List : constant Elist_Id :=
13069                   Collect_Primitive_Operations (Parent_Type);
13070
13071       function Check_Derived_Type return Boolean;
13072       --  Check that all the entities derived from Parent_Type are found in
13073       --  the list of primitives of Derived_Type exactly in the same order.
13074
13075       procedure Derive_Interface_Subprogram
13076         (New_Subp    : in out Entity_Id;
13077          Subp        : Entity_Id;
13078          Actual_Subp : Entity_Id);
13079       --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
13080       --  (which is an interface primitive). If Generic_Actual is present then
13081       --  Actual_Subp is the actual subprogram corresponding with the generic
13082       --  subprogram Subp.
13083
13084       function Check_Derived_Type return Boolean is
13085          E        : Entity_Id;
13086          Elmt     : Elmt_Id;
13087          List     : Elist_Id;
13088          New_Subp : Entity_Id;
13089          Op_Elmt  : Elmt_Id;
13090          Subp     : Entity_Id;
13091
13092       begin
13093          --  Traverse list of entities in the current scope searching for
13094          --  an incomplete type whose full-view is derived type
13095
13096          E := First_Entity (Scope (Derived_Type));
13097          while Present (E)
13098            and then E /= Derived_Type
13099          loop
13100             if Ekind (E) = E_Incomplete_Type
13101               and then Present (Full_View (E))
13102               and then Full_View (E) = Derived_Type
13103             then
13104                --  Disable this test if Derived_Type completes an incomplete
13105                --  type because in such case more primitives can be added
13106                --  later to the list of primitives of Derived_Type by routine
13107                --  Process_Incomplete_Dependents
13108
13109                return True;
13110             end if;
13111
13112             E := Next_Entity (E);
13113          end loop;
13114
13115          List := Collect_Primitive_Operations (Derived_Type);
13116          Elmt := First_Elmt (List);
13117
13118          Op_Elmt := First_Elmt (Op_List);
13119          while Present (Op_Elmt) loop
13120             Subp     := Node (Op_Elmt);
13121             New_Subp := Node (Elmt);
13122
13123             --  At this early stage Derived_Type has no entities with attribute
13124             --  Interface_Alias. In addition, such primitives are always
13125             --  located at the end of the list of primitives of Parent_Type.
13126             --  Therefore, if found we can safely stop processing pending
13127             --  entities.
13128
13129             exit when Present (Interface_Alias (Subp));
13130
13131             --  Handle hidden entities
13132
13133             if not Is_Predefined_Dispatching_Operation (Subp)
13134               and then Is_Hidden (Subp)
13135             then
13136                if Present (New_Subp)
13137                  and then Primitive_Names_Match (Subp, New_Subp)
13138                then
13139                   Next_Elmt (Elmt);
13140                end if;
13141
13142             else
13143                if not Present (New_Subp)
13144                  or else Ekind (Subp) /= Ekind (New_Subp)
13145                  or else not Primitive_Names_Match (Subp, New_Subp)
13146                then
13147                   return False;
13148                end if;
13149
13150                Next_Elmt (Elmt);
13151             end if;
13152
13153             Next_Elmt (Op_Elmt);
13154          end loop;
13155
13156          return True;
13157       end Check_Derived_Type;
13158
13159       ---------------------------------
13160       -- Derive_Interface_Subprogram --
13161       ---------------------------------
13162
13163       procedure Derive_Interface_Subprogram
13164         (New_Subp    : in out Entity_Id;
13165          Subp        : Entity_Id;
13166          Actual_Subp : Entity_Id)
13167       is
13168          Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
13169          Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
13170
13171       begin
13172          pragma Assert (Is_Interface (Iface_Type));
13173
13174          Derive_Subprogram
13175            (New_Subp     => New_Subp,
13176             Parent_Subp  => Iface_Subp,
13177             Derived_Type => Derived_Type,
13178             Parent_Type  => Iface_Type,
13179             Actual_Subp  => Actual_Subp);
13180
13181          --  Given that this new interface entity corresponds with a primitive
13182          --  of the parent that was not overridden we must leave it associated
13183          --  with its parent primitive to ensure that it will share the same
13184          --  dispatch table slot when overridden.
13185
13186          if No (Actual_Subp) then
13187             Set_Alias (New_Subp, Subp);
13188
13189          --  For instantiations this is not needed since the previous call to
13190          --  Derive_Subprogram leaves the entity well decorated.
13191
13192          else
13193             pragma Assert (Alias (New_Subp) = Actual_Subp);
13194             null;
13195          end if;
13196       end Derive_Interface_Subprogram;
13197
13198       --  Local variables
13199
13200       Alias_Subp   : Entity_Id;
13201       Act_List     : Elist_Id;
13202       Act_Elmt     : Elmt_Id   := No_Elmt;
13203       Act_Subp     : Entity_Id := Empty;
13204       Elmt         : Elmt_Id;
13205       Need_Search  : Boolean   := False;
13206       New_Subp     : Entity_Id := Empty;
13207       Parent_Base  : Entity_Id;
13208       Subp         : Entity_Id;
13209
13210    --  Start of processing for Derive_Subprograms
13211
13212    begin
13213       if Ekind (Parent_Type) = E_Record_Type_With_Private
13214         and then Has_Discriminants (Parent_Type)
13215         and then Present (Full_View (Parent_Type))
13216       then
13217          Parent_Base := Full_View (Parent_Type);
13218       else
13219          Parent_Base := Parent_Type;
13220       end if;
13221
13222       if Present (Generic_Actual) then
13223          Act_List := Collect_Primitive_Operations (Generic_Actual);
13224          Act_Elmt := First_Elmt (Act_List);
13225       end if;
13226
13227       --  Derive primitives inherited from the parent. Note that if the generic
13228       --  actual is present, this is not really a type derivation, it is a
13229       --  completion within an instance.
13230
13231       --  Case 1: Derived_Type does not implement interfaces
13232
13233       if not Is_Tagged_Type (Derived_Type)
13234         or else (not Has_Interfaces (Derived_Type)
13235                   and then not (Present (Generic_Actual)
13236                                   and then
13237                                 Has_Interfaces (Generic_Actual)))
13238       then
13239          Elmt := First_Elmt (Op_List);
13240          while Present (Elmt) loop
13241             Subp := Node (Elmt);
13242
13243             --  Literals are derived earlier in the process of building the
13244             --  derived type, and are skipped here.
13245
13246             if Ekind (Subp) = E_Enumeration_Literal then
13247                null;
13248
13249             --  The actual is a direct descendant and the common primitive
13250             --  operations appear in the same order.
13251
13252             --  If the generic parent type is present, the derived type is an
13253             --  instance of a formal derived type, and within the instance its
13254             --  operations are those of the actual. We derive from the formal
13255             --  type but make the inherited operations aliases of the
13256             --  corresponding operations of the actual.
13257
13258             else
13259                pragma Assert (No (Node (Act_Elmt))
13260                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
13261                             and then
13262                           Type_Conformant (Subp, Node (Act_Elmt),
13263                                            Skip_Controlling_Formals => True)));
13264
13265                Derive_Subprogram
13266                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
13267
13268                if Present (Act_Elmt) then
13269                   Next_Elmt (Act_Elmt);
13270                end if;
13271             end if;
13272
13273             Next_Elmt (Elmt);
13274          end loop;
13275
13276       --  Case 2: Derived_Type implements interfaces
13277
13278       else
13279          --  If the parent type has no predefined primitives we remove
13280          --  predefined primitives from the list of primitives of generic
13281          --  actual to simplify the complexity of this algorithm.
13282
13283          if Present (Generic_Actual) then
13284             declare
13285                Has_Predefined_Primitives : Boolean := False;
13286
13287             begin
13288                --  Check if the parent type has predefined primitives
13289
13290                Elmt := First_Elmt (Op_List);
13291                while Present (Elmt) loop
13292                   Subp := Node (Elmt);
13293
13294                   if Is_Predefined_Dispatching_Operation (Subp)
13295                     and then not Comes_From_Source (Ultimate_Alias (Subp))
13296                   then
13297                      Has_Predefined_Primitives := True;
13298                      exit;
13299                   end if;
13300
13301                   Next_Elmt (Elmt);
13302                end loop;
13303
13304                --  Remove predefined primitives of Generic_Actual. We must use
13305                --  an auxiliary list because in case of tagged types the value
13306                --  returned by Collect_Primitive_Operations is the value stored
13307                --  in its Primitive_Operations attribute (and we don't want to
13308                --  modify its current contents).
13309
13310                if not Has_Predefined_Primitives then
13311                   declare
13312                      Aux_List : constant Elist_Id := New_Elmt_List;
13313
13314                   begin
13315                      Elmt := First_Elmt (Act_List);
13316                      while Present (Elmt) loop
13317                         Subp := Node (Elmt);
13318
13319                         if not Is_Predefined_Dispatching_Operation (Subp)
13320                           or else Comes_From_Source (Subp)
13321                         then
13322                            Append_Elmt (Subp, Aux_List);
13323                         end if;
13324
13325                         Next_Elmt (Elmt);
13326                      end loop;
13327
13328                      Act_List := Aux_List;
13329                   end;
13330                end if;
13331
13332                Act_Elmt := First_Elmt (Act_List);
13333                Act_Subp := Node (Act_Elmt);
13334             end;
13335          end if;
13336
13337          --  Stage 1: If the generic actual is not present we derive the
13338          --  primitives inherited from the parent type. If the generic parent
13339          --  type is present, the derived type is an instance of a formal
13340          --  derived type, and within the instance its operations are those of
13341          --  the actual. We derive from the formal type but make the inherited
13342          --  operations aliases of the corresponding operations of the actual.
13343
13344          Elmt := First_Elmt (Op_List);
13345          while Present (Elmt) loop
13346             Subp       := Node (Elmt);
13347             Alias_Subp := Ultimate_Alias (Subp);
13348
13349             --  Do not derive internal entities of the parent that link
13350             --  interface primitives with their covering primitive. These
13351             --  entities will be added to this type when frozen.
13352
13353             if Present (Interface_Alias (Subp)) then
13354                goto Continue;
13355             end if;
13356
13357             --  If the generic actual is present find the corresponding
13358             --  operation in the generic actual. If the parent type is a
13359             --  direct ancestor of the derived type then, even if it is an
13360             --  interface, the operations are inherited from the primary
13361             --  dispatch table and are in the proper order. If we detect here
13362             --  that primitives are not in the same order we traverse the list
13363             --  of primitive operations of the actual to find the one that
13364             --  implements the interface primitive.
13365
13366             if Need_Search
13367               or else
13368                 (Present (Generic_Actual)
13369                   and then Present (Act_Subp)
13370                   and then not
13371                     (Primitive_Names_Match (Subp, Act_Subp)
13372                        and then
13373                      Type_Conformant (Subp, Act_Subp,
13374                                       Skip_Controlling_Formals => True)))
13375             then
13376                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual));
13377
13378                --  Remember that we need searching for all pending primitives
13379
13380                Need_Search := True;
13381
13382                --  Handle entities associated with interface primitives
13383
13384                if Present (Alias_Subp)
13385                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13386                  and then not Is_Predefined_Dispatching_Operation (Subp)
13387                then
13388                   --  Search for the primitive in the homonym chain
13389
13390                   Act_Subp :=
13391                     Find_Primitive_Covering_Interface
13392                       (Tagged_Type => Generic_Actual,
13393                        Iface_Prim  => Alias_Subp);
13394
13395                   --  Previous search may not locate primitives covering
13396                   --  interfaces defined in generics units or instantiations.
13397                   --  (it fails if the covering primitive has formals whose
13398                   --  type is also defined in generics or instantiations).
13399                   --  In such case we search in the list of primitives of the
13400                   --  generic actual for the internal entity that links the
13401                   --  interface primitive and the covering primitive.
13402
13403                   if No (Act_Subp)
13404                     and then Is_Generic_Type (Parent_Type)
13405                   then
13406                      --  This code has been designed to handle only generic
13407                      --  formals that implement interfaces that are defined
13408                      --  in a generic unit or instantiation. If this code is
13409                      --  needed for other cases we must review it because
13410                      --  (given that it relies on Original_Location to locate
13411                      --  the primitive of Generic_Actual that covers the
13412                      --  interface) it could leave linked through attribute
13413                      --  Alias entities of unrelated instantiations).
13414
13415                      pragma Assert
13416                        (Is_Generic_Unit
13417                           (Scope (Find_Dispatching_Type (Alias_Subp)))
13418                        or else
13419                         Instantiation_Depth
13420                           (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
13421
13422                      declare
13423                         Iface_Prim_Loc : constant Source_Ptr :=
13424                                          Original_Location (Sloc (Alias_Subp));
13425                         Elmt      : Elmt_Id;
13426                         Prim      : Entity_Id;
13427                      begin
13428                         Elmt :=
13429                           First_Elmt (Primitive_Operations (Generic_Actual));
13430
13431                         Search : while Present (Elmt) loop
13432                            Prim := Node (Elmt);
13433
13434                            if Present (Interface_Alias (Prim))
13435                              and then Original_Location
13436                                         (Sloc (Interface_Alias (Prim)))
13437                                        = Iface_Prim_Loc
13438                            then
13439                               Act_Subp := Alias (Prim);
13440                               exit Search;
13441                            end if;
13442
13443                            Next_Elmt (Elmt);
13444                         end loop Search;
13445                      end;
13446                   end if;
13447
13448                   pragma Assert (Present (Act_Subp)
13449                     or else Is_Abstract_Type (Generic_Actual)
13450                     or else Serious_Errors_Detected > 0);
13451
13452                --  Handle predefined primitives plus the rest of user-defined
13453                --  primitives
13454
13455                else
13456                   Act_Elmt := First_Elmt (Act_List);
13457                   while Present (Act_Elmt) loop
13458                      Act_Subp := Node (Act_Elmt);
13459
13460                      exit when Primitive_Names_Match (Subp, Act_Subp)
13461                        and then Type_Conformant
13462                                   (Subp, Act_Subp,
13463                                    Skip_Controlling_Formals => True)
13464                        and then No (Interface_Alias (Act_Subp));
13465
13466                      Next_Elmt (Act_Elmt);
13467                   end loop;
13468
13469                   if No (Act_Elmt) then
13470                      Act_Subp := Empty;
13471                   end if;
13472                end if;
13473             end if;
13474
13475             --   Case 1: If the parent is a limited interface then it has the
13476             --   predefined primitives of synchronized interfaces. However, the
13477             --   actual type may be a non-limited type and hence it does not
13478             --   have such primitives.
13479
13480             if Present (Generic_Actual)
13481               and then not Present (Act_Subp)
13482               and then Is_Limited_Interface (Parent_Base)
13483               and then Is_Predefined_Interface_Primitive (Subp)
13484             then
13485                null;
13486
13487             --  Case 2: Inherit entities associated with interfaces that were
13488             --  not covered by the parent type. We exclude here null interface
13489             --  primitives because they do not need special management.
13490
13491             --  We also exclude interface operations that are renamings. If the
13492             --  subprogram is an explicit renaming of an interface primitive,
13493             --  it is a regular primitive operation, and the presence of its
13494             --  alias is not relevant: it has to be derived like any other
13495             --  primitive.
13496
13497             elsif Present (Alias (Subp))
13498               and then Nkind (Unit_Declaration_Node (Subp)) /=
13499                                             N_Subprogram_Renaming_Declaration
13500               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13501               and then not
13502                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
13503                   and then Null_Present (Parent (Alias_Subp)))
13504             then
13505                --  If this is an abstract private type then we transfer the
13506                --  derivation of the interface primitive from the partial view
13507                --  to the full view. This is safe because all the interfaces
13508                --  must be visible in the partial view. Done to avoid adding
13509                --  a new interface derivation to the private part of the
13510                --  enclosing package; otherwise this new derivation would be
13511                --  decorated as hidden when the analysis of the enclosing
13512                --  package completes.
13513
13514                if Is_Abstract_Type (Derived_Type)
13515                  and then In_Private_Part (Current_Scope)
13516                  and then Has_Private_Declaration (Derived_Type)
13517                then
13518                   declare
13519                      Partial_View : Entity_Id;
13520                      Elmt         : Elmt_Id;
13521                      Ent          : Entity_Id;
13522
13523                   begin
13524                      Partial_View := First_Entity (Current_Scope);
13525                      loop
13526                         exit when No (Partial_View)
13527                           or else (Has_Private_Declaration (Partial_View)
13528                                      and then
13529                                    Full_View (Partial_View) = Derived_Type);
13530
13531                         Next_Entity (Partial_View);
13532                      end loop;
13533
13534                      --  If the partial view was not found then the source code
13535                      --  has errors and the derivation is not needed.
13536
13537                      if Present (Partial_View) then
13538                         Elmt :=
13539                           First_Elmt (Primitive_Operations (Partial_View));
13540                         while Present (Elmt) loop
13541                            Ent := Node (Elmt);
13542
13543                            if Present (Alias (Ent))
13544                              and then Ultimate_Alias (Ent) = Alias (Subp)
13545                            then
13546                               Append_Elmt
13547                                 (Ent, Primitive_Operations (Derived_Type));
13548                               exit;
13549                            end if;
13550
13551                            Next_Elmt (Elmt);
13552                         end loop;
13553
13554                         --  If the interface primitive was not found in the
13555                         --  partial view then this interface primitive was
13556                         --  overridden. We add a derivation to activate in
13557                         --  Derive_Progenitor_Subprograms the machinery to
13558                         --  search for it.
13559
13560                         if No (Elmt) then
13561                            Derive_Interface_Subprogram
13562                              (New_Subp    => New_Subp,
13563                               Subp        => Subp,
13564                               Actual_Subp => Act_Subp);
13565                         end if;
13566                      end if;
13567                   end;
13568                else
13569                   Derive_Interface_Subprogram
13570                     (New_Subp     => New_Subp,
13571                      Subp         => Subp,
13572                      Actual_Subp  => Act_Subp);
13573                end if;
13574
13575             --  Case 3: Common derivation
13576
13577             else
13578                Derive_Subprogram
13579                  (New_Subp     => New_Subp,
13580                   Parent_Subp  => Subp,
13581                   Derived_Type => Derived_Type,
13582                   Parent_Type  => Parent_Base,
13583                   Actual_Subp  => Act_Subp);
13584             end if;
13585
13586             --  No need to update Act_Elm if we must search for the
13587             --  corresponding operation in the generic actual
13588
13589             if not Need_Search
13590               and then Present (Act_Elmt)
13591             then
13592                Next_Elmt (Act_Elmt);
13593                Act_Subp := Node (Act_Elmt);
13594             end if;
13595
13596             <<Continue>>
13597             Next_Elmt (Elmt);
13598          end loop;
13599
13600          --  Inherit additional operations from progenitors. If the derived
13601          --  type is a generic actual, there are not new primitive operations
13602          --  for the type because it has those of the actual, and therefore
13603          --  nothing needs to be done. The renamings generated above are not
13604          --  primitive operations, and their purpose is simply to make the
13605          --  proper operations visible within an instantiation.
13606
13607          if No (Generic_Actual) then
13608             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
13609          end if;
13610       end if;
13611
13612       --  Final check: Direct descendants must have their primitives in the
13613       --  same order. We exclude from this test untagged types and instances
13614       --  of formal derived types. We skip this test if we have already
13615       --  reported serious errors in the sources.
13616
13617       pragma Assert (not Is_Tagged_Type (Derived_Type)
13618         or else Present (Generic_Actual)
13619         or else Serious_Errors_Detected > 0
13620         or else Check_Derived_Type);
13621    end Derive_Subprograms;
13622
13623    --------------------------------
13624    -- Derived_Standard_Character --
13625    --------------------------------
13626
13627    procedure Derived_Standard_Character
13628      (N            : Node_Id;
13629       Parent_Type  : Entity_Id;
13630       Derived_Type : Entity_Id)
13631    is
13632       Loc           : constant Source_Ptr := Sloc (N);
13633       Def           : constant Node_Id    := Type_Definition (N);
13634       Indic         : constant Node_Id    := Subtype_Indication (Def);
13635       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
13636       Implicit_Base : constant Entity_Id  :=
13637                         Create_Itype
13638                           (E_Enumeration_Type, N, Derived_Type, 'B');
13639
13640       Lo : Node_Id;
13641       Hi : Node_Id;
13642
13643    begin
13644       Discard_Node (Process_Subtype (Indic, N));
13645
13646       Set_Etype     (Implicit_Base, Parent_Base);
13647       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
13648       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
13649
13650       Set_Is_Character_Type  (Implicit_Base, True);
13651       Set_Has_Delayed_Freeze (Implicit_Base);
13652
13653       --  The bounds of the implicit base are the bounds of the parent base.
13654       --  Note that their type is the parent base.
13655
13656       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
13657       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
13658
13659       Set_Scalar_Range (Implicit_Base,
13660         Make_Range (Loc,
13661           Low_Bound  => Lo,
13662           High_Bound => Hi));
13663
13664       Conditional_Delay (Derived_Type, Parent_Type);
13665
13666       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
13667       Set_Etype (Derived_Type, Implicit_Base);
13668       Set_Size_Info         (Derived_Type, Parent_Type);
13669
13670       if Unknown_RM_Size (Derived_Type) then
13671          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
13672       end if;
13673
13674       Set_Is_Character_Type (Derived_Type, True);
13675
13676       if Nkind (Indic) /= N_Subtype_Indication then
13677
13678          --  If no explicit constraint, the bounds are those
13679          --  of the parent type.
13680
13681          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
13682          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
13683          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
13684       end if;
13685
13686       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
13687
13688       --  Because the implicit base is used in the conversion of the bounds, we
13689       --  have to freeze it now. This is similar to what is done for numeric
13690       --  types, and it equally suspicious, but otherwise a non-static bound
13691       --  will have a reference to an unfrozen type, which is rejected by Gigi
13692       --  (???). This requires specific care for definition of stream
13693       --  attributes. For details, see comments at the end of
13694       --  Build_Derived_Numeric_Type.
13695
13696       Freeze_Before (N, Implicit_Base);
13697    end Derived_Standard_Character;
13698
13699    ------------------------------
13700    -- Derived_Type_Declaration --
13701    ------------------------------
13702
13703    procedure Derived_Type_Declaration
13704      (T             : Entity_Id;
13705       N             : Node_Id;
13706       Is_Completion : Boolean)
13707    is
13708       Parent_Type  : Entity_Id;
13709
13710       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
13711       --  Check whether the parent type is a generic formal, or derives
13712       --  directly or indirectly from one.
13713
13714       ------------------------
13715       -- Comes_From_Generic --
13716       ------------------------
13717
13718       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
13719       begin
13720          if Is_Generic_Type (Typ) then
13721             return True;
13722
13723          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
13724             return True;
13725
13726          elsif Is_Private_Type (Typ)
13727            and then Present (Full_View (Typ))
13728            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
13729          then
13730             return True;
13731
13732          elsif Is_Generic_Actual_Type (Typ) then
13733             return True;
13734
13735          else
13736             return False;
13737          end if;
13738       end Comes_From_Generic;
13739
13740       --  Local variables
13741
13742       Def          : constant Node_Id := Type_Definition (N);
13743       Iface_Def    : Node_Id;
13744       Indic        : constant Node_Id := Subtype_Indication (Def);
13745       Extension    : constant Node_Id := Record_Extension_Part (Def);
13746       Parent_Node  : Node_Id;
13747       Parent_Scope : Entity_Id;
13748       Taggd        : Boolean;
13749
13750    --  Start of processing for Derived_Type_Declaration
13751
13752    begin
13753       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
13754
13755       --  Ada 2005 (AI-251): In case of interface derivation check that the
13756       --  parent is also an interface.
13757
13758       if Interface_Present (Def) then
13759          if not Is_Interface (Parent_Type) then
13760             Diagnose_Interface (Indic, Parent_Type);
13761
13762          else
13763             Parent_Node := Parent (Base_Type (Parent_Type));
13764             Iface_Def   := Type_Definition (Parent_Node);
13765
13766             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
13767             --  other limited interfaces.
13768
13769             if Limited_Present (Def) then
13770                if Limited_Present (Iface_Def) then
13771                   null;
13772
13773                elsif Protected_Present (Iface_Def) then
13774                   Error_Msg_NE
13775                     ("descendant of& must be declared"
13776                        & " as a protected interface",
13777                          N, Parent_Type);
13778
13779                elsif Synchronized_Present (Iface_Def) then
13780                   Error_Msg_NE
13781                     ("descendant of& must be declared"
13782                        & " as a synchronized interface",
13783                          N, Parent_Type);
13784
13785                elsif Task_Present (Iface_Def) then
13786                   Error_Msg_NE
13787                     ("descendant of& must be declared as a task interface",
13788                        N, Parent_Type);
13789
13790                else
13791                   Error_Msg_N
13792                     ("(Ada 2005) limited interface cannot "
13793                      & "inherit from non-limited interface", Indic);
13794                end if;
13795
13796             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
13797             --  from non-limited or limited interfaces.
13798
13799             elsif not Protected_Present (Def)
13800               and then not Synchronized_Present (Def)
13801               and then not Task_Present (Def)
13802             then
13803                if Limited_Present (Iface_Def) then
13804                   null;
13805
13806                elsif Protected_Present (Iface_Def) then
13807                   Error_Msg_NE
13808                     ("descendant of& must be declared"
13809                        & " as a protected interface",
13810                          N, Parent_Type);
13811
13812                elsif Synchronized_Present (Iface_Def) then
13813                   Error_Msg_NE
13814                     ("descendant of& must be declared"
13815                        & " as a synchronized interface",
13816                          N, Parent_Type);
13817
13818                elsif Task_Present (Iface_Def) then
13819                   Error_Msg_NE
13820                     ("descendant of& must be declared as a task interface",
13821                        N, Parent_Type);
13822                else
13823                   null;
13824                end if;
13825             end if;
13826          end if;
13827       end if;
13828
13829       if Is_Tagged_Type (Parent_Type)
13830         and then Is_Concurrent_Type (Parent_Type)
13831         and then not Is_Interface (Parent_Type)
13832       then
13833          Error_Msg_N
13834            ("parent type of a record extension cannot be "
13835             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
13836          Set_Etype (T, Any_Type);
13837          return;
13838       end if;
13839
13840       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
13841       --  interfaces
13842
13843       if Is_Tagged_Type (Parent_Type)
13844         and then Is_Non_Empty_List (Interface_List (Def))
13845       then
13846          declare
13847             Intf : Node_Id;
13848             T    : Entity_Id;
13849
13850          begin
13851             Intf := First (Interface_List (Def));
13852             while Present (Intf) loop
13853                T := Find_Type_Of_Subtype_Indic (Intf);
13854
13855                if not Is_Interface (T) then
13856                   Diagnose_Interface (Intf, T);
13857
13858                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
13859                --  a limited type from having a nonlimited progenitor.
13860
13861                elsif (Limited_Present (Def)
13862                        or else (not Is_Interface (Parent_Type)
13863                                  and then Is_Limited_Type (Parent_Type)))
13864                  and then not Is_Limited_Interface (T)
13865                then
13866                   Error_Msg_NE
13867                    ("progenitor interface& of limited type must be limited",
13868                      N, T);
13869                end if;
13870
13871                Next (Intf);
13872             end loop;
13873          end;
13874       end if;
13875
13876       if Parent_Type = Any_Type
13877         or else Etype (Parent_Type) = Any_Type
13878         or else (Is_Class_Wide_Type (Parent_Type)
13879                    and then Etype (Parent_Type) = T)
13880       then
13881          --  If Parent_Type is undefined or illegal, make new type into a
13882          --  subtype of Any_Type, and set a few attributes to prevent cascaded
13883          --  errors. If this is a self-definition, emit error now.
13884
13885          if T = Parent_Type
13886            or else T = Etype (Parent_Type)
13887          then
13888             Error_Msg_N ("type cannot be used in its own definition", Indic);
13889          end if;
13890
13891          Set_Ekind        (T, Ekind (Parent_Type));
13892          Set_Etype        (T, Any_Type);
13893          Set_Scalar_Range (T, Scalar_Range (Any_Type));
13894
13895          if Is_Tagged_Type (T)
13896            and then Is_Record_Type (T)
13897          then
13898             Set_Direct_Primitive_Operations (T, New_Elmt_List);
13899          end if;
13900
13901          return;
13902       end if;
13903
13904       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
13905       --  an interface is special because the list of interfaces in the full
13906       --  view can be given in any order. For example:
13907
13908       --     type A is interface;
13909       --     type B is interface and A;
13910       --     type D is new B with private;
13911       --   private
13912       --     type D is new A and B with null record; -- 1 --
13913
13914       --  In this case we perform the following transformation of -1-:
13915
13916       --     type D is new B and A with null record;
13917
13918       --  If the parent of the full-view covers the parent of the partial-view
13919       --  we have two possible cases:
13920
13921       --     1) They have the same parent
13922       --     2) The parent of the full-view implements some further interfaces
13923
13924       --  In both cases we do not need to perform the transformation. In the
13925       --  first case the source program is correct and the transformation is
13926       --  not needed; in the second case the source program does not fulfill
13927       --  the no-hidden interfaces rule (AI-396) and the error will be reported
13928       --  later.
13929
13930       --  This transformation not only simplifies the rest of the analysis of
13931       --  this type declaration but also simplifies the correct generation of
13932       --  the object layout to the expander.
13933
13934       if In_Private_Part (Current_Scope)
13935         and then Is_Interface (Parent_Type)
13936       then
13937          declare
13938             Iface               : Node_Id;
13939             Partial_View        : Entity_Id;
13940             Partial_View_Parent : Entity_Id;
13941             New_Iface           : Node_Id;
13942
13943          begin
13944             --  Look for the associated private type declaration
13945
13946             Partial_View := First_Entity (Current_Scope);
13947             loop
13948                exit when No (Partial_View)
13949                  or else (Has_Private_Declaration (Partial_View)
13950                            and then Full_View (Partial_View) = T);
13951
13952                Next_Entity (Partial_View);
13953             end loop;
13954
13955             --  If the partial view was not found then the source code has
13956             --  errors and the transformation is not needed.
13957
13958             if Present (Partial_View) then
13959                Partial_View_Parent := Etype (Partial_View);
13960
13961                --  If the parent of the full-view covers the parent of the
13962                --  partial-view we have nothing else to do.
13963
13964                if Interface_Present_In_Ancestor
13965                     (Parent_Type, Partial_View_Parent)
13966                then
13967                   null;
13968
13969                --  Traverse the list of interfaces of the full-view to look
13970                --  for the parent of the partial-view and perform the tree
13971                --  transformation.
13972
13973                else
13974                   Iface := First (Interface_List (Def));
13975                   while Present (Iface) loop
13976                      if Etype (Iface) = Etype (Partial_View) then
13977                         Rewrite (Subtype_Indication (Def),
13978                           New_Copy (Subtype_Indication
13979                                      (Parent (Partial_View))));
13980
13981                         New_Iface :=
13982                           Make_Identifier (Sloc (N), Chars (Parent_Type));
13983                         Append (New_Iface, Interface_List (Def));
13984
13985                         --  Analyze the transformed code
13986
13987                         Derived_Type_Declaration (T, N, Is_Completion);
13988                         return;
13989                      end if;
13990
13991                      Next (Iface);
13992                   end loop;
13993                end if;
13994             end if;
13995          end;
13996       end if;
13997
13998       --  Only composite types other than array types are allowed to have
13999       --  discriminants.
14000
14001       if Present (Discriminant_Specifications (N))
14002         and then (Is_Elementary_Type (Parent_Type)
14003                   or else Is_Array_Type (Parent_Type))
14004         and then not Error_Posted (N)
14005       then
14006          Error_Msg_N
14007            ("elementary or array type cannot have discriminants",
14008             Defining_Identifier (First (Discriminant_Specifications (N))));
14009          Set_Has_Discriminants (T, False);
14010       end if;
14011
14012       --  In Ada 83, a derived type defined in a package specification cannot
14013       --  be used for further derivation until the end of its visible part.
14014       --  Note that derivation in the private part of the package is allowed.
14015
14016       if Ada_Version = Ada_83
14017         and then Is_Derived_Type (Parent_Type)
14018         and then In_Visible_Part (Scope (Parent_Type))
14019       then
14020          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
14021             Error_Msg_N
14022               ("(Ada 83): premature use of type for derivation", Indic);
14023          end if;
14024       end if;
14025
14026       --  Check for early use of incomplete or private type
14027
14028       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
14029          Error_Msg_N ("premature derivation of incomplete type", Indic);
14030          return;
14031
14032       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
14033               and then not Comes_From_Generic (Parent_Type))
14034         or else Has_Private_Component (Parent_Type)
14035       then
14036          --  The ancestor type of a formal type can be incomplete, in which
14037          --  case only the operations of the partial view are available in
14038          --  the generic. Subsequent checks may be required when the full
14039          --  view is analyzed, to verify that derivation from a tagged type
14040          --  has an extension.
14041
14042          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
14043             null;
14044
14045          elsif No (Underlying_Type (Parent_Type))
14046            or else Has_Private_Component (Parent_Type)
14047          then
14048             Error_Msg_N
14049               ("premature derivation of derived or private type", Indic);
14050
14051             --  Flag the type itself as being in error, this prevents some
14052             --  nasty problems with subsequent uses of the malformed type.
14053
14054             Set_Error_Posted (T);
14055
14056          --  Check that within the immediate scope of an untagged partial
14057          --  view it's illegal to derive from the partial view if the
14058          --  full view is tagged. (7.3(7))
14059
14060          --  We verify that the Parent_Type is a partial view by checking
14061          --  that it is not a Full_Type_Declaration (i.e. a private type or
14062          --  private extension declaration), to distinguish a partial view
14063          --  from  a derivation from a private type which also appears as
14064          --  E_Private_Type.
14065
14066          elsif Present (Full_View (Parent_Type))
14067            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
14068            and then not Is_Tagged_Type (Parent_Type)
14069            and then Is_Tagged_Type (Full_View (Parent_Type))
14070          then
14071             Parent_Scope := Scope (T);
14072             while Present (Parent_Scope)
14073               and then Parent_Scope /= Standard_Standard
14074             loop
14075                if Parent_Scope = Scope (Parent_Type) then
14076                   Error_Msg_N
14077                     ("premature derivation from type with tagged full view",
14078                      Indic);
14079                end if;
14080
14081                Parent_Scope := Scope (Parent_Scope);
14082             end loop;
14083          end if;
14084       end if;
14085
14086       --  Check that form of derivation is appropriate
14087
14088       Taggd := Is_Tagged_Type (Parent_Type);
14089
14090       --  Perhaps the parent type should be changed to the class-wide type's
14091       --  specific type in this case to prevent cascading errors ???
14092
14093       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
14094          Error_Msg_N ("parent type must not be a class-wide type", Indic);
14095          return;
14096       end if;
14097
14098       if Present (Extension) and then not Taggd then
14099          Error_Msg_N
14100            ("type derived from untagged type cannot have extension", Indic);
14101
14102       elsif No (Extension) and then Taggd then
14103
14104          --  If this declaration is within a private part (or body) of a
14105          --  generic instantiation then the derivation is allowed (the parent
14106          --  type can only appear tagged in this case if it's a generic actual
14107          --  type, since it would otherwise have been rejected in the analysis
14108          --  of the generic template).
14109
14110          if not Is_Generic_Actual_Type (Parent_Type)
14111            or else In_Visible_Part (Scope (Parent_Type))
14112          then
14113             if Is_Class_Wide_Type (Parent_Type) then
14114                Error_Msg_N
14115                  ("parent type must not be a class-wide type", Indic);
14116
14117                --  Use specific type to prevent cascaded errors.
14118
14119                Parent_Type := Etype (Parent_Type);
14120
14121             else
14122                Error_Msg_N
14123                  ("type derived from tagged type must have extension", Indic);
14124             end if;
14125          end if;
14126       end if;
14127
14128       --  AI-443: Synchronized formal derived types require a private
14129       --  extension. There is no point in checking the ancestor type or
14130       --  the progenitors since the construct is wrong to begin with.
14131
14132       if Ada_Version >= Ada_2005
14133         and then Is_Generic_Type (T)
14134         and then Present (Original_Node (N))
14135       then
14136          declare
14137             Decl : constant Node_Id := Original_Node (N);
14138
14139          begin
14140             if Nkind (Decl) = N_Formal_Type_Declaration
14141               and then Nkind (Formal_Type_Definition (Decl)) =
14142                          N_Formal_Derived_Type_Definition
14143               and then Synchronized_Present (Formal_Type_Definition (Decl))
14144               and then No (Extension)
14145
14146                --  Avoid emitting a duplicate error message
14147
14148               and then not Error_Posted (Indic)
14149             then
14150                Error_Msg_N
14151                  ("synchronized derived type must have extension", N);
14152             end if;
14153          end;
14154       end if;
14155
14156       if Null_Exclusion_Present (Def)
14157         and then not Is_Access_Type (Parent_Type)
14158       then
14159          Error_Msg_N ("null exclusion can only apply to an access type", N);
14160       end if;
14161
14162       --  Avoid deriving parent primitives of underlying record views
14163
14164       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
14165         Derive_Subps => not Is_Underlying_Record_View (T));
14166
14167       --  AI-419: The parent type of an explicitly limited derived type must
14168       --  be a limited type or a limited interface.
14169
14170       if Limited_Present (Def) then
14171          Set_Is_Limited_Record (T);
14172
14173          if Is_Interface (T) then
14174             Set_Is_Limited_Interface (T);
14175          end if;
14176
14177          if not Is_Limited_Type (Parent_Type)
14178            and then
14179              (not Is_Interface (Parent_Type)
14180                or else not Is_Limited_Interface (Parent_Type))
14181          then
14182             --  AI05-0096: a derivation in the private part of an instance is
14183             --  legal if the generic formal is untagged limited, and the actual
14184             --  is non-limited.
14185
14186             if Is_Generic_Actual_Type (Parent_Type)
14187               and then In_Private_Part (Current_Scope)
14188               and then
14189                 not Is_Tagged_Type
14190                       (Generic_Parent_Type (Parent (Parent_Type)))
14191             then
14192                null;
14193
14194             else
14195                Error_Msg_NE
14196                  ("parent type& of limited type must be limited",
14197                   N, Parent_Type);
14198             end if;
14199          end if;
14200       end if;
14201    end Derived_Type_Declaration;
14202
14203    ------------------------
14204    -- Diagnose_Interface --
14205    ------------------------
14206
14207    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
14208    begin
14209       if not Is_Interface (E)
14210         and then  E /= Any_Type
14211       then
14212          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
14213       end if;
14214    end Diagnose_Interface;
14215
14216    ----------------------------------
14217    -- Enumeration_Type_Declaration --
14218    ----------------------------------
14219
14220    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14221       Ev     : Uint;
14222       L      : Node_Id;
14223       R_Node : Node_Id;
14224       B_Node : Node_Id;
14225
14226    begin
14227       --  Create identifier node representing lower bound
14228
14229       B_Node := New_Node (N_Identifier, Sloc (Def));
14230       L := First (Literals (Def));
14231       Set_Chars (B_Node, Chars (L));
14232       Set_Entity (B_Node,  L);
14233       Set_Etype (B_Node, T);
14234       Set_Is_Static_Expression (B_Node, True);
14235
14236       R_Node := New_Node (N_Range, Sloc (Def));
14237       Set_Low_Bound  (R_Node, B_Node);
14238
14239       Set_Ekind (T, E_Enumeration_Type);
14240       Set_First_Literal (T, L);
14241       Set_Etype (T, T);
14242       Set_Is_Constrained (T);
14243
14244       Ev := Uint_0;
14245
14246       --  Loop through literals of enumeration type setting pos and rep values
14247       --  except that if the Ekind is already set, then it means the literal
14248       --  was already constructed (case of a derived type declaration and we
14249       --  should not disturb the Pos and Rep values.
14250
14251       while Present (L) loop
14252          if Ekind (L) /= E_Enumeration_Literal then
14253             Set_Ekind (L, E_Enumeration_Literal);
14254             Set_Enumeration_Pos (L, Ev);
14255             Set_Enumeration_Rep (L, Ev);
14256             Set_Is_Known_Valid  (L, True);
14257          end if;
14258
14259          Set_Etype (L, T);
14260          New_Overloaded_Entity (L);
14261          Generate_Definition (L);
14262          Set_Convention (L, Convention_Intrinsic);
14263
14264          --  Case of character literal
14265
14266          if Nkind (L) = N_Defining_Character_Literal then
14267             Set_Is_Character_Type (T, True);
14268
14269             --  Check violation of No_Wide_Characters
14270
14271             if Restriction_Check_Required (No_Wide_Characters) then
14272                Get_Name_String (Chars (L));
14273
14274                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
14275                   Check_Restriction (No_Wide_Characters, L);
14276                end if;
14277             end if;
14278          end if;
14279
14280          Ev := Ev + 1;
14281          Next (L);
14282       end loop;
14283
14284       --  Now create a node representing upper bound
14285
14286       B_Node := New_Node (N_Identifier, Sloc (Def));
14287       Set_Chars (B_Node, Chars (Last (Literals (Def))));
14288       Set_Entity (B_Node,  Last (Literals (Def)));
14289       Set_Etype (B_Node, T);
14290       Set_Is_Static_Expression (B_Node, True);
14291
14292       Set_High_Bound (R_Node, B_Node);
14293
14294       --  Initialize various fields of the type. Some of this information
14295       --  may be overwritten later through rep.clauses.
14296
14297       Set_Scalar_Range    (T, R_Node);
14298       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
14299       Set_Enum_Esize      (T);
14300       Set_Enum_Pos_To_Rep (T, Empty);
14301
14302       --  Set Discard_Names if configuration pragma set, or if there is
14303       --  a parameterless pragma in the current declarative region
14304
14305       if Global_Discard_Names
14306         or else Discard_Names (Scope (T))
14307       then
14308          Set_Discard_Names (T);
14309       end if;
14310
14311       --  Process end label if there is one
14312
14313       if Present (Def) then
14314          Process_End_Label (Def, 'e', T);
14315       end if;
14316    end Enumeration_Type_Declaration;
14317
14318    ---------------------------------
14319    -- Expand_To_Stored_Constraint --
14320    ---------------------------------
14321
14322    function Expand_To_Stored_Constraint
14323      (Typ        : Entity_Id;
14324       Constraint : Elist_Id) return Elist_Id
14325    is
14326       Explicitly_Discriminated_Type : Entity_Id;
14327       Expansion    : Elist_Id;
14328       Discriminant : Entity_Id;
14329
14330       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
14331       --  Find the nearest type that actually specifies discriminants
14332
14333       ---------------------------------
14334       -- Type_With_Explicit_Discrims --
14335       ---------------------------------
14336
14337       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
14338          Typ : constant E := Base_Type (Id);
14339
14340       begin
14341          if Ekind (Typ) in Incomplete_Or_Private_Kind then
14342             if Present (Full_View (Typ)) then
14343                return Type_With_Explicit_Discrims (Full_View (Typ));
14344             end if;
14345
14346          else
14347             if Has_Discriminants (Typ) then
14348                return Typ;
14349             end if;
14350          end if;
14351
14352          if Etype (Typ) = Typ then
14353             return Empty;
14354          elsif Has_Discriminants (Typ) then
14355             return Typ;
14356          else
14357             return Type_With_Explicit_Discrims (Etype (Typ));
14358          end if;
14359
14360       end Type_With_Explicit_Discrims;
14361
14362    --  Start of processing for Expand_To_Stored_Constraint
14363
14364    begin
14365       if No (Constraint)
14366         or else Is_Empty_Elmt_List (Constraint)
14367       then
14368          return No_Elist;
14369       end if;
14370
14371       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
14372
14373       if No (Explicitly_Discriminated_Type) then
14374          return No_Elist;
14375       end if;
14376
14377       Expansion := New_Elmt_List;
14378
14379       Discriminant :=
14380          First_Stored_Discriminant (Explicitly_Discriminated_Type);
14381       while Present (Discriminant) loop
14382          Append_Elmt (
14383            Get_Discriminant_Value (
14384              Discriminant, Explicitly_Discriminated_Type, Constraint),
14385            Expansion);
14386          Next_Stored_Discriminant (Discriminant);
14387       end loop;
14388
14389       return Expansion;
14390    end Expand_To_Stored_Constraint;
14391
14392    ---------------------------
14393    -- Find_Hidden_Interface --
14394    ---------------------------
14395
14396    function Find_Hidden_Interface
14397      (Src  : Elist_Id;
14398       Dest : Elist_Id) return Entity_Id
14399    is
14400       Iface      : Entity_Id;
14401       Iface_Elmt : Elmt_Id;
14402
14403    begin
14404       if Present (Src) and then Present (Dest) then
14405          Iface_Elmt := First_Elmt (Src);
14406          while Present (Iface_Elmt) loop
14407             Iface := Node (Iface_Elmt);
14408
14409             if Is_Interface (Iface)
14410               and then not Contain_Interface (Iface, Dest)
14411             then
14412                return Iface;
14413             end if;
14414
14415             Next_Elmt (Iface_Elmt);
14416          end loop;
14417       end if;
14418
14419       return Empty;
14420    end Find_Hidden_Interface;
14421
14422    --------------------
14423    -- Find_Type_Name --
14424    --------------------
14425
14426    function Find_Type_Name (N : Node_Id) return Entity_Id is
14427       Id       : constant Entity_Id := Defining_Identifier (N);
14428       Prev     : Entity_Id;
14429       New_Id   : Entity_Id;
14430       Prev_Par : Node_Id;
14431
14432       procedure Tag_Mismatch;
14433       --  Diagnose a tagged partial view whose full view is untagged.
14434       --  We post the message on the full view, with a reference to
14435       --  the previous partial view. The partial view can be private
14436       --  or incomplete, and these are handled in a different manner,
14437       --  so we determine the position of the error message from the
14438       --  respective slocs of both.
14439
14440       ------------------
14441       -- Tag_Mismatch --
14442       ------------------
14443
14444       procedure Tag_Mismatch is
14445       begin
14446          if Sloc (Prev) < Sloc (Id) then
14447             if Ada_Version >= Ada_2012
14448               and then Nkind (N) = N_Private_Type_Declaration
14449             then
14450                Error_Msg_NE
14451                  ("declaration of private } must be a tagged type ", Id, Prev);
14452             else
14453                Error_Msg_NE
14454                  ("full declaration of } must be a tagged type ", Id, Prev);
14455             end if;
14456          else
14457             if Ada_Version >= Ada_2012
14458               and then Nkind (N) = N_Private_Type_Declaration
14459             then
14460                Error_Msg_NE
14461                  ("declaration of private } must be a tagged type ", Prev, Id);
14462             else
14463                Error_Msg_NE
14464                  ("full declaration of } must be a tagged type ", Prev, Id);
14465             end if;
14466          end if;
14467       end Tag_Mismatch;
14468
14469    --  Start of processing for Find_Type_Name
14470
14471    begin
14472       --  Find incomplete declaration, if one was given
14473
14474       Prev := Current_Entity_In_Scope (Id);
14475
14476       --  New type declaration
14477
14478       if No (Prev) then
14479          Enter_Name (Id);
14480          return Id;
14481
14482       --  Previous declaration exists
14483
14484       else
14485          Prev_Par := Parent (Prev);
14486
14487          --  Error if not incomplete/private case except if previous
14488          --  declaration is implicit, etc. Enter_Name will emit error if
14489          --  appropriate.
14490
14491          if not Is_Incomplete_Or_Private_Type (Prev) then
14492             Enter_Name (Id);
14493             New_Id := Id;
14494
14495          --  Check invalid completion of private or incomplete type
14496
14497          elsif not Nkind_In (N, N_Full_Type_Declaration,
14498                                 N_Task_Type_Declaration,
14499                                 N_Protected_Type_Declaration)
14500            and then
14501              (Ada_Version < Ada_2012
14502                 or else not Is_Incomplete_Type (Prev)
14503                 or else not Nkind_In (N, N_Private_Type_Declaration,
14504                                          N_Private_Extension_Declaration))
14505          then
14506             --  Completion must be a full type declarations (RM 7.3(4))
14507
14508             Error_Msg_Sloc := Sloc (Prev);
14509             Error_Msg_NE ("invalid completion of }", Id, Prev);
14510
14511             --  Set scope of Id to avoid cascaded errors. Entity is never
14512             --  examined again, except when saving globals in generics.
14513
14514             Set_Scope (Id, Current_Scope);
14515             New_Id := Id;
14516
14517             --  If this is a repeated incomplete declaration, no further
14518             --  checks are possible.
14519
14520             if Nkind (N) = N_Incomplete_Type_Declaration then
14521                return Prev;
14522             end if;
14523
14524          --  Case of full declaration of incomplete type
14525
14526          elsif Ekind (Prev) = E_Incomplete_Type
14527            and then (Ada_Version < Ada_2012
14528                       or else No (Full_View (Prev))
14529                       or else not Is_Private_Type (Full_View (Prev)))
14530          then
14531
14532             --  Indicate that the incomplete declaration has a matching full
14533             --  declaration. The defining occurrence of the incomplete
14534             --  declaration remains the visible one, and the procedure
14535             --  Get_Full_View dereferences it whenever the type is used.
14536
14537             if Present (Full_View (Prev)) then
14538                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14539             end if;
14540
14541             Set_Full_View (Prev,  Id);
14542             Append_Entity (Id, Current_Scope);
14543             Set_Is_Public (Id, Is_Public (Prev));
14544             Set_Is_Internal (Id);
14545             New_Id := Prev;
14546
14547             --  If the incomplete view is tagged, a class_wide type has been
14548             --  created already. Use it for the private type as well, in order
14549             --  to prevent multiple incompatible class-wide types that may be
14550             --  created for self-referential anonymous access components.
14551
14552             if Is_Tagged_Type (Prev)
14553               and then Present (Class_Wide_Type (Prev))
14554             then
14555                Set_Ekind (Id, Ekind (Prev));         --  will be reset later
14556                Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
14557                Set_Etype (Class_Wide_Type (Id), Id);
14558             end if;
14559
14560          --  Case of full declaration of private type
14561
14562          else
14563             --  If the private type was a completion of an incomplete type then
14564             --  update Prev to reference the private type
14565
14566             if Ada_Version >= Ada_2012
14567               and then Ekind (Prev) = E_Incomplete_Type
14568               and then Present (Full_View (Prev))
14569               and then Is_Private_Type (Full_View (Prev))
14570             then
14571                Prev := Full_View (Prev);
14572                Prev_Par := Parent (Prev);
14573             end if;
14574
14575             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
14576                if Etype (Prev) /= Prev then
14577
14578                   --  Prev is a private subtype or a derived type, and needs
14579                   --  no completion.
14580
14581                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14582                   New_Id := Id;
14583
14584                elsif Ekind (Prev) = E_Private_Type
14585                  and then Nkind_In (N, N_Task_Type_Declaration,
14586                                        N_Protected_Type_Declaration)
14587                then
14588                   Error_Msg_N
14589                    ("completion of nonlimited type cannot be limited", N);
14590
14591                elsif Ekind (Prev) = E_Record_Type_With_Private
14592                  and then Nkind_In (N, N_Task_Type_Declaration,
14593                                        N_Protected_Type_Declaration)
14594                then
14595                   if not Is_Limited_Record (Prev) then
14596                      Error_Msg_N
14597                         ("completion of nonlimited type cannot be limited", N);
14598
14599                   elsif No (Interface_List (N)) then
14600                      Error_Msg_N
14601                         ("completion of tagged private type must be tagged",
14602                          N);
14603                   end if;
14604
14605                elsif Nkind (N) = N_Full_Type_Declaration
14606                  and then
14607                    Nkind (Type_Definition (N)) = N_Record_Definition
14608                  and then Interface_Present (Type_Definition (N))
14609                then
14610                   Error_Msg_N
14611                     ("completion of private type cannot be an interface", N);
14612                end if;
14613
14614             --  Ada 2005 (AI-251): Private extension declaration of a task
14615             --  type or a protected type. This case arises when covering
14616             --  interface types.
14617
14618             elsif Nkind_In (N, N_Task_Type_Declaration,
14619                                N_Protected_Type_Declaration)
14620             then
14621                null;
14622
14623             elsif Nkind (N) /= N_Full_Type_Declaration
14624               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
14625             then
14626                Error_Msg_N
14627                  ("full view of private extension must be an extension", N);
14628
14629             elsif not (Abstract_Present (Parent (Prev)))
14630               and then Abstract_Present (Type_Definition (N))
14631             then
14632                Error_Msg_N
14633                  ("full view of non-abstract extension cannot be abstract", N);
14634             end if;
14635
14636             if not In_Private_Part (Current_Scope) then
14637                Error_Msg_N
14638                  ("declaration of full view must appear in private part", N);
14639             end if;
14640
14641             Copy_And_Swap (Prev, Id);
14642             Set_Has_Private_Declaration (Prev);
14643             Set_Has_Private_Declaration (Id);
14644
14645             --  If no error, propagate freeze_node from private to full view.
14646             --  It may have been generated for an early operational item.
14647
14648             if Present (Freeze_Node (Id))
14649               and then Serious_Errors_Detected = 0
14650               and then No (Full_View (Id))
14651             then
14652                Set_Freeze_Node (Prev, Freeze_Node (Id));
14653                Set_Freeze_Node (Id, Empty);
14654                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
14655             end if;
14656
14657             Set_Full_View (Id, Prev);
14658             New_Id := Prev;
14659          end if;
14660
14661          --  Verify that full declaration conforms to partial one
14662
14663          if Is_Incomplete_Or_Private_Type (Prev)
14664            and then Present (Discriminant_Specifications (Prev_Par))
14665          then
14666             if Present (Discriminant_Specifications (N)) then
14667                if Ekind (Prev) = E_Incomplete_Type then
14668                   Check_Discriminant_Conformance (N, Prev, Prev);
14669                else
14670                   Check_Discriminant_Conformance (N, Prev, Id);
14671                end if;
14672
14673             else
14674                Error_Msg_N
14675                  ("missing discriminants in full type declaration", N);
14676
14677                --  To avoid cascaded errors on subsequent use, share the
14678                --  discriminants of the partial view.
14679
14680                Set_Discriminant_Specifications (N,
14681                  Discriminant_Specifications (Prev_Par));
14682             end if;
14683          end if;
14684
14685          --  A prior untagged partial view can have an associated class-wide
14686          --  type due to use of the class attribute, and in this case the full
14687          --  type must also be tagged. This Ada 95 usage is deprecated in favor
14688          --  of incomplete tagged declarations, but we check for it.
14689
14690          if Is_Type (Prev)
14691            and then (Is_Tagged_Type (Prev)
14692                        or else Present (Class_Wide_Type (Prev)))
14693          then
14694             --  Ada 2012 (AI05-0162): A private type may be the completion of
14695             --  an incomplete type
14696
14697             if Ada_Version >= Ada_2012
14698               and then Is_Incomplete_Type (Prev)
14699               and then Nkind_In (N, N_Private_Type_Declaration,
14700                                     N_Private_Extension_Declaration)
14701             then
14702                --  No need to check private extensions since they are tagged
14703
14704                if Nkind (N) = N_Private_Type_Declaration
14705                  and then not Tagged_Present (N)
14706                then
14707                   Tag_Mismatch;
14708                end if;
14709
14710             --  The full declaration is either a tagged type (including
14711             --  a synchronized type that implements interfaces) or a
14712             --  type extension, otherwise this is an error.
14713
14714             elsif Nkind_In (N, N_Task_Type_Declaration,
14715                                N_Protected_Type_Declaration)
14716             then
14717                if No (Interface_List (N))
14718                  and then not Error_Posted (N)
14719                then
14720                   Tag_Mismatch;
14721                end if;
14722
14723             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
14724
14725                --  Indicate that the previous declaration (tagged incomplete
14726                --  or private declaration) requires the same on the full one.
14727
14728                if not Tagged_Present (Type_Definition (N)) then
14729                   Tag_Mismatch;
14730                   Set_Is_Tagged_Type (Id);
14731                end if;
14732
14733             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
14734                if No (Record_Extension_Part (Type_Definition (N))) then
14735                   Error_Msg_NE
14736                     ("full declaration of } must be a record extension",
14737                      Prev, Id);
14738
14739                   --  Set some attributes to produce a usable full view
14740
14741                   Set_Is_Tagged_Type (Id);
14742                end if;
14743
14744             else
14745                Tag_Mismatch;
14746             end if;
14747          end if;
14748
14749          return New_Id;
14750       end if;
14751    end Find_Type_Name;
14752
14753    -------------------------
14754    -- Find_Type_Of_Object --
14755    -------------------------
14756
14757    function Find_Type_Of_Object
14758      (Obj_Def     : Node_Id;
14759       Related_Nod : Node_Id) return Entity_Id
14760    is
14761       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
14762       P        : Node_Id := Parent (Obj_Def);
14763       T        : Entity_Id;
14764       Nam      : Name_Id;
14765
14766    begin
14767       --  If the parent is a component_definition node we climb to the
14768       --  component_declaration node
14769
14770       if Nkind (P) = N_Component_Definition then
14771          P := Parent (P);
14772       end if;
14773
14774       --  Case of an anonymous array subtype
14775
14776       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
14777                              N_Unconstrained_Array_Definition)
14778       then
14779          T := Empty;
14780          Array_Type_Declaration (T, Obj_Def);
14781
14782       --  Create an explicit subtype whenever possible
14783
14784       elsif Nkind (P) /= N_Component_Declaration
14785         and then Def_Kind = N_Subtype_Indication
14786       then
14787          --  Base name of subtype on object name, which will be unique in
14788          --  the current scope.
14789
14790          --  If this is a duplicate declaration, return base type, to avoid
14791          --  generating duplicate anonymous types.
14792
14793          if Error_Posted (P) then
14794             Analyze (Subtype_Mark (Obj_Def));
14795             return Entity (Subtype_Mark (Obj_Def));
14796          end if;
14797
14798          Nam :=
14799             New_External_Name
14800              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
14801
14802          T := Make_Defining_Identifier (Sloc (P), Nam);
14803
14804          Insert_Action (Obj_Def,
14805            Make_Subtype_Declaration (Sloc (P),
14806              Defining_Identifier => T,
14807              Subtype_Indication  => Relocate_Node (Obj_Def)));
14808
14809          --  This subtype may need freezing, and this will not be done
14810          --  automatically if the object declaration is not in declarative
14811          --  part. Since this is an object declaration, the type cannot always
14812          --  be frozen here. Deferred constants do not freeze their type
14813          --  (which often enough will be private).
14814
14815          if Nkind (P) = N_Object_Declaration
14816            and then Constant_Present (P)
14817            and then No (Expression (P))
14818          then
14819             null;
14820          else
14821             Insert_Actions (Obj_Def, Freeze_Entity (T, P));
14822          end if;
14823
14824       --  Ada 2005 AI-406: the object definition in an object declaration
14825       --  can be an access definition.
14826
14827       elsif Def_Kind = N_Access_Definition then
14828          T := Access_Definition (Related_Nod, Obj_Def);
14829          Set_Is_Local_Anonymous_Access (T);
14830
14831       --  Otherwise, the object definition is just a subtype_mark
14832
14833       else
14834          T := Process_Subtype (Obj_Def, Related_Nod);
14835       end if;
14836
14837       return T;
14838    end Find_Type_Of_Object;
14839
14840    --------------------------------
14841    -- Find_Type_Of_Subtype_Indic --
14842    --------------------------------
14843
14844    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
14845       Typ : Entity_Id;
14846
14847    begin
14848       --  Case of subtype mark with a constraint
14849
14850       if Nkind (S) = N_Subtype_Indication then
14851          Find_Type (Subtype_Mark (S));
14852          Typ := Entity (Subtype_Mark (S));
14853
14854          if not
14855            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
14856          then
14857             Error_Msg_N
14858               ("incorrect constraint for this kind of type", Constraint (S));
14859             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
14860          end if;
14861
14862       --  Otherwise we have a subtype mark without a constraint
14863
14864       elsif Error_Posted (S) then
14865          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
14866          return Any_Type;
14867
14868       else
14869          Find_Type (S);
14870          Typ := Entity (S);
14871       end if;
14872
14873       --  Check No_Wide_Characters restriction
14874
14875       Check_Wide_Character_Restriction (Typ, S);
14876
14877       return Typ;
14878    end Find_Type_Of_Subtype_Indic;
14879
14880    -------------------------------------
14881    -- Floating_Point_Type_Declaration --
14882    -------------------------------------
14883
14884    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14885       Digs          : constant Node_Id := Digits_Expression (Def);
14886       Digs_Val      : Uint;
14887       Base_Typ      : Entity_Id;
14888       Implicit_Base : Entity_Id;
14889       Bound         : Node_Id;
14890
14891       function Can_Derive_From (E : Entity_Id) return Boolean;
14892       --  Find if given digits value allows derivation from specified type
14893
14894       ---------------------
14895       -- Can_Derive_From --
14896       ---------------------
14897
14898       function Can_Derive_From (E : Entity_Id) return Boolean is
14899          Spec : constant Entity_Id := Real_Range_Specification (Def);
14900
14901       begin
14902          if Digs_Val > Digits_Value (E) then
14903             return False;
14904          end if;
14905
14906          if Present (Spec) then
14907             if Expr_Value_R (Type_Low_Bound (E)) >
14908                Expr_Value_R (Low_Bound (Spec))
14909             then
14910                return False;
14911             end if;
14912
14913             if Expr_Value_R (Type_High_Bound (E)) <
14914                Expr_Value_R (High_Bound (Spec))
14915             then
14916                return False;
14917             end if;
14918          end if;
14919
14920          return True;
14921       end Can_Derive_From;
14922
14923    --  Start of processing for Floating_Point_Type_Declaration
14924
14925    begin
14926       Check_Restriction (No_Floating_Point, Def);
14927
14928       --  Create an implicit base type
14929
14930       Implicit_Base :=
14931         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
14932
14933       --  Analyze and verify digits value
14934
14935       Analyze_And_Resolve (Digs, Any_Integer);
14936       Check_Digits_Expression (Digs);
14937       Digs_Val := Expr_Value (Digs);
14938
14939       --  Process possible range spec and find correct type to derive from
14940
14941       Process_Real_Range_Specification (Def);
14942
14943       if Can_Derive_From (Standard_Short_Float) then
14944          Base_Typ := Standard_Short_Float;
14945       elsif Can_Derive_From (Standard_Float) then
14946          Base_Typ := Standard_Float;
14947       elsif Can_Derive_From (Standard_Long_Float) then
14948          Base_Typ := Standard_Long_Float;
14949       elsif Can_Derive_From (Standard_Long_Long_Float) then
14950          Base_Typ := Standard_Long_Long_Float;
14951
14952       --  If we can't derive from any existing type, use long_long_float
14953       --  and give appropriate message explaining the problem.
14954
14955       else
14956          Base_Typ := Standard_Long_Long_Float;
14957
14958          if Digs_Val >= Digits_Value (Standard_Long_Long_Float) then
14959             Error_Msg_Uint_1 := Digits_Value (Standard_Long_Long_Float);
14960             Error_Msg_N ("digits value out of range, maximum is ^", Digs);
14961
14962          else
14963             Error_Msg_N
14964               ("range too large for any predefined type",
14965                Real_Range_Specification (Def));
14966          end if;
14967       end if;
14968
14969       --  If there are bounds given in the declaration use them as the bounds
14970       --  of the type, otherwise use the bounds of the predefined base type
14971       --  that was chosen based on the Digits value.
14972
14973       if Present (Real_Range_Specification (Def)) then
14974          Set_Scalar_Range (T, Real_Range_Specification (Def));
14975          Set_Is_Constrained (T);
14976
14977          --  The bounds of this range must be converted to machine numbers
14978          --  in accordance with RM 4.9(38).
14979
14980          Bound := Type_Low_Bound (T);
14981
14982          if Nkind (Bound) = N_Real_Literal then
14983             Set_Realval
14984               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14985             Set_Is_Machine_Number (Bound);
14986          end if;
14987
14988          Bound := Type_High_Bound (T);
14989
14990          if Nkind (Bound) = N_Real_Literal then
14991             Set_Realval
14992               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14993             Set_Is_Machine_Number (Bound);
14994          end if;
14995
14996       else
14997          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
14998       end if;
14999
15000       --  Complete definition of implicit base and declared first subtype
15001
15002       Set_Etype          (Implicit_Base, Base_Typ);
15003
15004       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
15005       Set_Size_Info      (Implicit_Base,                (Base_Typ));
15006       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
15007       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
15008       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
15009       Set_Float_Rep      (Implicit_Base, Float_Rep      (Base_Typ));
15010
15011       Set_Ekind          (T, E_Floating_Point_Subtype);
15012       Set_Etype          (T, Implicit_Base);
15013
15014       Set_Size_Info      (T,                (Implicit_Base));
15015       Set_RM_Size        (T, RM_Size        (Implicit_Base));
15016       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
15017       Set_Digits_Value   (T, Digs_Val);
15018    end Floating_Point_Type_Declaration;
15019
15020    ----------------------------
15021    -- Get_Discriminant_Value --
15022    ----------------------------
15023
15024    --  This is the situation:
15025
15026    --  There is a non-derived type
15027
15028    --       type T0 (Dx, Dy, Dz...)
15029
15030    --  There are zero or more levels of derivation, with each derivation
15031    --  either purely inheriting the discriminants, or defining its own.
15032
15033    --       type Ti      is new Ti-1
15034    --  or
15035    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
15036    --  or
15037    --       subtype Ti is ...
15038
15039    --  The subtype issue is avoided by the use of Original_Record_Component,
15040    --  and the fact that derived subtypes also derive the constraints.
15041
15042    --  This chain leads back from
15043
15044    --       Typ_For_Constraint
15045
15046    --  Typ_For_Constraint has discriminants, and the value for each
15047    --  discriminant is given by its corresponding Elmt of Constraints.
15048
15049    --  Discriminant is some discriminant in this hierarchy
15050
15051    --  We need to return its value
15052
15053    --  We do this by recursively searching each level, and looking for
15054    --  Discriminant. Once we get to the bottom, we start backing up
15055    --  returning the value for it which may in turn be a discriminant
15056    --  further up, so on the backup we continue the substitution.
15057
15058    function Get_Discriminant_Value
15059      (Discriminant       : Entity_Id;
15060       Typ_For_Constraint : Entity_Id;
15061       Constraint         : Elist_Id) return Node_Id
15062    is
15063       function Search_Derivation_Levels
15064         (Ti                    : Entity_Id;
15065          Discrim_Values        : Elist_Id;
15066          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
15067       --  This is the routine that performs the recursive search of levels
15068       --  as described above.
15069
15070       ------------------------------
15071       -- Search_Derivation_Levels --
15072       ------------------------------
15073
15074       function Search_Derivation_Levels
15075         (Ti                    : Entity_Id;
15076          Discrim_Values        : Elist_Id;
15077          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
15078       is
15079          Assoc          : Elmt_Id;
15080          Disc           : Entity_Id;
15081          Result         : Node_Or_Entity_Id;
15082          Result_Entity  : Node_Id;
15083
15084       begin
15085          --  If inappropriate type, return Error, this happens only in
15086          --  cascaded error situations, and we want to avoid a blow up.
15087
15088          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
15089             return Error;
15090          end if;
15091
15092          --  Look deeper if possible. Use Stored_Constraints only for
15093          --  untagged types. For tagged types use the given constraint.
15094          --  This asymmetry needs explanation???
15095
15096          if not Stored_Discrim_Values
15097            and then Present (Stored_Constraint (Ti))
15098            and then not Is_Tagged_Type (Ti)
15099          then
15100             Result :=
15101               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
15102          else
15103             declare
15104                Td : constant Entity_Id := Etype (Ti);
15105
15106             begin
15107                if Td = Ti then
15108                   Result := Discriminant;
15109
15110                else
15111                   if Present (Stored_Constraint (Ti)) then
15112                      Result :=
15113                         Search_Derivation_Levels
15114                           (Td, Stored_Constraint (Ti), True);
15115                   else
15116                      Result :=
15117                         Search_Derivation_Levels
15118                           (Td, Discrim_Values, Stored_Discrim_Values);
15119                   end if;
15120                end if;
15121             end;
15122          end if;
15123
15124          --  Extra underlying places to search, if not found above. For
15125          --  concurrent types, the relevant discriminant appears in the
15126          --  corresponding record. For a type derived from a private type
15127          --  without discriminant, the full view inherits the discriminants
15128          --  of the full view of the parent.
15129
15130          if Result = Discriminant then
15131             if Is_Concurrent_Type (Ti)
15132               and then Present (Corresponding_Record_Type (Ti))
15133             then
15134                Result :=
15135                  Search_Derivation_Levels (
15136                    Corresponding_Record_Type (Ti),
15137                    Discrim_Values,
15138                    Stored_Discrim_Values);
15139
15140             elsif Is_Private_Type (Ti)
15141               and then not Has_Discriminants (Ti)
15142               and then Present (Full_View (Ti))
15143               and then Etype (Full_View (Ti)) /= Ti
15144             then
15145                Result :=
15146                  Search_Derivation_Levels (
15147                    Full_View (Ti),
15148                    Discrim_Values,
15149                    Stored_Discrim_Values);
15150             end if;
15151          end if;
15152
15153          --  If Result is not a (reference to a) discriminant, return it,
15154          --  otherwise set Result_Entity to the discriminant.
15155
15156          if Nkind (Result) = N_Defining_Identifier then
15157             pragma Assert (Result = Discriminant);
15158             Result_Entity := Result;
15159
15160          else
15161             if not Denotes_Discriminant (Result) then
15162                return Result;
15163             end if;
15164
15165             Result_Entity := Entity (Result);
15166          end if;
15167
15168          --  See if this level of derivation actually has discriminants
15169          --  because tagged derivations can add them, hence the lower
15170          --  levels need not have any.
15171
15172          if not Has_Discriminants (Ti) then
15173             return Result;
15174          end if;
15175
15176          --  Scan Ti's discriminants for Result_Entity,
15177          --  and return its corresponding value, if any.
15178
15179          Result_Entity := Original_Record_Component (Result_Entity);
15180
15181          Assoc := First_Elmt (Discrim_Values);
15182
15183          if Stored_Discrim_Values then
15184             Disc := First_Stored_Discriminant (Ti);
15185          else
15186             Disc := First_Discriminant (Ti);
15187          end if;
15188
15189          while Present (Disc) loop
15190             pragma Assert (Present (Assoc));
15191
15192             if Original_Record_Component (Disc) = Result_Entity then
15193                return Node (Assoc);
15194             end if;
15195
15196             Next_Elmt (Assoc);
15197
15198             if Stored_Discrim_Values then
15199                Next_Stored_Discriminant (Disc);
15200             else
15201                Next_Discriminant (Disc);
15202             end if;
15203          end loop;
15204
15205          --  Could not find it
15206          --
15207          return Result;
15208       end Search_Derivation_Levels;
15209
15210       --  Local Variables
15211
15212       Result : Node_Or_Entity_Id;
15213
15214    --  Start of processing for Get_Discriminant_Value
15215
15216    begin
15217       --  ??? This routine is a gigantic mess and will be deleted. For the
15218       --  time being just test for the trivial case before calling recurse.
15219
15220       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
15221          declare
15222             D : Entity_Id;
15223             E : Elmt_Id;
15224
15225          begin
15226             D := First_Discriminant (Typ_For_Constraint);
15227             E := First_Elmt (Constraint);
15228             while Present (D) loop
15229                if Chars (D) = Chars (Discriminant) then
15230                   return Node (E);
15231                end if;
15232
15233                Next_Discriminant (D);
15234                Next_Elmt (E);
15235             end loop;
15236          end;
15237       end if;
15238
15239       Result := Search_Derivation_Levels
15240         (Typ_For_Constraint, Constraint, False);
15241
15242       --  ??? hack to disappear when this routine is gone
15243
15244       if  Nkind (Result) = N_Defining_Identifier then
15245          declare
15246             D : Entity_Id;
15247             E : Elmt_Id;
15248
15249          begin
15250             D := First_Discriminant (Typ_For_Constraint);
15251             E := First_Elmt (Constraint);
15252             while Present (D) loop
15253                if Corresponding_Discriminant (D) = Discriminant then
15254                   return Node (E);
15255                end if;
15256
15257                Next_Discriminant (D);
15258                Next_Elmt (E);
15259             end loop;
15260          end;
15261       end if;
15262
15263       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
15264       return Result;
15265    end Get_Discriminant_Value;
15266
15267    --------------------------
15268    -- Has_Range_Constraint --
15269    --------------------------
15270
15271    function Has_Range_Constraint (N : Node_Id) return Boolean is
15272       C : constant Node_Id := Constraint (N);
15273
15274    begin
15275       if Nkind (C) = N_Range_Constraint then
15276          return True;
15277
15278       elsif Nkind (C) = N_Digits_Constraint then
15279          return
15280             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
15281               or else
15282             Present (Range_Constraint (C));
15283
15284       elsif Nkind (C) = N_Delta_Constraint then
15285          return Present (Range_Constraint (C));
15286
15287       else
15288          return False;
15289       end if;
15290    end Has_Range_Constraint;
15291
15292    ------------------------
15293    -- Inherit_Components --
15294    ------------------------
15295
15296    function Inherit_Components
15297      (N             : Node_Id;
15298       Parent_Base   : Entity_Id;
15299       Derived_Base  : Entity_Id;
15300       Is_Tagged     : Boolean;
15301       Inherit_Discr : Boolean;
15302       Discs         : Elist_Id) return Elist_Id
15303    is
15304       Assoc_List : constant Elist_Id := New_Elmt_List;
15305
15306       procedure Inherit_Component
15307         (Old_C          : Entity_Id;
15308          Plain_Discrim  : Boolean := False;
15309          Stored_Discrim : Boolean := False);
15310       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
15311       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
15312       --  True, Old_C is a stored discriminant. If they are both false then
15313       --  Old_C is a regular component.
15314
15315       -----------------------
15316       -- Inherit_Component --
15317       -----------------------
15318
15319       procedure Inherit_Component
15320         (Old_C          : Entity_Id;
15321          Plain_Discrim  : Boolean := False;
15322          Stored_Discrim : Boolean := False)
15323       is
15324          New_C : constant Entity_Id := New_Copy (Old_C);
15325
15326          Discrim      : Entity_Id;
15327          Corr_Discrim : Entity_Id;
15328
15329       begin
15330          pragma Assert (not Is_Tagged or else not Stored_Discrim);
15331
15332          Set_Parent (New_C, Parent (Old_C));
15333
15334          --  Regular discriminants and components must be inserted in the scope
15335          --  of the Derived_Base. Do it here.
15336
15337          if not Stored_Discrim then
15338             Enter_Name (New_C);
15339          end if;
15340
15341          --  For tagged types the Original_Record_Component must point to
15342          --  whatever this field was pointing to in the parent type. This has
15343          --  already been achieved by the call to New_Copy above.
15344
15345          if not Is_Tagged then
15346             Set_Original_Record_Component (New_C, New_C);
15347          end if;
15348
15349          --  If we have inherited a component then see if its Etype contains
15350          --  references to Parent_Base discriminants. In this case, replace
15351          --  these references with the constraints given in Discs. We do not
15352          --  do this for the partial view of private types because this is
15353          --  not needed (only the components of the full view will be used
15354          --  for code generation) and cause problem. We also avoid this
15355          --  transformation in some error situations.
15356
15357          if Ekind (New_C) = E_Component then
15358             if (Is_Private_Type (Derived_Base)
15359                  and then not Is_Generic_Type (Derived_Base))
15360               or else (Is_Empty_Elmt_List (Discs)
15361                         and then  not Expander_Active)
15362             then
15363                Set_Etype (New_C, Etype (Old_C));
15364
15365             else
15366                --  The current component introduces a circularity of the
15367                --  following kind:
15368
15369                --     limited with Pack_2;
15370                --     package Pack_1 is
15371                --        type T_1 is tagged record
15372                --           Comp : access Pack_2.T_2;
15373                --           ...
15374                --        end record;
15375                --     end Pack_1;
15376
15377                --     with Pack_1;
15378                --     package Pack_2 is
15379                --        type T_2 is new Pack_1.T_1 with ...;
15380                --     end Pack_2;
15381
15382                Set_Etype
15383                  (New_C,
15384                   Constrain_Component_Type
15385                   (Old_C, Derived_Base, N, Parent_Base, Discs));
15386             end if;
15387          end if;
15388
15389          --  In derived tagged types it is illegal to reference a non
15390          --  discriminant component in the parent type. To catch this, mark
15391          --  these components with an Ekind of E_Void. This will be reset in
15392          --  Record_Type_Definition after processing the record extension of
15393          --  the derived type.
15394
15395          --  If the declaration is a private extension, there is no further
15396          --  record extension to process, and the components retain their
15397          --  current kind, because they are visible at this point.
15398
15399          if Is_Tagged and then Ekind (New_C) = E_Component
15400            and then Nkind (N) /= N_Private_Extension_Declaration
15401          then
15402             Set_Ekind (New_C, E_Void);
15403          end if;
15404
15405          if Plain_Discrim then
15406             Set_Corresponding_Discriminant (New_C, Old_C);
15407             Build_Discriminal (New_C);
15408
15409          --  If we are explicitly inheriting a stored discriminant it will be
15410          --  completely hidden.
15411
15412          elsif Stored_Discrim then
15413             Set_Corresponding_Discriminant (New_C, Empty);
15414             Set_Discriminal (New_C, Empty);
15415             Set_Is_Completely_Hidden (New_C);
15416
15417             --  Set the Original_Record_Component of each discriminant in the
15418             --  derived base to point to the corresponding stored that we just
15419             --  created.
15420
15421             Discrim := First_Discriminant (Derived_Base);
15422             while Present (Discrim) loop
15423                Corr_Discrim := Corresponding_Discriminant (Discrim);
15424
15425                --  Corr_Discrim could be missing in an error situation
15426
15427                if Present (Corr_Discrim)
15428                  and then Original_Record_Component (Corr_Discrim) = Old_C
15429                then
15430                   Set_Original_Record_Component (Discrim, New_C);
15431                end if;
15432
15433                Next_Discriminant (Discrim);
15434             end loop;
15435
15436             Append_Entity (New_C, Derived_Base);
15437          end if;
15438
15439          if not Is_Tagged then
15440             Append_Elmt (Old_C, Assoc_List);
15441             Append_Elmt (New_C, Assoc_List);
15442          end if;
15443       end Inherit_Component;
15444
15445       --  Variables local to Inherit_Component
15446
15447       Loc : constant Source_Ptr := Sloc (N);
15448
15449       Parent_Discrim : Entity_Id;
15450       Stored_Discrim : Entity_Id;
15451       D              : Entity_Id;
15452       Component      : Entity_Id;
15453
15454    --  Start of processing for Inherit_Components
15455
15456    begin
15457       if not Is_Tagged then
15458          Append_Elmt (Parent_Base,  Assoc_List);
15459          Append_Elmt (Derived_Base, Assoc_List);
15460       end if;
15461
15462       --  Inherit parent discriminants if needed
15463
15464       if Inherit_Discr then
15465          Parent_Discrim := First_Discriminant (Parent_Base);
15466          while Present (Parent_Discrim) loop
15467             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
15468             Next_Discriminant (Parent_Discrim);
15469          end loop;
15470       end if;
15471
15472       --  Create explicit stored discrims for untagged types when necessary
15473
15474       if not Has_Unknown_Discriminants (Derived_Base)
15475         and then Has_Discriminants (Parent_Base)
15476         and then not Is_Tagged
15477         and then
15478           (not Inherit_Discr
15479              or else First_Discriminant (Parent_Base) /=
15480                      First_Stored_Discriminant (Parent_Base))
15481       then
15482          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
15483          while Present (Stored_Discrim) loop
15484             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
15485             Next_Stored_Discriminant (Stored_Discrim);
15486          end loop;
15487       end if;
15488
15489       --  See if we can apply the second transformation for derived types, as
15490       --  explained in point 6. in the comments above Build_Derived_Record_Type
15491       --  This is achieved by appending Derived_Base discriminants into Discs,
15492       --  which has the side effect of returning a non empty Discs list to the
15493       --  caller of Inherit_Components, which is what we want. This must be
15494       --  done for private derived types if there are explicit stored
15495       --  discriminants, to ensure that we can retrieve the values of the
15496       --  constraints provided in the ancestors.
15497
15498       if Inherit_Discr
15499         and then Is_Empty_Elmt_List (Discs)
15500         and then Present (First_Discriminant (Derived_Base))
15501         and then
15502           (not Is_Private_Type (Derived_Base)
15503              or else Is_Completely_Hidden
15504                (First_Stored_Discriminant (Derived_Base))
15505              or else Is_Generic_Type (Derived_Base))
15506       then
15507          D := First_Discriminant (Derived_Base);
15508          while Present (D) loop
15509             Append_Elmt (New_Reference_To (D, Loc), Discs);
15510             Next_Discriminant (D);
15511          end loop;
15512       end if;
15513
15514       --  Finally, inherit non-discriminant components unless they are not
15515       --  visible because defined or inherited from the full view of the
15516       --  parent. Don't inherit the _parent field of the parent type.
15517
15518       Component := First_Entity (Parent_Base);
15519       while Present (Component) loop
15520
15521          --  Ada 2005 (AI-251): Do not inherit components associated with
15522          --  secondary tags of the parent.
15523
15524          if Ekind (Component) = E_Component
15525            and then Present (Related_Type (Component))
15526          then
15527             null;
15528
15529          elsif Ekind (Component) /= E_Component
15530            or else Chars (Component) = Name_uParent
15531          then
15532             null;
15533
15534          --  If the derived type is within the parent type's declarative
15535          --  region, then the components can still be inherited even though
15536          --  they aren't visible at this point. This can occur for cases
15537          --  such as within public child units where the components must
15538          --  become visible upon entering the child unit's private part.
15539
15540          elsif not Is_Visible_Component (Component)
15541            and then not In_Open_Scopes (Scope (Parent_Base))
15542          then
15543             null;
15544
15545          elsif Ekind_In (Derived_Base, E_Private_Type,
15546                                        E_Limited_Private_Type)
15547          then
15548             null;
15549
15550          else
15551             Inherit_Component (Component);
15552          end if;
15553
15554          Next_Entity (Component);
15555       end loop;
15556
15557       --  For tagged derived types, inherited discriminants cannot be used in
15558       --  component declarations of the record extension part. To achieve this
15559       --  we mark the inherited discriminants as not visible.
15560
15561       if Is_Tagged and then Inherit_Discr then
15562          D := First_Discriminant (Derived_Base);
15563          while Present (D) loop
15564             Set_Is_Immediately_Visible (D, False);
15565             Next_Discriminant (D);
15566          end loop;
15567       end if;
15568
15569       return Assoc_List;
15570    end Inherit_Components;
15571
15572    -----------------------
15573    -- Is_Constant_Bound --
15574    -----------------------
15575
15576    function Is_Constant_Bound (Exp : Node_Id) return Boolean is
15577    begin
15578       if Compile_Time_Known_Value (Exp) then
15579          return True;
15580
15581       elsif Is_Entity_Name (Exp)
15582         and then Present (Entity (Exp))
15583       then
15584          return Is_Constant_Object (Entity (Exp))
15585            or else Ekind (Entity (Exp)) = E_Enumeration_Literal;
15586
15587       elsif Nkind (Exp) in N_Binary_Op then
15588          return Is_Constant_Bound (Left_Opnd (Exp))
15589            and then Is_Constant_Bound (Right_Opnd (Exp))
15590            and then Scope (Entity (Exp)) = Standard_Standard;
15591
15592       else
15593          return False;
15594       end if;
15595    end Is_Constant_Bound;
15596
15597    -----------------------
15598    -- Is_Null_Extension --
15599    -----------------------
15600
15601    function Is_Null_Extension (T : Entity_Id) return Boolean is
15602       Type_Decl : constant Node_Id := Parent (Base_Type (T));
15603       Comp_List : Node_Id;
15604       Comp      : Node_Id;
15605
15606    begin
15607       if Nkind (Type_Decl) /= N_Full_Type_Declaration
15608         or else not Is_Tagged_Type (T)
15609         or else Nkind (Type_Definition (Type_Decl)) /=
15610                                               N_Derived_Type_Definition
15611         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
15612       then
15613          return False;
15614       end if;
15615
15616       Comp_List :=
15617         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
15618
15619       if Present (Discriminant_Specifications (Type_Decl)) then
15620          return False;
15621
15622       elsif Present (Comp_List)
15623         and then Is_Non_Empty_List (Component_Items (Comp_List))
15624       then
15625          Comp := First (Component_Items (Comp_List));
15626
15627          --  Only user-defined components are relevant. The component list
15628          --  may also contain a parent component and internal components
15629          --  corresponding to secondary tags, but these do not determine
15630          --  whether this is a null extension.
15631
15632          while Present (Comp) loop
15633             if Comes_From_Source (Comp) then
15634                return False;
15635             end if;
15636
15637             Next (Comp);
15638          end loop;
15639
15640          return True;
15641       else
15642          return True;
15643       end if;
15644    end Is_Null_Extension;
15645
15646    ------------------------------
15647    -- Is_Valid_Constraint_Kind --
15648    ------------------------------
15649
15650    function Is_Valid_Constraint_Kind
15651      (T_Kind          : Type_Kind;
15652       Constraint_Kind : Node_Kind) return Boolean
15653    is
15654    begin
15655       case T_Kind is
15656          when Enumeration_Kind |
15657               Integer_Kind =>
15658             return Constraint_Kind = N_Range_Constraint;
15659
15660          when Decimal_Fixed_Point_Kind =>
15661             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
15662                                               N_Range_Constraint);
15663
15664          when Ordinary_Fixed_Point_Kind =>
15665             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
15666                                               N_Range_Constraint);
15667
15668          when Float_Kind =>
15669             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
15670                                               N_Range_Constraint);
15671
15672          when Access_Kind       |
15673               Array_Kind        |
15674               E_Record_Type     |
15675               E_Record_Subtype  |
15676               Class_Wide_Kind   |
15677               E_Incomplete_Type |
15678               Private_Kind      |
15679               Concurrent_Kind  =>
15680             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
15681
15682          when others =>
15683             return True; -- Error will be detected later
15684       end case;
15685    end Is_Valid_Constraint_Kind;
15686
15687    --------------------------
15688    -- Is_Visible_Component --
15689    --------------------------
15690
15691    function Is_Visible_Component (C : Entity_Id) return Boolean is
15692       Original_Comp  : Entity_Id := Empty;
15693       Original_Scope : Entity_Id;
15694       Type_Scope     : Entity_Id;
15695
15696       function Is_Local_Type (Typ : Entity_Id) return Boolean;
15697       --  Check whether parent type of inherited component is declared locally,
15698       --  possibly within a nested package or instance. The current scope is
15699       --  the derived record itself.
15700
15701       -------------------
15702       -- Is_Local_Type --
15703       -------------------
15704
15705       function Is_Local_Type (Typ : Entity_Id) return Boolean is
15706          Scop : Entity_Id;
15707
15708       begin
15709          Scop := Scope (Typ);
15710          while Present (Scop)
15711            and then Scop /= Standard_Standard
15712          loop
15713             if Scop = Scope (Current_Scope) then
15714                return True;
15715             end if;
15716
15717             Scop := Scope (Scop);
15718          end loop;
15719
15720          return False;
15721       end Is_Local_Type;
15722
15723    --  Start of processing for Is_Visible_Component
15724
15725    begin
15726       if Ekind_In (C, E_Component, E_Discriminant) then
15727          Original_Comp := Original_Record_Component (C);
15728       end if;
15729
15730       if No (Original_Comp) then
15731
15732          --  Premature usage, or previous error
15733
15734          return False;
15735
15736       else
15737          Original_Scope := Scope (Original_Comp);
15738          Type_Scope     := Scope (Base_Type (Scope (C)));
15739       end if;
15740
15741       --  This test only concerns tagged types
15742
15743       if not Is_Tagged_Type (Original_Scope) then
15744          return True;
15745
15746       --  If it is _Parent or _Tag, there is no visibility issue
15747
15748       elsif not Comes_From_Source (Original_Comp) then
15749          return True;
15750
15751       --  If we are in the body of an instantiation, the component is visible
15752       --  even when the parent type (possibly defined in an enclosing unit or
15753       --  in a parent unit) might not.
15754
15755       elsif In_Instance_Body then
15756          return True;
15757
15758       --  Discriminants are always visible
15759
15760       elsif Ekind (Original_Comp) = E_Discriminant
15761         and then not Has_Unknown_Discriminants (Original_Scope)
15762       then
15763          return True;
15764
15765       --  If the component has been declared in an ancestor which is currently
15766       --  a private type, then it is not visible. The same applies if the
15767       --  component's containing type is not in an open scope and the original
15768       --  component's enclosing type is a visible full view of a private type
15769       --  (which can occur in cases where an attempt is being made to reference
15770       --  a component in a sibling package that is inherited from a visible
15771       --  component of a type in an ancestor package; the component in the
15772       --  sibling package should not be visible even though the component it
15773       --  inherited from is visible). This does not apply however in the case
15774       --  where the scope of the type is a private child unit, or when the
15775       --  parent comes from a local package in which the ancestor is currently
15776       --  visible. The latter suppression of visibility is needed for cases
15777       --  that are tested in B730006.
15778
15779       elsif Is_Private_Type (Original_Scope)
15780         or else
15781           (not Is_Private_Descendant (Type_Scope)
15782             and then not In_Open_Scopes (Type_Scope)
15783             and then Has_Private_Declaration (Original_Scope))
15784       then
15785          --  If the type derives from an entity in a formal package, there
15786          --  are no additional visible components.
15787
15788          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
15789             N_Formal_Package_Declaration
15790          then
15791             return False;
15792
15793          --  if we are not in the private part of the current package, there
15794          --  are no additional visible components.
15795
15796          elsif Ekind (Scope (Current_Scope)) = E_Package
15797            and then not In_Private_Part (Scope (Current_Scope))
15798          then
15799             return False;
15800          else
15801             return
15802               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
15803                 and then In_Open_Scopes (Scope (Original_Scope))
15804                 and then Is_Local_Type (Type_Scope);
15805          end if;
15806
15807       --  There is another weird way in which a component may be invisible
15808       --  when the private and the full view are not derived from the same
15809       --  ancestor. Here is an example :
15810
15811       --       type A1 is tagged      record F1 : integer; end record;
15812       --       type A2 is new A1 with record F2 : integer; end record;
15813       --       type T is new A1 with private;
15814       --     private
15815       --       type T is new A2 with null record;
15816
15817       --  In this case, the full view of T inherits F1 and F2 but the private
15818       --  view inherits only F1
15819
15820       else
15821          declare
15822             Ancestor : Entity_Id := Scope (C);
15823
15824          begin
15825             loop
15826                if Ancestor = Original_Scope then
15827                   return True;
15828                elsif Ancestor = Etype (Ancestor) then
15829                   return False;
15830                end if;
15831
15832                Ancestor := Etype (Ancestor);
15833             end loop;
15834          end;
15835       end if;
15836    end Is_Visible_Component;
15837
15838    --------------------------
15839    -- Make_Class_Wide_Type --
15840    --------------------------
15841
15842    procedure Make_Class_Wide_Type (T : Entity_Id) is
15843       CW_Type : Entity_Id;
15844       CW_Name : Name_Id;
15845       Next_E  : Entity_Id;
15846
15847    begin
15848       --  The class wide type can have been defined by the partial view, in
15849       --  which case everything is already done.
15850
15851       if Present (Class_Wide_Type (T)) then
15852          return;
15853       end if;
15854
15855       CW_Type :=
15856         New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
15857
15858       --  Inherit root type characteristics
15859
15860       CW_Name := Chars (CW_Type);
15861       Next_E  := Next_Entity (CW_Type);
15862       Copy_Node (T, CW_Type);
15863       Set_Comes_From_Source (CW_Type, False);
15864       Set_Chars (CW_Type, CW_Name);
15865       Set_Parent (CW_Type, Parent (T));
15866       Set_Next_Entity (CW_Type, Next_E);
15867
15868       --  Ensure we have a new freeze node for the class-wide type. The partial
15869       --  view may have freeze action of its own, requiring a proper freeze
15870       --  node, and the same freeze node cannot be shared between the two
15871       --  types.
15872
15873       Set_Has_Delayed_Freeze (CW_Type);
15874       Set_Freeze_Node (CW_Type, Empty);
15875
15876       --  Customize the class-wide type: It has no prim. op., it cannot be
15877       --  abstract and its Etype points back to the specific root type.
15878
15879       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
15880       Set_Is_Tagged_Type              (CW_Type, True);
15881       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
15882       Set_Is_Abstract_Type            (CW_Type, False);
15883       Set_Is_Constrained              (CW_Type, False);
15884       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
15885
15886       if Ekind (T) = E_Class_Wide_Subtype then
15887          Set_Etype             (CW_Type, Etype (Base_Type (T)));
15888       else
15889          Set_Etype             (CW_Type, T);
15890       end if;
15891
15892       --  If this is the class_wide type of a constrained subtype, it does
15893       --  not have discriminants.
15894
15895       Set_Has_Discriminants (CW_Type,
15896         Has_Discriminants (T) and then not Is_Constrained (T));
15897
15898       Set_Has_Unknown_Discriminants (CW_Type, True);
15899       Set_Class_Wide_Type (T, CW_Type);
15900       Set_Equivalent_Type (CW_Type, Empty);
15901
15902       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
15903
15904       Set_Class_Wide_Type (CW_Type, CW_Type);
15905    end Make_Class_Wide_Type;
15906
15907    ----------------
15908    -- Make_Index --
15909    ----------------
15910
15911    procedure Make_Index
15912      (I            : Node_Id;
15913       Related_Nod  : Node_Id;
15914       Related_Id   : Entity_Id := Empty;
15915       Suffix_Index : Nat := 1)
15916    is
15917       R      : Node_Id;
15918       T      : Entity_Id;
15919       Def_Id : Entity_Id := Empty;
15920       Found  : Boolean := False;
15921
15922    begin
15923       --  For a discrete range used in a constrained array definition and
15924       --  defined by a range, an implicit conversion to the predefined type
15925       --  INTEGER is assumed if each bound is either a numeric literal, a named
15926       --  number, or an attribute, and the type of both bounds (prior to the
15927       --  implicit conversion) is the type universal_integer. Otherwise, both
15928       --  bounds must be of the same discrete type, other than universal
15929       --  integer; this type must be determinable independently of the
15930       --  context, but using the fact that the type must be discrete and that
15931       --  both bounds must have the same type.
15932
15933       --  Character literals also have a universal type in the absence of
15934       --  of additional context,  and are resolved to Standard_Character.
15935
15936       if Nkind (I) = N_Range then
15937
15938          --  The index is given by a range constraint. The bounds are known
15939          --  to be of a consistent type.
15940
15941          if not Is_Overloaded (I) then
15942             T := Etype (I);
15943
15944             --  For universal bounds, choose the specific predefined type
15945
15946             if T = Universal_Integer then
15947                T := Standard_Integer;
15948
15949             elsif T = Any_Character then
15950                Ambiguous_Character (Low_Bound (I));
15951
15952                T := Standard_Character;
15953             end if;
15954
15955          --  The node may be overloaded because some user-defined operators
15956          --  are available, but if a universal interpretation exists it is
15957          --  also the selected one.
15958
15959          elsif Universal_Interpretation (I) = Universal_Integer then
15960             T := Standard_Integer;
15961
15962          else
15963             T := Any_Type;
15964
15965             declare
15966                Ind : Interp_Index;
15967                It  : Interp;
15968
15969             begin
15970                Get_First_Interp (I, Ind, It);
15971                while Present (It.Typ) loop
15972                   if Is_Discrete_Type (It.Typ) then
15973
15974                      if Found
15975                        and then not Covers (It.Typ, T)
15976                        and then not Covers (T, It.Typ)
15977                      then
15978                         Error_Msg_N ("ambiguous bounds in discrete range", I);
15979                         exit;
15980                      else
15981                         T := It.Typ;
15982                         Found := True;
15983                      end if;
15984                   end if;
15985
15986                   Get_Next_Interp (Ind, It);
15987                end loop;
15988
15989                if T = Any_Type then
15990                   Error_Msg_N ("discrete type required for range", I);
15991                   Set_Etype (I, Any_Type);
15992                   return;
15993
15994                elsif T = Universal_Integer then
15995                   T := Standard_Integer;
15996                end if;
15997             end;
15998          end if;
15999
16000          if not Is_Discrete_Type (T) then
16001             Error_Msg_N ("discrete type required for range", I);
16002             Set_Etype (I, Any_Type);
16003             return;
16004          end if;
16005
16006          if Nkind (Low_Bound (I)) = N_Attribute_Reference
16007            and then Attribute_Name (Low_Bound (I)) = Name_First
16008            and then Is_Entity_Name (Prefix (Low_Bound (I)))
16009            and then Is_Type (Entity (Prefix (Low_Bound (I))))
16010            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
16011          then
16012             --  The type of the index will be the type of the prefix, as long
16013             --  as the upper bound is 'Last of the same type.
16014
16015             Def_Id := Entity (Prefix (Low_Bound (I)));
16016
16017             if Nkind (High_Bound (I)) /= N_Attribute_Reference
16018               or else Attribute_Name (High_Bound (I)) /= Name_Last
16019               or else not Is_Entity_Name (Prefix (High_Bound (I)))
16020               or else Entity (Prefix (High_Bound (I))) /= Def_Id
16021             then
16022                Def_Id := Empty;
16023             end if;
16024          end if;
16025
16026          R := I;
16027          Process_Range_Expr_In_Decl (R, T);
16028
16029       elsif Nkind (I) = N_Subtype_Indication then
16030
16031          --  The index is given by a subtype with a range constraint
16032
16033          T :=  Base_Type (Entity (Subtype_Mark (I)));
16034
16035          if not Is_Discrete_Type (T) then
16036             Error_Msg_N ("discrete type required for range", I);
16037             Set_Etype (I, Any_Type);
16038             return;
16039          end if;
16040
16041          R := Range_Expression (Constraint (I));
16042
16043          Resolve (R, T);
16044          Process_Range_Expr_In_Decl (R, Entity (Subtype_Mark (I)));
16045
16046       elsif Nkind (I) = N_Attribute_Reference then
16047
16048          --  The parser guarantees that the attribute is a RANGE attribute
16049
16050          --  If the node denotes the range of a type mark, that is also the
16051          --  resulting type, and we do no need to create an Itype for it.
16052
16053          if Is_Entity_Name (Prefix (I))
16054            and then Comes_From_Source (I)
16055            and then Is_Type (Entity (Prefix (I)))
16056            and then Is_Discrete_Type (Entity (Prefix (I)))
16057          then
16058             Def_Id := Entity (Prefix (I));
16059          end if;
16060
16061          Analyze_And_Resolve (I);
16062          T := Etype (I);
16063          R := I;
16064
16065       --  If none of the above, must be a subtype. We convert this to a
16066       --  range attribute reference because in the case of declared first
16067       --  named subtypes, the types in the range reference can be different
16068       --  from the type of the entity. A range attribute normalizes the
16069       --  reference and obtains the correct types for the bounds.
16070
16071       --  This transformation is in the nature of an expansion, is only
16072       --  done if expansion is active. In particular, it is not done on
16073       --  formal generic types,  because we need to retain the name of the
16074       --  original index for instantiation purposes.
16075
16076       else
16077          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
16078             Error_Msg_N ("invalid subtype mark in discrete range ", I);
16079             Set_Etype (I, Any_Integer);
16080             return;
16081
16082          else
16083             --  The type mark may be that of an incomplete type. It is only
16084             --  now that we can get the full view, previous analysis does
16085             --  not look specifically for a type mark.
16086
16087             Set_Entity (I, Get_Full_View (Entity (I)));
16088             Set_Etype  (I, Entity (I));
16089             Def_Id := Entity (I);
16090
16091             if not Is_Discrete_Type (Def_Id) then
16092                Error_Msg_N ("discrete type required for index", I);
16093                Set_Etype (I, Any_Type);
16094                return;
16095             end if;
16096          end if;
16097
16098          if Expander_Active then
16099             Rewrite (I,
16100               Make_Attribute_Reference (Sloc (I),
16101                 Attribute_Name => Name_Range,
16102                 Prefix         => Relocate_Node (I)));
16103
16104             --  The original was a subtype mark that does not freeze. This
16105             --  means that the rewritten version must not freeze either.
16106
16107             Set_Must_Not_Freeze (I);
16108             Set_Must_Not_Freeze (Prefix (I));
16109
16110             --  Is order critical??? if so, document why, if not
16111             --  use Analyze_And_Resolve
16112
16113             Analyze_And_Resolve (I);
16114             T := Etype (I);
16115             R := I;
16116
16117          --  If expander is inactive, type is legal, nothing else to construct
16118
16119          else
16120             return;
16121          end if;
16122       end if;
16123
16124       if not Is_Discrete_Type (T) then
16125          Error_Msg_N ("discrete type required for range", I);
16126          Set_Etype (I, Any_Type);
16127          return;
16128
16129       elsif T = Any_Type then
16130          Set_Etype (I, Any_Type);
16131          return;
16132       end if;
16133
16134       --  We will now create the appropriate Itype to describe the range, but
16135       --  first a check. If we originally had a subtype, then we just label
16136       --  the range with this subtype. Not only is there no need to construct
16137       --  a new subtype, but it is wrong to do so for two reasons:
16138
16139       --    1. A legality concern, if we have a subtype, it must not freeze,
16140       --       and the Itype would cause freezing incorrectly
16141
16142       --    2. An efficiency concern, if we created an Itype, it would not be
16143       --       recognized as the same type for the purposes of eliminating
16144       --       checks in some circumstances.
16145
16146       --  We signal this case by setting the subtype entity in Def_Id
16147
16148       if No (Def_Id) then
16149          Def_Id :=
16150            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
16151          Set_Etype (Def_Id, Base_Type (T));
16152
16153          if Is_Signed_Integer_Type (T) then
16154             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
16155
16156          elsif Is_Modular_Integer_Type (T) then
16157             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
16158
16159          else
16160             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
16161             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
16162             Set_First_Literal     (Def_Id, First_Literal (T));
16163          end if;
16164
16165          Set_Size_Info      (Def_Id,                  (T));
16166          Set_RM_Size        (Def_Id, RM_Size          (T));
16167          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
16168
16169          Set_Scalar_Range   (Def_Id, R);
16170          Conditional_Delay  (Def_Id, T);
16171
16172          --  In the subtype indication case, if the immediate parent of the
16173          --  new subtype is non-static, then the subtype we create is non-
16174          --  static, even if its bounds are static.
16175
16176          if Nkind (I) = N_Subtype_Indication
16177            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
16178          then
16179             Set_Is_Non_Static_Subtype (Def_Id);
16180          end if;
16181       end if;
16182
16183       --  Final step is to label the index with this constructed type
16184
16185       Set_Etype (I, Def_Id);
16186    end Make_Index;
16187
16188    ------------------------------
16189    -- Modular_Type_Declaration --
16190    ------------------------------
16191
16192    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16193       Mod_Expr : constant Node_Id := Expression (Def);
16194       M_Val    : Uint;
16195
16196       procedure Set_Modular_Size (Bits : Int);
16197       --  Sets RM_Size to Bits, and Esize to normal word size above this
16198
16199       ----------------------
16200       -- Set_Modular_Size --
16201       ----------------------
16202
16203       procedure Set_Modular_Size (Bits : Int) is
16204       begin
16205          Set_RM_Size (T, UI_From_Int (Bits));
16206
16207          if Bits <= 8 then
16208             Init_Esize (T, 8);
16209
16210          elsif Bits <= 16 then
16211             Init_Esize (T, 16);
16212
16213          elsif Bits <= 32 then
16214             Init_Esize (T, 32);
16215
16216          else
16217             Init_Esize (T, System_Max_Binary_Modulus_Power);
16218          end if;
16219
16220          if not Non_Binary_Modulus (T)
16221            and then Esize (T) = RM_Size (T)
16222          then
16223             Set_Is_Known_Valid (T);
16224          end if;
16225       end Set_Modular_Size;
16226
16227    --  Start of processing for Modular_Type_Declaration
16228
16229    begin
16230       Analyze_And_Resolve (Mod_Expr, Any_Integer);
16231       Set_Etype (T, T);
16232       Set_Ekind (T, E_Modular_Integer_Type);
16233       Init_Alignment (T);
16234       Set_Is_Constrained (T);
16235
16236       if not Is_OK_Static_Expression (Mod_Expr) then
16237          Flag_Non_Static_Expr
16238            ("non-static expression used for modular type bound!", Mod_Expr);
16239          M_Val := 2 ** System_Max_Binary_Modulus_Power;
16240       else
16241          M_Val := Expr_Value (Mod_Expr);
16242       end if;
16243
16244       if M_Val < 1 then
16245          Error_Msg_N ("modulus value must be positive", Mod_Expr);
16246          M_Val := 2 ** System_Max_Binary_Modulus_Power;
16247       end if;
16248
16249       Set_Modulus (T, M_Val);
16250
16251       --   Create bounds for the modular type based on the modulus given in
16252       --   the type declaration and then analyze and resolve those bounds.
16253
16254       Set_Scalar_Range (T,
16255         Make_Range (Sloc (Mod_Expr),
16256           Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
16257           High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
16258
16259       --  Properly analyze the literals for the range. We do this manually
16260       --  because we can't go calling Resolve, since we are resolving these
16261       --  bounds with the type, and this type is certainly not complete yet!
16262
16263       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
16264       Set_Etype (High_Bound (Scalar_Range (T)), T);
16265       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
16266       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
16267
16268       --  Loop through powers of two to find number of bits required
16269
16270       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
16271
16272          --  Binary case
16273
16274          if M_Val = 2 ** Bits then
16275             Set_Modular_Size (Bits);
16276             return;
16277
16278          --  Non-binary case
16279
16280          elsif M_Val < 2 ** Bits then
16281             Set_Non_Binary_Modulus (T);
16282
16283             if Bits > System_Max_Nonbinary_Modulus_Power then
16284                Error_Msg_Uint_1 :=
16285                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
16286                Error_Msg_F
16287                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
16288                Set_Modular_Size (System_Max_Binary_Modulus_Power);
16289                return;
16290
16291             else
16292                --  In the non-binary case, set size as per RM 13.3(55)
16293
16294                Set_Modular_Size (Bits);
16295                return;
16296             end if;
16297          end if;
16298
16299       end loop;
16300
16301       --  If we fall through, then the size exceed System.Max_Binary_Modulus
16302       --  so we just signal an error and set the maximum size.
16303
16304       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
16305       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
16306
16307       Set_Modular_Size (System_Max_Binary_Modulus_Power);
16308       Init_Alignment (T);
16309
16310    end Modular_Type_Declaration;
16311
16312    --------------------------
16313    -- New_Concatenation_Op --
16314    --------------------------
16315
16316    procedure New_Concatenation_Op (Typ : Entity_Id) is
16317       Loc : constant Source_Ptr := Sloc (Typ);
16318       Op  : Entity_Id;
16319
16320       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
16321       --  Create abbreviated declaration for the formal of a predefined
16322       --  Operator 'Op' of type 'Typ'
16323
16324       --------------------
16325       -- Make_Op_Formal --
16326       --------------------
16327
16328       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
16329          Formal : Entity_Id;
16330       begin
16331          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
16332          Set_Etype (Formal, Typ);
16333          Set_Mechanism (Formal, Default_Mechanism);
16334          return Formal;
16335       end Make_Op_Formal;
16336
16337    --  Start of processing for New_Concatenation_Op
16338
16339    begin
16340       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
16341
16342       Set_Ekind                   (Op, E_Operator);
16343       Set_Scope                   (Op, Current_Scope);
16344       Set_Etype                   (Op, Typ);
16345       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
16346       Set_Is_Immediately_Visible  (Op);
16347       Set_Is_Intrinsic_Subprogram (Op);
16348       Set_Has_Completion          (Op);
16349       Append_Entity               (Op, Current_Scope);
16350
16351       Set_Name_Entity_Id (Name_Op_Concat, Op);
16352
16353       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16354       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16355    end New_Concatenation_Op;
16356
16357    -------------------------
16358    -- OK_For_Limited_Init --
16359    -------------------------
16360
16361    --  ???Check all calls of this, and compare the conditions under which it's
16362    --  called.
16363
16364    function OK_For_Limited_Init
16365      (Typ : Entity_Id;
16366       Exp : Node_Id) return Boolean
16367    is
16368    begin
16369       return Is_CPP_Constructor_Call (Exp)
16370         or else (Ada_Version >= Ada_2005
16371                   and then not Debug_Flag_Dot_L
16372                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
16373    end OK_For_Limited_Init;
16374
16375    -------------------------------
16376    -- OK_For_Limited_Init_In_05 --
16377    -------------------------------
16378
16379    function OK_For_Limited_Init_In_05
16380      (Typ : Entity_Id;
16381       Exp : Node_Id) return Boolean
16382    is
16383    begin
16384       --  An object of a limited interface type can be initialized with any
16385       --  expression of a nonlimited descendant type.
16386
16387       if Is_Class_Wide_Type (Typ)
16388         and then Is_Limited_Interface (Typ)
16389         and then not Is_Limited_Type (Etype (Exp))
16390       then
16391          return True;
16392       end if;
16393
16394       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
16395       --  case of limited aggregates (including extension aggregates), and
16396       --  function calls. The function call may have been given in prefixed
16397       --  notation, in which case the original node is an indexed component.
16398       --  If the function is parameterless, the original node was an explicit
16399       --  dereference.
16400
16401       case Nkind (Original_Node (Exp)) is
16402          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
16403             return True;
16404
16405          when N_Qualified_Expression =>
16406             return
16407               OK_For_Limited_Init_In_05
16408                 (Typ, Expression (Original_Node (Exp)));
16409
16410          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
16411          --  with a function call, the expander has rewritten the call into an
16412          --  N_Type_Conversion node to force displacement of the pointer to
16413          --  reference the component containing the secondary dispatch table.
16414          --  Otherwise a type conversion is not a legal context.
16415          --  A return statement for a build-in-place function returning a
16416          --  synchronized type also introduces an unchecked conversion.
16417
16418          when N_Type_Conversion           |
16419               N_Unchecked_Type_Conversion =>
16420             return not Comes_From_Source (Exp)
16421               and then
16422                 OK_For_Limited_Init_In_05
16423                   (Typ, Expression (Original_Node (Exp)));
16424
16425          when N_Indexed_Component     |
16426               N_Selected_Component    |
16427               N_Explicit_Dereference  =>
16428             return Nkind (Exp) = N_Function_Call;
16429
16430          --  A use of 'Input is a function call, hence allowed. Normally the
16431          --  attribute will be changed to a call, but the attribute by itself
16432          --  can occur with -gnatc.
16433
16434          when N_Attribute_Reference =>
16435             return Attribute_Name (Original_Node (Exp)) = Name_Input;
16436
16437          when others =>
16438             return False;
16439       end case;
16440    end OK_For_Limited_Init_In_05;
16441
16442    -------------------------------------------
16443    -- Ordinary_Fixed_Point_Type_Declaration --
16444    -------------------------------------------
16445
16446    procedure Ordinary_Fixed_Point_Type_Declaration
16447      (T   : Entity_Id;
16448       Def : Node_Id)
16449    is
16450       Loc           : constant Source_Ptr := Sloc (Def);
16451       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
16452       RRS           : constant Node_Id    := Real_Range_Specification (Def);
16453       Implicit_Base : Entity_Id;
16454       Delta_Val     : Ureal;
16455       Small_Val     : Ureal;
16456       Low_Val       : Ureal;
16457       High_Val      : Ureal;
16458
16459    begin
16460       Check_Restriction (No_Fixed_Point, Def);
16461
16462       --  Create implicit base type
16463
16464       Implicit_Base :=
16465         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
16466       Set_Etype (Implicit_Base, Implicit_Base);
16467
16468       --  Analyze and process delta expression
16469
16470       Analyze_And_Resolve (Delta_Expr, Any_Real);
16471
16472       Check_Delta_Expression (Delta_Expr);
16473       Delta_Val := Expr_Value_R (Delta_Expr);
16474
16475       Set_Delta_Value (Implicit_Base, Delta_Val);
16476
16477       --  Compute default small from given delta, which is the largest power
16478       --  of two that does not exceed the given delta value.
16479
16480       declare
16481          Tmp   : Ureal;
16482          Scale : Int;
16483
16484       begin
16485          Tmp := Ureal_1;
16486          Scale := 0;
16487
16488          if Delta_Val < Ureal_1 then
16489             while Delta_Val < Tmp loop
16490                Tmp := Tmp / Ureal_2;
16491                Scale := Scale + 1;
16492             end loop;
16493
16494          else
16495             loop
16496                Tmp := Tmp * Ureal_2;
16497                exit when Tmp > Delta_Val;
16498                Scale := Scale - 1;
16499             end loop;
16500          end if;
16501
16502          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
16503       end;
16504
16505       Set_Small_Value (Implicit_Base, Small_Val);
16506
16507       --  If no range was given, set a dummy range
16508
16509       if RRS <= Empty_Or_Error then
16510          Low_Val  := -Small_Val;
16511          High_Val := Small_Val;
16512
16513       --  Otherwise analyze and process given range
16514
16515       else
16516          declare
16517             Low  : constant Node_Id := Low_Bound  (RRS);
16518             High : constant Node_Id := High_Bound (RRS);
16519
16520          begin
16521             Analyze_And_Resolve (Low, Any_Real);
16522             Analyze_And_Resolve (High, Any_Real);
16523             Check_Real_Bound (Low);
16524             Check_Real_Bound (High);
16525
16526             --  Obtain and set the range
16527
16528             Low_Val  := Expr_Value_R (Low);
16529             High_Val := Expr_Value_R (High);
16530
16531             if Low_Val > High_Val then
16532                Error_Msg_NE ("?fixed point type& has null range", Def, T);
16533             end if;
16534          end;
16535       end if;
16536
16537       --  The range for both the implicit base and the declared first subtype
16538       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
16539       --  set a temporary range in place. Note that the bounds of the base
16540       --  type will be widened to be symmetrical and to fill the available
16541       --  bits when the type is frozen.
16542
16543       --  We could do this with all discrete types, and probably should, but
16544       --  we absolutely have to do it for fixed-point, since the end-points
16545       --  of the range and the size are determined by the small value, which
16546       --  could be reset before the freeze point.
16547
16548       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
16549       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
16550
16551       --  Complete definition of first subtype
16552
16553       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
16554       Set_Etype          (T, Implicit_Base);
16555       Init_Size_Align    (T);
16556       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
16557       Set_Small_Value    (T, Small_Val);
16558       Set_Delta_Value    (T, Delta_Val);
16559       Set_Is_Constrained (T);
16560
16561    end Ordinary_Fixed_Point_Type_Declaration;
16562
16563    ----------------------------------------
16564    -- Prepare_Private_Subtype_Completion --
16565    ----------------------------------------
16566
16567    procedure Prepare_Private_Subtype_Completion
16568      (Id          : Entity_Id;
16569       Related_Nod : Node_Id)
16570    is
16571       Id_B   : constant Entity_Id := Base_Type (Id);
16572       Full_B : constant Entity_Id := Full_View (Id_B);
16573       Full   : Entity_Id;
16574
16575    begin
16576       if Present (Full_B) then
16577
16578          --  The Base_Type is already completed, we can complete the subtype
16579          --  now. We have to create a new entity with the same name, Thus we
16580          --  can't use Create_Itype.
16581
16582          --  This is messy, should be fixed ???
16583
16584          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
16585          Set_Is_Itype (Full);
16586          Set_Associated_Node_For_Itype (Full, Related_Nod);
16587          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
16588       end if;
16589
16590       --  The parent subtype may be private, but the base might not, in some
16591       --  nested instances. In that case, the subtype does not need to be
16592       --  exchanged. It would still be nice to make private subtypes and their
16593       --  bases consistent at all times ???
16594
16595       if Is_Private_Type (Id_B) then
16596          Append_Elmt (Id, Private_Dependents (Id_B));
16597       end if;
16598
16599    end Prepare_Private_Subtype_Completion;
16600
16601    ---------------------------
16602    -- Process_Discriminants --
16603    ---------------------------
16604
16605    procedure Process_Discriminants
16606      (N    : Node_Id;
16607       Prev : Entity_Id := Empty)
16608    is
16609       Elist               : constant Elist_Id := New_Elmt_List;
16610       Id                  : Node_Id;
16611       Discr               : Node_Id;
16612       Discr_Number        : Uint;
16613       Discr_Type          : Entity_Id;
16614       Default_Present     : Boolean := False;
16615       Default_Not_Present : Boolean := False;
16616
16617    begin
16618       --  A composite type other than an array type can have discriminants.
16619       --  On entry, the current scope is the composite type.
16620
16621       --  The discriminants are initially entered into the scope of the type
16622       --  via Enter_Name with the default Ekind of E_Void to prevent premature
16623       --  use, as explained at the end of this procedure.
16624
16625       Discr := First (Discriminant_Specifications (N));
16626       while Present (Discr) loop
16627          Enter_Name (Defining_Identifier (Discr));
16628
16629          --  For navigation purposes we add a reference to the discriminant
16630          --  in the entity for the type. If the current declaration is a
16631          --  completion, place references on the partial view. Otherwise the
16632          --  type is the current scope.
16633
16634          if Present (Prev) then
16635
16636             --  The references go on the partial view, if present. If the
16637             --  partial view has discriminants, the references have been
16638             --  generated already.
16639
16640             if not Has_Discriminants (Prev) then
16641                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
16642             end if;
16643          else
16644             Generate_Reference
16645               (Current_Scope, Defining_Identifier (Discr), 'd');
16646          end if;
16647
16648          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
16649             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
16650
16651             --  Ada 2005 (AI-254)
16652
16653             if Present (Access_To_Subprogram_Definition
16654                          (Discriminant_Type (Discr)))
16655               and then Protected_Present (Access_To_Subprogram_Definition
16656                                            (Discriminant_Type (Discr)))
16657             then
16658                Discr_Type :=
16659                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
16660             end if;
16661
16662          else
16663             Find_Type (Discriminant_Type (Discr));
16664             Discr_Type := Etype (Discriminant_Type (Discr));
16665
16666             if Error_Posted (Discriminant_Type (Discr)) then
16667                Discr_Type := Any_Type;
16668             end if;
16669          end if;
16670
16671          if Is_Access_Type (Discr_Type) then
16672
16673             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
16674             --  record types
16675
16676             if Ada_Version < Ada_2005 then
16677                Check_Access_Discriminant_Requires_Limited
16678                  (Discr, Discriminant_Type (Discr));
16679             end if;
16680
16681             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
16682                Error_Msg_N
16683                  ("(Ada 83) access discriminant not allowed", Discr);
16684             end if;
16685
16686          elsif not Is_Discrete_Type (Discr_Type) then
16687             Error_Msg_N ("discriminants must have a discrete or access type",
16688               Discriminant_Type (Discr));
16689          end if;
16690
16691          Set_Etype (Defining_Identifier (Discr), Discr_Type);
16692
16693          --  If a discriminant specification includes the assignment compound
16694          --  delimiter followed by an expression, the expression is the default
16695          --  expression of the discriminant; the default expression must be of
16696          --  the type of the discriminant. (RM 3.7.1) Since this expression is
16697          --  a default expression, we do the special preanalysis, since this
16698          --  expression does not freeze (see "Handling of Default and Per-
16699          --  Object Expressions" in spec of package Sem).
16700
16701          if Present (Expression (Discr)) then
16702             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
16703
16704             if Nkind (N) = N_Formal_Type_Declaration then
16705                Error_Msg_N
16706                  ("discriminant defaults not allowed for formal type",
16707                   Expression (Discr));
16708
16709             --  Flag an error for a tagged type with defaulted discriminants,
16710             --  excluding limited tagged types when compiling for Ada 2012
16711             --  (see AI05-0214).
16712
16713             elsif Is_Tagged_Type (Current_Scope)
16714               and then (not Is_Limited_Type (Current_Scope)
16715                          or else Ada_Version < Ada_2012)
16716               and then Comes_From_Source (N)
16717             then
16718                --  Note: see similar test in Check_Or_Process_Discriminants, to
16719                --  handle the (illegal) case of the completion of an untagged
16720                --  view with discriminants with defaults by a tagged full view.
16721                --  We skip the check if Discr does not come from source, to
16722                --  account for the case of an untagged derived type providing
16723                --  defaults for a renamed discriminant from a private untagged
16724                --  ancestor with a tagged full view (ACATS B460006).
16725
16726                if Ada_Version >= Ada_2012 then
16727                   Error_Msg_N
16728                     ("discriminants of nonlimited tagged type cannot have"
16729                        & " defaults",
16730                      Expression (Discr));
16731                else
16732                   Error_Msg_N
16733                     ("discriminants of tagged type cannot have defaults",
16734                      Expression (Discr));
16735                end if;
16736
16737             else
16738                Default_Present := True;
16739                Append_Elmt (Expression (Discr), Elist);
16740
16741                --  Tag the defining identifiers for the discriminants with
16742                --  their corresponding default expressions from the tree.
16743
16744                Set_Discriminant_Default_Value
16745                  (Defining_Identifier (Discr), Expression (Discr));
16746             end if;
16747
16748          else
16749             Default_Not_Present := True;
16750          end if;
16751
16752          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
16753          --  Discr_Type but with the null-exclusion attribute
16754
16755          if Ada_Version >= Ada_2005 then
16756
16757             --  Ada 2005 (AI-231): Static checks
16758
16759             if Can_Never_Be_Null (Discr_Type) then
16760                Null_Exclusion_Static_Checks (Discr);
16761
16762             elsif Is_Access_Type (Discr_Type)
16763               and then Null_Exclusion_Present (Discr)
16764
16765                --  No need to check itypes because in their case this check
16766                --  was done at their point of creation
16767
16768               and then not Is_Itype (Discr_Type)
16769             then
16770                if Can_Never_Be_Null (Discr_Type) then
16771                   Error_Msg_NE
16772                     ("`NOT NULL` not allowed (& already excludes null)",
16773                      Discr,
16774                      Discr_Type);
16775                end if;
16776
16777                Set_Etype (Defining_Identifier (Discr),
16778                  Create_Null_Excluding_Itype
16779                    (T           => Discr_Type,
16780                     Related_Nod => Discr));
16781
16782             --  Check for improper null exclusion if the type is otherwise
16783             --  legal for a discriminant.
16784
16785             elsif Null_Exclusion_Present (Discr)
16786               and then Is_Discrete_Type (Discr_Type)
16787             then
16788                Error_Msg_N
16789                  ("null exclusion can only apply to an access type", Discr);
16790             end if;
16791
16792             --  Ada 2005 (AI-402): access discriminants of nonlimited types
16793             --  can't have defaults. Synchronized types, or types that are
16794             --  explicitly limited are fine, but special tests apply to derived
16795             --  types in generics: in a generic body we have to assume the
16796             --  worst, and therefore defaults are not allowed if the parent is
16797             --  a generic formal private type (see ACATS B370001).
16798
16799             if Is_Access_Type (Discr_Type) then
16800                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
16801                  or else not Default_Present
16802                  or else Is_Limited_Record (Current_Scope)
16803                  or else Is_Concurrent_Type (Current_Scope)
16804                  or else Is_Concurrent_Record_Type (Current_Scope)
16805                  or else Ekind (Current_Scope) = E_Limited_Private_Type
16806                then
16807                   if not Is_Derived_Type (Current_Scope)
16808                     or else not Is_Generic_Type (Etype (Current_Scope))
16809                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
16810                     or else Limited_Present
16811                               (Type_Definition (Parent (Current_Scope)))
16812                   then
16813                      null;
16814
16815                   else
16816                      Error_Msg_N ("access discriminants of nonlimited types",
16817                          Expression (Discr));
16818                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
16819                   end if;
16820
16821                elsif Present (Expression (Discr)) then
16822                   Error_Msg_N
16823                     ("(Ada 2005) access discriminants of nonlimited types",
16824                      Expression (Discr));
16825                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
16826                end if;
16827             end if;
16828          end if;
16829
16830          Next (Discr);
16831       end loop;
16832
16833       --  An element list consisting of the default expressions of the
16834       --  discriminants is constructed in the above loop and used to set
16835       --  the Discriminant_Constraint attribute for the type. If an object
16836       --  is declared of this (record or task) type without any explicit
16837       --  discriminant constraint given, this element list will form the
16838       --  actual parameters for the corresponding initialization procedure
16839       --  for the type.
16840
16841       Set_Discriminant_Constraint (Current_Scope, Elist);
16842       Set_Stored_Constraint (Current_Scope, No_Elist);
16843
16844       --  Default expressions must be provided either for all or for none
16845       --  of the discriminants of a discriminant part. (RM 3.7.1)
16846
16847       if Default_Present and then Default_Not_Present then
16848          Error_Msg_N
16849            ("incomplete specification of defaults for discriminants", N);
16850       end if;
16851
16852       --  The use of the name of a discriminant is not allowed in default
16853       --  expressions of a discriminant part if the specification of the
16854       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
16855
16856       --  To detect this, the discriminant names are entered initially with an
16857       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
16858       --  attempt to use a void entity (for example in an expression that is
16859       --  type-checked) produces the error message: premature usage. Now after
16860       --  completing the semantic analysis of the discriminant part, we can set
16861       --  the Ekind of all the discriminants appropriately.
16862
16863       Discr := First (Discriminant_Specifications (N));
16864       Discr_Number := Uint_1;
16865       while Present (Discr) loop
16866          Id := Defining_Identifier (Discr);
16867          Set_Ekind (Id, E_Discriminant);
16868          Init_Component_Location (Id);
16869          Init_Esize (Id);
16870          Set_Discriminant_Number (Id, Discr_Number);
16871
16872          --  Make sure this is always set, even in illegal programs
16873
16874          Set_Corresponding_Discriminant (Id, Empty);
16875
16876          --  Initialize the Original_Record_Component to the entity itself.
16877          --  Inherit_Components will propagate the right value to
16878          --  discriminants in derived record types.
16879
16880          Set_Original_Record_Component (Id, Id);
16881
16882          --  Create the discriminal for the discriminant
16883
16884          Build_Discriminal (Id);
16885
16886          Next (Discr);
16887          Discr_Number := Discr_Number + 1;
16888       end loop;
16889
16890       Set_Has_Discriminants (Current_Scope);
16891    end Process_Discriminants;
16892
16893    -----------------------
16894    -- Process_Full_View --
16895    -----------------------
16896
16897    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
16898       Priv_Parent : Entity_Id;
16899       Full_Parent : Entity_Id;
16900       Full_Indic  : Node_Id;
16901
16902       procedure Collect_Implemented_Interfaces
16903         (Typ    : Entity_Id;
16904          Ifaces : Elist_Id);
16905       --  Ada 2005: Gather all the interfaces that Typ directly or
16906       --  inherently implements. Duplicate entries are not added to
16907       --  the list Ifaces.
16908
16909       ------------------------------------
16910       -- Collect_Implemented_Interfaces --
16911       ------------------------------------
16912
16913       procedure Collect_Implemented_Interfaces
16914         (Typ    : Entity_Id;
16915          Ifaces : Elist_Id)
16916       is
16917          Iface      : Entity_Id;
16918          Iface_Elmt : Elmt_Id;
16919
16920       begin
16921          --  Abstract interfaces are only associated with tagged record types
16922
16923          if not Is_Tagged_Type (Typ)
16924            or else not Is_Record_Type (Typ)
16925          then
16926             return;
16927          end if;
16928
16929          --  Recursively climb to the ancestors
16930
16931          if Etype (Typ) /= Typ
16932
16933             --  Protect the frontend against wrong cyclic declarations like:
16934
16935             --     type B is new A with private;
16936             --     type C is new A with private;
16937             --  private
16938             --     type B is new C with null record;
16939             --     type C is new B with null record;
16940
16941            and then Etype (Typ) /= Priv_T
16942            and then Etype (Typ) /= Full_T
16943          then
16944             --  Keep separate the management of private type declarations
16945
16946             if Ekind (Typ) = E_Record_Type_With_Private then
16947
16948                --  Handle the following erroneous case:
16949                --      type Private_Type is tagged private;
16950                --   private
16951                --      type Private_Type is new Type_Implementing_Iface;
16952
16953                if Present (Full_View (Typ))
16954                  and then Etype (Typ) /= Full_View (Typ)
16955                then
16956                   if Is_Interface (Etype (Typ)) then
16957                      Append_Unique_Elmt (Etype (Typ), Ifaces);
16958                   end if;
16959
16960                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16961                end if;
16962
16963             --  Non-private types
16964
16965             else
16966                if Is_Interface (Etype (Typ)) then
16967                   Append_Unique_Elmt (Etype (Typ), Ifaces);
16968                end if;
16969
16970                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16971             end if;
16972          end if;
16973
16974          --  Handle entities in the list of abstract interfaces
16975
16976          if Present (Interfaces (Typ)) then
16977             Iface_Elmt := First_Elmt (Interfaces (Typ));
16978             while Present (Iface_Elmt) loop
16979                Iface := Node (Iface_Elmt);
16980
16981                pragma Assert (Is_Interface (Iface));
16982
16983                if not Contain_Interface (Iface, Ifaces) then
16984                   Append_Elmt (Iface, Ifaces);
16985                   Collect_Implemented_Interfaces (Iface, Ifaces);
16986                end if;
16987
16988                Next_Elmt (Iface_Elmt);
16989             end loop;
16990          end if;
16991       end Collect_Implemented_Interfaces;
16992
16993    --  Start of processing for Process_Full_View
16994
16995    begin
16996       --  First some sanity checks that must be done after semantic
16997       --  decoration of the full view and thus cannot be placed with other
16998       --  similar checks in Find_Type_Name
16999
17000       if not Is_Limited_Type (Priv_T)
17001         and then (Is_Limited_Type (Full_T)
17002                    or else Is_Limited_Composite (Full_T))
17003       then
17004          Error_Msg_N
17005            ("completion of nonlimited type cannot be limited", Full_T);
17006          Explain_Limited_Type (Full_T, Full_T);
17007
17008       elsif Is_Abstract_Type (Full_T)
17009         and then not Is_Abstract_Type (Priv_T)
17010       then
17011          Error_Msg_N
17012            ("completion of nonabstract type cannot be abstract", Full_T);
17013
17014       elsif Is_Tagged_Type (Priv_T)
17015         and then Is_Limited_Type (Priv_T)
17016         and then not Is_Limited_Type (Full_T)
17017       then
17018          --  If pragma CPP_Class was applied to the private declaration
17019          --  propagate the limitedness to the full-view
17020
17021          if Is_CPP_Class (Priv_T) then
17022             Set_Is_Limited_Record (Full_T);
17023
17024          --  GNAT allow its own definition of Limited_Controlled to disobey
17025          --  this rule in order in ease the implementation. The next test is
17026          --  safe because Root_Controlled is defined in a private system child
17027
17028          elsif Etype (Full_T) = Full_View (RTE (RE_Root_Controlled)) then
17029             Set_Is_Limited_Composite (Full_T);
17030          else
17031             Error_Msg_N
17032               ("completion of limited tagged type must be limited", Full_T);
17033          end if;
17034
17035       elsif Is_Generic_Type (Priv_T) then
17036          Error_Msg_N ("generic type cannot have a completion", Full_T);
17037       end if;
17038
17039       --  Check that ancestor interfaces of private and full views are
17040       --  consistent. We omit this check for synchronized types because
17041       --  they are performed on the corresponding record type when frozen.
17042
17043       if Ada_Version >= Ada_2005
17044         and then Is_Tagged_Type (Priv_T)
17045         and then Is_Tagged_Type (Full_T)
17046         and then not Is_Concurrent_Type (Full_T)
17047       then
17048          declare
17049             Iface         : Entity_Id;
17050             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
17051             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
17052
17053          begin
17054             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
17055             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
17056
17057             --  Ada 2005 (AI-251): The partial view shall be a descendant of
17058             --  an interface type if and only if the full type is descendant
17059             --  of the interface type (AARM 7.3 (7.3/2).
17060
17061             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
17062
17063             if Present (Iface) then
17064                Error_Msg_NE
17065                  ("interface & not implemented by full type " &
17066                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
17067             end if;
17068
17069             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
17070
17071             if Present (Iface) then
17072                Error_Msg_NE
17073                  ("interface & not implemented by partial view " &
17074                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
17075             end if;
17076          end;
17077       end if;
17078
17079       if Is_Tagged_Type (Priv_T)
17080         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17081         and then Is_Derived_Type (Full_T)
17082       then
17083          Priv_Parent := Etype (Priv_T);
17084
17085          --  The full view of a private extension may have been transformed
17086          --  into an unconstrained derived type declaration and a subtype
17087          --  declaration (see build_derived_record_type for details).
17088
17089          if Nkind (N) = N_Subtype_Declaration then
17090             Full_Indic  := Subtype_Indication (N);
17091             Full_Parent := Etype (Base_Type (Full_T));
17092          else
17093             Full_Indic  := Subtype_Indication (Type_Definition (N));
17094             Full_Parent := Etype (Full_T);
17095          end if;
17096
17097          --  Check that the parent type of the full type is a descendant of
17098          --  the ancestor subtype given in the private extension. If either
17099          --  entity has an Etype equal to Any_Type then we had some previous
17100          --  error situation [7.3(8)].
17101
17102          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
17103             return;
17104
17105          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
17106          --  any order. Therefore we don't have to check that its parent must
17107          --  be a descendant of the parent of the private type declaration.
17108
17109          elsif Is_Interface (Priv_Parent)
17110            and then Is_Interface (Full_Parent)
17111          then
17112             null;
17113
17114          --  Ada 2005 (AI-251): If the parent of the private type declaration
17115          --  is an interface there is no need to check that it is an ancestor
17116          --  of the associated full type declaration. The required tests for
17117          --  this case are performed by Build_Derived_Record_Type.
17118
17119          elsif not Is_Interface (Base_Type (Priv_Parent))
17120            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
17121          then
17122             Error_Msg_N
17123               ("parent of full type must descend from parent"
17124                   & " of private extension", Full_Indic);
17125
17126          --  Check the rules of 7.3(10): if the private extension inherits
17127          --  known discriminants, then the full type must also inherit those
17128          --  discriminants from the same (ancestor) type, and the parent
17129          --  subtype of the full type must be constrained if and only if
17130          --  the ancestor subtype of the private extension is constrained.
17131
17132          elsif No (Discriminant_Specifications (Parent (Priv_T)))
17133            and then not Has_Unknown_Discriminants (Priv_T)
17134            and then Has_Discriminants (Base_Type (Priv_Parent))
17135          then
17136             declare
17137                Priv_Indic  : constant Node_Id :=
17138                                Subtype_Indication (Parent (Priv_T));
17139
17140                Priv_Constr : constant Boolean :=
17141                                Is_Constrained (Priv_Parent)
17142                                  or else
17143                                    Nkind (Priv_Indic) = N_Subtype_Indication
17144                                  or else Is_Constrained (Entity (Priv_Indic));
17145
17146                Full_Constr : constant Boolean :=
17147                                Is_Constrained (Full_Parent)
17148                                  or else
17149                                    Nkind (Full_Indic) = N_Subtype_Indication
17150                                  or else Is_Constrained (Entity (Full_Indic));
17151
17152                Priv_Discr : Entity_Id;
17153                Full_Discr : Entity_Id;
17154
17155             begin
17156                Priv_Discr := First_Discriminant (Priv_Parent);
17157                Full_Discr := First_Discriminant (Full_Parent);
17158                while Present (Priv_Discr) and then Present (Full_Discr) loop
17159                   if Original_Record_Component (Priv_Discr) =
17160                      Original_Record_Component (Full_Discr)
17161                     or else
17162                      Corresponding_Discriminant (Priv_Discr) =
17163                      Corresponding_Discriminant (Full_Discr)
17164                   then
17165                      null;
17166                   else
17167                      exit;
17168                   end if;
17169
17170                   Next_Discriminant (Priv_Discr);
17171                   Next_Discriminant (Full_Discr);
17172                end loop;
17173
17174                if Present (Priv_Discr) or else Present (Full_Discr) then
17175                   Error_Msg_N
17176                     ("full view must inherit discriminants of the parent type"
17177                      & " used in the private extension", Full_Indic);
17178
17179                elsif Priv_Constr and then not Full_Constr then
17180                   Error_Msg_N
17181                     ("parent subtype of full type must be constrained",
17182                      Full_Indic);
17183
17184                elsif Full_Constr and then not Priv_Constr then
17185                   Error_Msg_N
17186                     ("parent subtype of full type must be unconstrained",
17187                      Full_Indic);
17188                end if;
17189             end;
17190
17191          --  Check the rules of 7.3(12): if a partial view has neither known
17192          --  or unknown discriminants, then the full type declaration shall
17193          --  define a definite subtype.
17194
17195          elsif      not Has_Unknown_Discriminants (Priv_T)
17196            and then not Has_Discriminants (Priv_T)
17197            and then not Is_Constrained (Full_T)
17198          then
17199             Error_Msg_N
17200               ("full view must define a constrained type if partial view"
17201                 & " has no discriminants", Full_T);
17202          end if;
17203
17204          --  ??????? Do we implement the following properly ?????
17205          --  If the ancestor subtype of a private extension has constrained
17206          --  discriminants, then the parent subtype of the full view shall
17207          --  impose a statically matching constraint on those discriminants
17208          --  [7.3(13)].
17209
17210       else
17211          --  For untagged types, verify that a type without discriminants
17212          --  is not completed with an unconstrained type.
17213
17214          if not Is_Indefinite_Subtype (Priv_T)
17215            and then Is_Indefinite_Subtype (Full_T)
17216          then
17217             Error_Msg_N ("full view of type must be definite subtype", Full_T);
17218          end if;
17219       end if;
17220
17221       --  AI-419: verify that the use of "limited" is consistent
17222
17223       declare
17224          Orig_Decl : constant Node_Id := Original_Node (N);
17225
17226       begin
17227          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17228            and then not Limited_Present (Parent (Priv_T))
17229            and then not Synchronized_Present (Parent (Priv_T))
17230            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
17231            and then Nkind
17232              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
17233            and then Limited_Present (Type_Definition (Orig_Decl))
17234          then
17235             Error_Msg_N
17236               ("full view of non-limited extension cannot be limited", N);
17237          end if;
17238       end;
17239
17240       --  Ada 2005 (AI-443): A synchronized private extension must be
17241       --  completed by a task or protected type.
17242
17243       if Ada_Version >= Ada_2005
17244         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17245         and then Synchronized_Present (Parent (Priv_T))
17246         and then not Is_Concurrent_Type (Full_T)
17247       then
17248          Error_Msg_N ("full view of synchronized extension must " &
17249                       "be synchronized type", N);
17250       end if;
17251
17252       --  Ada 2005 AI-363: if the full view has discriminants with
17253       --  defaults, it is illegal to declare constrained access subtypes
17254       --  whose designated type is the current type. This allows objects
17255       --  of the type that are declared in the heap to be unconstrained.
17256
17257       if not Has_Unknown_Discriminants (Priv_T)
17258         and then not Has_Discriminants (Priv_T)
17259         and then Has_Discriminants (Full_T)
17260         and then
17261           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
17262       then
17263          Set_Has_Constrained_Partial_View (Full_T);
17264          Set_Has_Constrained_Partial_View (Priv_T);
17265       end if;
17266
17267       --  Create a full declaration for all its subtypes recorded in
17268       --  Private_Dependents and swap them similarly to the base type. These
17269       --  are subtypes that have been define before the full declaration of
17270       --  the private type. We also swap the entry in Private_Dependents list
17271       --  so we can properly restore the private view on exit from the scope.
17272
17273       declare
17274          Priv_Elmt : Elmt_Id;
17275          Priv      : Entity_Id;
17276          Full      : Entity_Id;
17277
17278       begin
17279          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
17280          while Present (Priv_Elmt) loop
17281             Priv := Node (Priv_Elmt);
17282
17283             if Ekind_In (Priv, E_Private_Subtype,
17284                                E_Limited_Private_Subtype,
17285                                E_Record_Subtype_With_Private)
17286             then
17287                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
17288                Set_Is_Itype (Full);
17289                Set_Parent (Full, Parent (Priv));
17290                Set_Associated_Node_For_Itype (Full, N);
17291
17292                --  Now we need to complete the private subtype, but since the
17293                --  base type has already been swapped, we must also swap the
17294                --  subtypes (and thus, reverse the arguments in the call to
17295                --  Complete_Private_Subtype).
17296
17297                Copy_And_Swap (Priv, Full);
17298                Complete_Private_Subtype (Full, Priv, Full_T, N);
17299                Replace_Elmt (Priv_Elmt, Full);
17300             end if;
17301
17302             Next_Elmt (Priv_Elmt);
17303          end loop;
17304       end;
17305
17306       --  If the private view was tagged, copy the new primitive operations
17307       --  from the private view to the full view.
17308
17309       if Is_Tagged_Type (Full_T) then
17310          declare
17311             Disp_Typ  : Entity_Id;
17312             Full_List : Elist_Id;
17313             Prim      : Entity_Id;
17314             Prim_Elmt : Elmt_Id;
17315             Priv_List : Elist_Id;
17316
17317             function Contains
17318               (E : Entity_Id;
17319                L : Elist_Id) return Boolean;
17320             --  Determine whether list L contains element E
17321
17322             --------------
17323             -- Contains --
17324             --------------
17325
17326             function Contains
17327               (E : Entity_Id;
17328                L : Elist_Id) return Boolean
17329             is
17330                List_Elmt : Elmt_Id;
17331
17332             begin
17333                List_Elmt := First_Elmt (L);
17334                while Present (List_Elmt) loop
17335                   if Node (List_Elmt) = E then
17336                      return True;
17337                   end if;
17338
17339                   Next_Elmt (List_Elmt);
17340                end loop;
17341
17342                return False;
17343             end Contains;
17344
17345          --  Start of processing
17346
17347          begin
17348             if Is_Tagged_Type (Priv_T) then
17349                Priv_List := Primitive_Operations (Priv_T);
17350                Prim_Elmt := First_Elmt (Priv_List);
17351
17352                --  In the case of a concurrent type completing a private tagged
17353                --  type, primitives may have been declared in between the two
17354                --  views. These subprograms need to be wrapped the same way
17355                --  entries and protected procedures are handled because they
17356                --  cannot be directly shared by the two views.
17357
17358                if Is_Concurrent_Type (Full_T) then
17359                   declare
17360                      Conc_Typ  : constant Entity_Id :=
17361                                    Corresponding_Record_Type (Full_T);
17362                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
17363                      Wrap_Spec : Node_Id;
17364
17365                   begin
17366                      while Present (Prim_Elmt) loop
17367                         Prim := Node (Prim_Elmt);
17368
17369                         if Comes_From_Source (Prim)
17370                           and then not Is_Abstract_Subprogram (Prim)
17371                         then
17372                            Wrap_Spec :=
17373                              Make_Subprogram_Declaration (Sloc (Prim),
17374                                Specification =>
17375                                  Build_Wrapper_Spec
17376                                    (Subp_Id => Prim,
17377                                     Obj_Typ => Conc_Typ,
17378                                     Formals =>
17379                                       Parameter_Specifications (
17380                                         Parent (Prim))));
17381
17382                            Insert_After (Curr_Nod, Wrap_Spec);
17383                            Curr_Nod := Wrap_Spec;
17384
17385                            Analyze (Wrap_Spec);
17386                         end if;
17387
17388                         Next_Elmt (Prim_Elmt);
17389                      end loop;
17390
17391                      return;
17392                   end;
17393
17394                --  For non-concurrent types, transfer explicit primitives, but
17395                --  omit those inherited from the parent of the private view
17396                --  since they will be re-inherited later on.
17397
17398                else
17399                   Full_List := Primitive_Operations (Full_T);
17400
17401                   while Present (Prim_Elmt) loop
17402                      Prim := Node (Prim_Elmt);
17403
17404                      if Comes_From_Source (Prim)
17405                        and then not Contains (Prim, Full_List)
17406                      then
17407                         Append_Elmt (Prim, Full_List);
17408                      end if;
17409
17410                      Next_Elmt (Prim_Elmt);
17411                   end loop;
17412                end if;
17413
17414             --  Untagged private view
17415
17416             else
17417                Full_List := Primitive_Operations (Full_T);
17418
17419                --  In this case the partial view is untagged, so here we locate
17420                --  all of the earlier primitives that need to be treated as
17421                --  dispatching (those that appear between the two views). Note
17422                --  that these additional operations must all be new operations
17423                --  (any earlier operations that override inherited operations
17424                --  of the full view will already have been inserted in the
17425                --  primitives list, marked by Check_Operation_From_Private_View
17426                --  as dispatching. Note that implicit "/=" operators are
17427                --  excluded from being added to the primitives list since they
17428                --  shouldn't be treated as dispatching (tagged "/=" is handled
17429                --  specially).
17430
17431                Prim := Next_Entity (Full_T);
17432                while Present (Prim) and then Prim /= Priv_T loop
17433                   if Ekind_In (Prim, E_Procedure, E_Function) then
17434                      Disp_Typ := Find_Dispatching_Type (Prim);
17435
17436                      if Disp_Typ = Full_T
17437                        and then (Chars (Prim) /= Name_Op_Ne
17438                                   or else Comes_From_Source (Prim))
17439                      then
17440                         Check_Controlling_Formals (Full_T, Prim);
17441
17442                         if not Is_Dispatching_Operation (Prim) then
17443                            Append_Elmt (Prim, Full_List);
17444                            Set_Is_Dispatching_Operation (Prim, True);
17445                            Set_DT_Position (Prim, No_Uint);
17446                         end if;
17447
17448                      elsif Is_Dispatching_Operation (Prim)
17449                        and then Disp_Typ  /= Full_T
17450                      then
17451
17452                         --  Verify that it is not otherwise controlled by a
17453                         --  formal or a return value of type T.
17454
17455                         Check_Controlling_Formals (Disp_Typ, Prim);
17456                      end if;
17457                   end if;
17458
17459                   Next_Entity (Prim);
17460                end loop;
17461             end if;
17462
17463             --  For the tagged case, the two views can share the same primitive
17464             --  operations list and the same class-wide type. Update attributes
17465             --  of the class-wide type which depend on the full declaration.
17466
17467             if Is_Tagged_Type (Priv_T) then
17468                Set_Direct_Primitive_Operations (Priv_T, Full_List);
17469                Set_Class_Wide_Type
17470                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
17471
17472                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
17473             end if;
17474          end;
17475       end if;
17476
17477       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
17478
17479       if Known_To_Have_Preelab_Init (Priv_T) then
17480
17481          --  Case where there is a pragma Preelaborable_Initialization. We
17482          --  always allow this in predefined units, which is a bit of a kludge,
17483          --  but it means we don't have to struggle to meet the requirements in
17484          --  the RM for having Preelaborable Initialization. Otherwise we
17485          --  require that the type meets the RM rules. But we can't check that
17486          --  yet, because of the rule about overriding Initialize, so we simply
17487          --  set a flag that will be checked at freeze time.
17488
17489          if not In_Predefined_Unit (Full_T) then
17490             Set_Must_Have_Preelab_Init (Full_T);
17491          end if;
17492       end if;
17493
17494       --  If pragma CPP_Class was applied to the private type declaration,
17495       --  propagate it now to the full type declaration.
17496
17497       if Is_CPP_Class (Priv_T) then
17498          Set_Is_CPP_Class (Full_T);
17499          Set_Convention   (Full_T, Convention_CPP);
17500       end if;
17501
17502       --  If the private view has user specified stream attributes, then so has
17503       --  the full view.
17504
17505       --  Why the test, how could these flags be already set in Full_T ???
17506
17507       if Has_Specified_Stream_Read (Priv_T) then
17508          Set_Has_Specified_Stream_Read (Full_T);
17509       end if;
17510
17511       if Has_Specified_Stream_Write (Priv_T) then
17512          Set_Has_Specified_Stream_Write (Full_T);
17513       end if;
17514
17515       if Has_Specified_Stream_Input (Priv_T) then
17516          Set_Has_Specified_Stream_Input (Full_T);
17517       end if;
17518
17519       if Has_Specified_Stream_Output (Priv_T) then
17520          Set_Has_Specified_Stream_Output (Full_T);
17521       end if;
17522
17523       --  Propagate invariants to full type
17524
17525       if Has_Invariants (Priv_T) then
17526          Set_Has_Invariants (Full_T);
17527          Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
17528       end if;
17529
17530       if Has_Inheritable_Invariants (Priv_T) then
17531          Set_Has_Inheritable_Invariants (Full_T);
17532       end if;
17533
17534       --  Propagate predicates to full type
17535
17536       if Has_Predicates (Priv_T) then
17537          Set_Predicate_Function (Priv_T, Predicate_Function (Full_T));
17538          Set_Has_Predicates (Priv_T);
17539       end if;
17540    end Process_Full_View;
17541
17542    -----------------------------------
17543    -- Process_Incomplete_Dependents --
17544    -----------------------------------
17545
17546    procedure Process_Incomplete_Dependents
17547      (N      : Node_Id;
17548       Full_T : Entity_Id;
17549       Inc_T  : Entity_Id)
17550    is
17551       Inc_Elmt : Elmt_Id;
17552       Priv_Dep : Entity_Id;
17553       New_Subt : Entity_Id;
17554
17555       Disc_Constraint : Elist_Id;
17556
17557    begin
17558       if No (Private_Dependents (Inc_T)) then
17559          return;
17560       end if;
17561
17562       --  Itypes that may be generated by the completion of an incomplete
17563       --  subtype are not used by the back-end and not attached to the tree.
17564       --  They are created only for constraint-checking purposes.
17565
17566       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
17567       while Present (Inc_Elmt) loop
17568          Priv_Dep := Node (Inc_Elmt);
17569
17570          if Ekind (Priv_Dep) = E_Subprogram_Type then
17571
17572             --  An Access_To_Subprogram type may have a return type or a
17573             --  parameter type that is incomplete. Replace with the full view.
17574
17575             if Etype (Priv_Dep) = Inc_T then
17576                Set_Etype (Priv_Dep, Full_T);
17577             end if;
17578
17579             declare
17580                Formal : Entity_Id;
17581
17582             begin
17583                Formal := First_Formal (Priv_Dep);
17584                while Present (Formal) loop
17585                   if Etype (Formal) = Inc_T then
17586                      Set_Etype (Formal, Full_T);
17587                   end if;
17588
17589                   Next_Formal (Formal);
17590                end loop;
17591             end;
17592
17593          elsif Is_Overloadable (Priv_Dep) then
17594
17595             --  A protected operation is never dispatching: only its
17596             --  wrapper operation (which has convention Ada) is.
17597
17598             if Is_Tagged_Type (Full_T)
17599               and then Convention (Priv_Dep) /= Convention_Protected
17600             then
17601
17602                --  Subprogram has an access parameter whose designated type
17603                --  was incomplete. Reexamine declaration now, because it may
17604                --  be a primitive operation of the full type.
17605
17606                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
17607                Set_Is_Dispatching_Operation (Priv_Dep);
17608                Check_Controlling_Formals (Full_T, Priv_Dep);
17609             end if;
17610
17611          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
17612
17613             --  Can happen during processing of a body before the completion
17614             --  of a TA type. Ignore, because spec is also on dependent list.
17615
17616             return;
17617
17618          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
17619          --  corresponding subtype of the full view.
17620
17621          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
17622             Set_Subtype_Indication
17623               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
17624             Set_Etype (Priv_Dep, Full_T);
17625             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
17626             Set_Analyzed (Parent (Priv_Dep), False);
17627
17628             --  Reanalyze the declaration, suppressing the call to
17629             --  Enter_Name to avoid duplicate names.
17630
17631             Analyze_Subtype_Declaration
17632               (N    => Parent (Priv_Dep),
17633                Skip => True);
17634
17635          --  Dependent is a subtype
17636
17637          else
17638             --  We build a new subtype indication using the full view of the
17639             --  incomplete parent. The discriminant constraints have been
17640             --  elaborated already at the point of the subtype declaration.
17641
17642             New_Subt := Create_Itype (E_Void, N);
17643
17644             if Has_Discriminants (Full_T) then
17645                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
17646             else
17647                Disc_Constraint := No_Elist;
17648             end if;
17649
17650             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
17651             Set_Full_View (Priv_Dep, New_Subt);
17652          end if;
17653
17654          Next_Elmt (Inc_Elmt);
17655       end loop;
17656    end Process_Incomplete_Dependents;
17657
17658    --------------------------------
17659    -- Process_Range_Expr_In_Decl --
17660    --------------------------------
17661
17662    procedure Process_Range_Expr_In_Decl
17663      (R           : Node_Id;
17664       T           : Entity_Id;
17665       Check_List  : List_Id := Empty_List;
17666       R_Check_Off : Boolean := False)
17667    is
17668       Lo, Hi      : Node_Id;
17669       R_Checks    : Check_Result;
17670       Insert_Node : Node_Id;
17671       Def_Id      : Entity_Id;
17672
17673    begin
17674       Analyze_And_Resolve (R, Base_Type (T));
17675
17676       if Nkind (R) = N_Range then
17677          Lo := Low_Bound (R);
17678          Hi := High_Bound (R);
17679
17680          --  We need to ensure validity of the bounds here, because if we
17681          --  go ahead and do the expansion, then the expanded code will get
17682          --  analyzed with range checks suppressed and we miss the check.
17683
17684          Validity_Check_Range (R);
17685
17686          --  If there were errors in the declaration, try and patch up some
17687          --  common mistakes in the bounds. The cases handled are literals
17688          --  which are Integer where the expected type is Real and vice versa.
17689          --  These corrections allow the compilation process to proceed further
17690          --  along since some basic assumptions of the format of the bounds
17691          --  are guaranteed.
17692
17693          if Etype (R) = Any_Type then
17694
17695             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
17696                Rewrite (Lo,
17697                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
17698
17699             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
17700                Rewrite (Hi,
17701                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
17702
17703             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
17704                Rewrite (Lo,
17705                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
17706
17707             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
17708                Rewrite (Hi,
17709                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
17710             end if;
17711
17712             Set_Etype (Lo, T);
17713             Set_Etype (Hi, T);
17714          end if;
17715
17716          --  If the bounds of the range have been mistakenly given as string
17717          --  literals (perhaps in place of character literals), then an error
17718          --  has already been reported, but we rewrite the string literal as a
17719          --  bound of the range's type to avoid blowups in later processing
17720          --  that looks at static values.
17721
17722          if Nkind (Lo) = N_String_Literal then
17723             Rewrite (Lo,
17724               Make_Attribute_Reference (Sloc (Lo),
17725                 Attribute_Name => Name_First,
17726                 Prefix => New_Reference_To (T, Sloc (Lo))));
17727             Analyze_And_Resolve (Lo);
17728          end if;
17729
17730          if Nkind (Hi) = N_String_Literal then
17731             Rewrite (Hi,
17732               Make_Attribute_Reference (Sloc (Hi),
17733                 Attribute_Name => Name_First,
17734                 Prefix => New_Reference_To (T, Sloc (Hi))));
17735             Analyze_And_Resolve (Hi);
17736          end if;
17737
17738          --  If bounds aren't scalar at this point then exit, avoiding
17739          --  problems with further processing of the range in this procedure.
17740
17741          if not Is_Scalar_Type (Etype (Lo)) then
17742             return;
17743          end if;
17744
17745          --  Resolve (actually Sem_Eval) has checked that the bounds are in
17746          --  then range of the base type. Here we check whether the bounds
17747          --  are in the range of the subtype itself. Note that if the bounds
17748          --  represent the null range the Constraint_Error exception should
17749          --  not be raised.
17750
17751          --  ??? The following code should be cleaned up as follows
17752
17753          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
17754          --     is done in the call to Range_Check (R, T); below
17755
17756          --  2. The use of R_Check_Off should be investigated and possibly
17757          --     removed, this would clean up things a bit.
17758
17759          if Is_Null_Range (Lo, Hi) then
17760             null;
17761
17762          else
17763             --  Capture values of bounds and generate temporaries for them
17764             --  if needed, before applying checks, since checks may cause
17765             --  duplication of the expression without forcing evaluation.
17766
17767             if Expander_Active then
17768                Force_Evaluation (Lo);
17769                Force_Evaluation (Hi);
17770             end if;
17771
17772             --  We use a flag here instead of suppressing checks on the
17773             --  type because the type we check against isn't necessarily
17774             --  the place where we put the check.
17775
17776             if not R_Check_Off then
17777                R_Checks := Get_Range_Checks (R, T);
17778
17779                --  Look up tree to find an appropriate insertion point. We
17780                --  can't just use insert_actions because later processing
17781                --  depends on the insertion node. Prior to Ada2012 the
17782                --  insertion point could only be a declaration or a loop, but
17783                --  quantified expressions can appear within any context in an
17784                --  expression, and the insertion point can be any statement,
17785                --  pragma, or declaration.
17786
17787                Insert_Node := Parent (R);
17788                while Present (Insert_Node) loop
17789                   exit when
17790                     Nkind (Insert_Node) in N_Declaration
17791                     and then
17792                       not Nkind_In
17793                         (Insert_Node, N_Component_Declaration,
17794                                       N_Loop_Parameter_Specification,
17795                                       N_Function_Specification,
17796                                       N_Procedure_Specification);
17797
17798                   exit when Nkind (Insert_Node) in N_Later_Decl_Item
17799                     or else Nkind (Insert_Node) in
17800                               N_Statement_Other_Than_Procedure_Call
17801                     or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
17802                                                    N_Pragma);
17803
17804                   Insert_Node := Parent (Insert_Node);
17805                end loop;
17806
17807                --  Why would Type_Decl not be present???  Without this test,
17808                --  short regression tests fail.
17809
17810                if Present (Insert_Node) then
17811
17812                   --  Case of loop statement. Verify that the range is part
17813                   --  of the subtype indication of the iteration scheme.
17814
17815                   if Nkind (Insert_Node) = N_Loop_Statement then
17816                      declare
17817                         Indic : Node_Id;
17818
17819                      begin
17820                         Indic := Parent (R);
17821                         while Present (Indic)
17822                           and then Nkind (Indic) /= N_Subtype_Indication
17823                         loop
17824                            Indic := Parent (Indic);
17825                         end loop;
17826
17827                         if Present (Indic) then
17828                            Def_Id := Etype (Subtype_Mark (Indic));
17829
17830                            Insert_Range_Checks
17831                              (R_Checks,
17832                               Insert_Node,
17833                               Def_Id,
17834                               Sloc (Insert_Node),
17835                               R,
17836                               Do_Before => True);
17837                         end if;
17838                      end;
17839
17840                   --  Insertion before a declaration. If the declaration
17841                   --  includes discriminants, the list of applicable checks
17842                   --  is given by the caller.
17843
17844                   elsif Nkind (Insert_Node) in N_Declaration then
17845                      Def_Id := Defining_Identifier (Insert_Node);
17846
17847                      if (Ekind (Def_Id) = E_Record_Type
17848                           and then Depends_On_Discriminant (R))
17849                        or else
17850                         (Ekind (Def_Id) = E_Protected_Type
17851                           and then Has_Discriminants (Def_Id))
17852                      then
17853                         Append_Range_Checks
17854                           (R_Checks,
17855                             Check_List, Def_Id, Sloc (Insert_Node), R);
17856
17857                      else
17858                         Insert_Range_Checks
17859                           (R_Checks,
17860                             Insert_Node, Def_Id, Sloc (Insert_Node), R);
17861
17862                      end if;
17863
17864                   --  Insertion before a statement. Range appears in the
17865                   --  context of a quantified expression. Insertion will
17866                   --  take place when expression is expanded.
17867
17868                   else
17869                      null;
17870                   end if;
17871                end if;
17872             end if;
17873          end if;
17874
17875       --  Case of other than an explicit N_Range node
17876
17877       elsif Expander_Active then
17878          Get_Index_Bounds (R, Lo, Hi);
17879          Force_Evaluation (Lo);
17880          Force_Evaluation (Hi);
17881       end if;
17882    end Process_Range_Expr_In_Decl;
17883
17884    --------------------------------------
17885    -- Process_Real_Range_Specification --
17886    --------------------------------------
17887
17888    procedure Process_Real_Range_Specification (Def : Node_Id) is
17889       Spec : constant Node_Id := Real_Range_Specification (Def);
17890       Lo   : Node_Id;
17891       Hi   : Node_Id;
17892       Err  : Boolean := False;
17893
17894       procedure Analyze_Bound (N : Node_Id);
17895       --  Analyze and check one bound
17896
17897       -------------------
17898       -- Analyze_Bound --
17899       -------------------
17900
17901       procedure Analyze_Bound (N : Node_Id) is
17902       begin
17903          Analyze_And_Resolve (N, Any_Real);
17904
17905          if not Is_OK_Static_Expression (N) then
17906             Flag_Non_Static_Expr
17907               ("bound in real type definition is not static!", N);
17908             Err := True;
17909          end if;
17910       end Analyze_Bound;
17911
17912    --  Start of processing for Process_Real_Range_Specification
17913
17914    begin
17915       if Present (Spec) then
17916          Lo := Low_Bound (Spec);
17917          Hi := High_Bound (Spec);
17918          Analyze_Bound (Lo);
17919          Analyze_Bound (Hi);
17920
17921          --  If error, clear away junk range specification
17922
17923          if Err then
17924             Set_Real_Range_Specification (Def, Empty);
17925          end if;
17926       end if;
17927    end Process_Real_Range_Specification;
17928
17929    ---------------------
17930    -- Process_Subtype --
17931    ---------------------
17932
17933    function Process_Subtype
17934      (S           : Node_Id;
17935       Related_Nod : Node_Id;
17936       Related_Id  : Entity_Id := Empty;
17937       Suffix      : Character := ' ') return Entity_Id
17938    is
17939       P               : Node_Id;
17940       Def_Id          : Entity_Id;
17941       Error_Node      : Node_Id;
17942       Full_View_Id    : Entity_Id;
17943       Subtype_Mark_Id : Entity_Id;
17944
17945       May_Have_Null_Exclusion : Boolean;
17946
17947       procedure Check_Incomplete (T : Entity_Id);
17948       --  Called to verify that an incomplete type is not used prematurely
17949
17950       ----------------------
17951       -- Check_Incomplete --
17952       ----------------------
17953
17954       procedure Check_Incomplete (T : Entity_Id) is
17955       begin
17956          --  Ada 2005 (AI-412): Incomplete subtypes are legal
17957
17958          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
17959            and then
17960              not (Ada_Version >= Ada_2005
17961                     and then
17962                        (Nkind (Parent (T)) = N_Subtype_Declaration
17963                           or else
17964                             (Nkind (Parent (T)) = N_Subtype_Indication
17965                                and then Nkind (Parent (Parent (T))) =
17966                                           N_Subtype_Declaration)))
17967          then
17968             Error_Msg_N ("invalid use of type before its full declaration", T);
17969          end if;
17970       end Check_Incomplete;
17971
17972    --  Start of processing for Process_Subtype
17973
17974    begin
17975       --  Case of no constraints present
17976
17977       if Nkind (S) /= N_Subtype_Indication then
17978          Find_Type (S);
17979          Check_Incomplete (S);
17980          P := Parent (S);
17981
17982          --  Ada 2005 (AI-231): Static check
17983
17984          if Ada_Version >= Ada_2005
17985            and then Present (P)
17986            and then Null_Exclusion_Present (P)
17987            and then Nkind (P) /= N_Access_To_Object_Definition
17988            and then not Is_Access_Type (Entity (S))
17989          then
17990             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
17991          end if;
17992
17993          --  The following is ugly, can't we have a range or even a flag???
17994
17995          May_Have_Null_Exclusion :=
17996            Nkind_In (P, N_Access_Definition,
17997                         N_Access_Function_Definition,
17998                         N_Access_Procedure_Definition,
17999                         N_Access_To_Object_Definition,
18000                         N_Allocator,
18001                         N_Component_Definition)
18002              or else
18003            Nkind_In (P, N_Derived_Type_Definition,
18004                         N_Discriminant_Specification,
18005                         N_Formal_Object_Declaration,
18006                         N_Object_Declaration,
18007                         N_Object_Renaming_Declaration,
18008                         N_Parameter_Specification,
18009                         N_Subtype_Declaration);
18010
18011          --  Create an Itype that is a duplicate of Entity (S) but with the
18012          --  null-exclusion attribute.
18013
18014          if May_Have_Null_Exclusion
18015            and then Is_Access_Type (Entity (S))
18016            and then Null_Exclusion_Present (P)
18017
18018             --  No need to check the case of an access to object definition.
18019             --  It is correct to define double not-null pointers.
18020
18021             --  Example:
18022             --     type Not_Null_Int_Ptr is not null access Integer;
18023             --     type Acc is not null access Not_Null_Int_Ptr;
18024
18025            and then Nkind (P) /= N_Access_To_Object_Definition
18026          then
18027             if Can_Never_Be_Null (Entity (S)) then
18028                case Nkind (Related_Nod) is
18029                   when N_Full_Type_Declaration =>
18030                      if Nkind (Type_Definition (Related_Nod))
18031                        in N_Array_Type_Definition
18032                      then
18033                         Error_Node :=
18034                           Subtype_Indication
18035                             (Component_Definition
18036                              (Type_Definition (Related_Nod)));
18037                      else
18038                         Error_Node :=
18039                           Subtype_Indication (Type_Definition (Related_Nod));
18040                      end if;
18041
18042                   when N_Subtype_Declaration =>
18043                      Error_Node := Subtype_Indication (Related_Nod);
18044
18045                   when N_Object_Declaration =>
18046                      Error_Node := Object_Definition (Related_Nod);
18047
18048                   when N_Component_Declaration =>
18049                      Error_Node :=
18050                        Subtype_Indication (Component_Definition (Related_Nod));
18051
18052                   when N_Allocator =>
18053                      Error_Node := Expression (Related_Nod);
18054
18055                   when others =>
18056                      pragma Assert (False);
18057                      Error_Node := Related_Nod;
18058                end case;
18059
18060                Error_Msg_NE
18061                  ("`NOT NULL` not allowed (& already excludes null)",
18062                   Error_Node,
18063                   Entity (S));
18064             end if;
18065
18066             Set_Etype  (S,
18067               Create_Null_Excluding_Itype
18068                 (T           => Entity (S),
18069                  Related_Nod => P));
18070             Set_Entity (S, Etype (S));
18071          end if;
18072
18073          return Entity (S);
18074
18075       --  Case of constraint present, so that we have an N_Subtype_Indication
18076       --  node (this node is created only if constraints are present).
18077
18078       else
18079          Find_Type (Subtype_Mark (S));
18080
18081          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
18082            and then not
18083             (Nkind (Parent (S)) = N_Subtype_Declaration
18084               and then Is_Itype (Defining_Identifier (Parent (S))))
18085          then
18086             Check_Incomplete (Subtype_Mark (S));
18087          end if;
18088
18089          P := Parent (S);
18090          Subtype_Mark_Id := Entity (Subtype_Mark (S));
18091
18092          --  Explicit subtype declaration case
18093
18094          if Nkind (P) = N_Subtype_Declaration then
18095             Def_Id := Defining_Identifier (P);
18096
18097          --  Explicit derived type definition case
18098
18099          elsif Nkind (P) = N_Derived_Type_Definition then
18100             Def_Id := Defining_Identifier (Parent (P));
18101
18102          --  Implicit case, the Def_Id must be created as an implicit type.
18103          --  The one exception arises in the case of concurrent types, array
18104          --  and access types, where other subsidiary implicit types may be
18105          --  created and must appear before the main implicit type. In these
18106          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
18107          --  has not yet been called to create Def_Id.
18108
18109          else
18110             if Is_Array_Type (Subtype_Mark_Id)
18111               or else Is_Concurrent_Type (Subtype_Mark_Id)
18112               or else Is_Access_Type (Subtype_Mark_Id)
18113             then
18114                Def_Id := Empty;
18115
18116             --  For the other cases, we create a new unattached Itype,
18117             --  and set the indication to ensure it gets attached later.
18118
18119             else
18120                Def_Id :=
18121                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
18122             end if;
18123          end if;
18124
18125          --  If the kind of constraint is invalid for this kind of type,
18126          --  then give an error, and then pretend no constraint was given.
18127
18128          if not Is_Valid_Constraint_Kind
18129                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
18130          then
18131             Error_Msg_N
18132               ("incorrect constraint for this kind of type", Constraint (S));
18133
18134             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
18135
18136             --  Set Ekind of orphan itype, to prevent cascaded errors
18137
18138             if Present (Def_Id) then
18139                Set_Ekind (Def_Id, Ekind (Any_Type));
18140             end if;
18141
18142             --  Make recursive call, having got rid of the bogus constraint
18143
18144             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
18145          end if;
18146
18147          --  Remaining processing depends on type
18148
18149          case Ekind (Subtype_Mark_Id) is
18150             when Access_Kind =>
18151                Constrain_Access (Def_Id, S, Related_Nod);
18152
18153                if Expander_Active
18154                  and then  Is_Itype (Designated_Type (Def_Id))
18155                  and then Nkind (Related_Nod) = N_Subtype_Declaration
18156                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
18157                then
18158                   Build_Itype_Reference
18159                     (Designated_Type (Def_Id), Related_Nod);
18160                end if;
18161
18162             when Array_Kind =>
18163                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
18164
18165             when Decimal_Fixed_Point_Kind =>
18166                Constrain_Decimal (Def_Id, S);
18167
18168             when Enumeration_Kind =>
18169                Constrain_Enumeration (Def_Id, S);
18170
18171             when Ordinary_Fixed_Point_Kind =>
18172                Constrain_Ordinary_Fixed (Def_Id, S);
18173
18174             when Float_Kind =>
18175                Constrain_Float (Def_Id, S);
18176
18177             when Integer_Kind =>
18178                Constrain_Integer (Def_Id, S);
18179
18180             when E_Record_Type     |
18181                  E_Record_Subtype  |
18182                  Class_Wide_Kind   |
18183                  E_Incomplete_Type =>
18184                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
18185
18186                if Ekind (Def_Id) = E_Incomplete_Type then
18187                   Set_Private_Dependents (Def_Id, New_Elmt_List);
18188                end if;
18189
18190             when Private_Kind =>
18191                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
18192                Set_Private_Dependents (Def_Id, New_Elmt_List);
18193
18194                --  In case of an invalid constraint prevent further processing
18195                --  since the type constructed is missing expected fields.
18196
18197                if Etype (Def_Id) = Any_Type then
18198                   return Def_Id;
18199                end if;
18200
18201                --  If the full view is that of a task with discriminants,
18202                --  we must constrain both the concurrent type and its
18203                --  corresponding record type. Otherwise we will just propagate
18204                --  the constraint to the full view, if available.
18205
18206                if Present (Full_View (Subtype_Mark_Id))
18207                  and then Has_Discriminants (Subtype_Mark_Id)
18208                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
18209                then
18210                   Full_View_Id :=
18211                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
18212
18213                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
18214                   Constrain_Concurrent (Full_View_Id, S,
18215                     Related_Nod, Related_Id, Suffix);
18216                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
18217                   Set_Full_View (Def_Id, Full_View_Id);
18218
18219                   --  Introduce an explicit reference to the private subtype,
18220                   --  to prevent scope anomalies in gigi if first use appears
18221                   --  in a nested context, e.g. a later function body.
18222                   --  Should this be generated in other contexts than a full
18223                   --  type declaration?
18224
18225                   if Is_Itype (Def_Id)
18226                     and then
18227                       Nkind (Parent (P)) = N_Full_Type_Declaration
18228                   then
18229                      Build_Itype_Reference (Def_Id, Parent (P));
18230                   end if;
18231
18232                else
18233                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
18234                end if;
18235
18236             when Concurrent_Kind  =>
18237                Constrain_Concurrent (Def_Id, S,
18238                  Related_Nod, Related_Id, Suffix);
18239
18240             when others =>
18241                Error_Msg_N ("invalid subtype mark in subtype indication", S);
18242          end case;
18243
18244          --  Size and Convention are always inherited from the base type
18245
18246          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
18247          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
18248
18249          return Def_Id;
18250       end if;
18251    end Process_Subtype;
18252
18253    ---------------------------------------
18254    -- Check_Anonymous_Access_Components --
18255    ---------------------------------------
18256
18257    procedure Check_Anonymous_Access_Components
18258       (Typ_Decl  : Node_Id;
18259        Typ       : Entity_Id;
18260        Prev      : Entity_Id;
18261        Comp_List : Node_Id)
18262    is
18263       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
18264       Anon_Access : Entity_Id;
18265       Acc_Def     : Node_Id;
18266       Comp        : Node_Id;
18267       Comp_Def    : Node_Id;
18268       Decl        : Node_Id;
18269       Type_Def    : Node_Id;
18270
18271       procedure Build_Incomplete_Type_Declaration;
18272       --  If the record type contains components that include an access to the
18273       --  current record, then create an incomplete type declaration for the
18274       --  record, to be used as the designated type of the anonymous access.
18275       --  This is done only once, and only if there is no previous partial
18276       --  view of the type.
18277
18278       function Designates_T (Subt : Node_Id) return Boolean;
18279       --  Check whether a node designates the enclosing record type, or 'Class
18280       --  of that type
18281
18282       function Mentions_T (Acc_Def : Node_Id) return Boolean;
18283       --  Check whether an access definition includes a reference to
18284       --  the enclosing record type. The reference can be a subtype mark
18285       --  in the access definition itself, a 'Class attribute reference, or
18286       --  recursively a reference appearing in a parameter specification
18287       --  or result definition of an access_to_subprogram definition.
18288
18289       --------------------------------------
18290       -- Build_Incomplete_Type_Declaration --
18291       --------------------------------------
18292
18293       procedure Build_Incomplete_Type_Declaration is
18294          Decl  : Node_Id;
18295          Inc_T : Entity_Id;
18296          H     : Entity_Id;
18297
18298          --  Is_Tagged indicates whether the type is tagged. It is tagged if
18299          --  it's "is new ... with record" or else "is tagged record ...".
18300
18301          Is_Tagged : constant Boolean :=
18302              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
18303                  and then
18304                    Present
18305                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
18306            or else
18307              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
18308                  and then Tagged_Present (Type_Definition (Typ_Decl)));
18309
18310       begin
18311          --  If there is a previous partial view, no need to create a new one
18312          --  If the partial view, given by Prev, is incomplete,  If Prev is
18313          --  a private declaration, full declaration is flagged accordingly.
18314
18315          if Prev /= Typ then
18316             if Is_Tagged then
18317                Make_Class_Wide_Type (Prev);
18318                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
18319                Set_Etype (Class_Wide_Type (Typ), Typ);
18320             end if;
18321
18322             return;
18323
18324          elsif Has_Private_Declaration (Typ) then
18325
18326             --  If we refer to T'Class inside T, and T is the completion of a
18327             --  private type, then we need to make sure the class-wide type
18328             --  exists.
18329
18330             if Is_Tagged then
18331                Make_Class_Wide_Type (Typ);
18332             end if;
18333
18334             return;
18335
18336          --  If there was a previous anonymous access type, the incomplete
18337          --  type declaration will have been created already.
18338
18339          elsif Present (Current_Entity (Typ))
18340            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
18341            and then Full_View (Current_Entity (Typ)) = Typ
18342          then
18343             if Is_Tagged
18344               and then Comes_From_Source (Current_Entity (Typ))
18345               and then not Is_Tagged_Type (Current_Entity (Typ))
18346             then
18347                Make_Class_Wide_Type (Typ);
18348                Error_Msg_N
18349                  ("incomplete view of tagged type should be declared tagged?",
18350                   Parent (Current_Entity (Typ)));
18351             end if;
18352             return;
18353
18354          else
18355             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
18356             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
18357
18358             --  Type has already been inserted into the current scope. Remove
18359             --  it, and add incomplete declaration for type, so that subsequent
18360             --  anonymous access types can use it. The entity is unchained from
18361             --  the homonym list and from immediate visibility. After analysis,
18362             --  the entity in the incomplete declaration becomes immediately
18363             --  visible in the record declaration that follows.
18364
18365             H := Current_Entity (Typ);
18366
18367             if H = Typ then
18368                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
18369             else
18370                while Present (H)
18371                  and then Homonym (H) /= Typ
18372                loop
18373                   H := Homonym (Typ);
18374                end loop;
18375
18376                Set_Homonym (H, Homonym (Typ));
18377             end if;
18378
18379             Insert_Before (Typ_Decl, Decl);
18380             Analyze (Decl);
18381             Set_Full_View (Inc_T, Typ);
18382
18383             if Is_Tagged then
18384
18385                --  Create a common class-wide type for both views, and set the
18386                --  Etype of the class-wide type to the full view.
18387
18388                Make_Class_Wide_Type (Inc_T);
18389                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
18390                Set_Etype (Class_Wide_Type (Typ), Typ);
18391             end if;
18392          end if;
18393       end Build_Incomplete_Type_Declaration;
18394
18395       ------------------
18396       -- Designates_T --
18397       ------------------
18398
18399       function Designates_T (Subt : Node_Id) return Boolean is
18400          Type_Id : constant Name_Id := Chars (Typ);
18401
18402          function Names_T (Nam : Node_Id) return Boolean;
18403          --  The record type has not been introduced in the current scope
18404          --  yet, so we must examine the name of the type itself, either
18405          --  an identifier T, or an expanded name of the form P.T, where
18406          --  P denotes the current scope.
18407
18408          -------------
18409          -- Names_T --
18410          -------------
18411
18412          function Names_T (Nam : Node_Id) return Boolean is
18413          begin
18414             if Nkind (Nam) = N_Identifier then
18415                return Chars (Nam) = Type_Id;
18416
18417             elsif Nkind (Nam) = N_Selected_Component then
18418                if Chars (Selector_Name (Nam)) = Type_Id then
18419                   if Nkind (Prefix (Nam)) = N_Identifier then
18420                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
18421
18422                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
18423                      return Chars (Selector_Name (Prefix (Nam))) =
18424                             Chars (Current_Scope);
18425                   else
18426                      return False;
18427                   end if;
18428
18429                else
18430                   return False;
18431                end if;
18432
18433             else
18434                return False;
18435             end if;
18436          end Names_T;
18437
18438       --  Start of processing for Designates_T
18439
18440       begin
18441          if Nkind (Subt) = N_Identifier then
18442             return Chars (Subt) = Type_Id;
18443
18444             --  Reference can be through an expanded name which has not been
18445             --  analyzed yet, and which designates enclosing scopes.
18446
18447          elsif Nkind (Subt) = N_Selected_Component then
18448             if Names_T (Subt) then
18449                return True;
18450
18451             --  Otherwise it must denote an entity that is already visible.
18452             --  The access definition may name a subtype of the enclosing
18453             --  type, if there is a previous incomplete declaration for it.
18454
18455             else
18456                Find_Selected_Component (Subt);
18457                return
18458                  Is_Entity_Name (Subt)
18459                    and then Scope (Entity (Subt)) = Current_Scope
18460                    and then
18461                      (Chars (Base_Type (Entity (Subt))) = Type_Id
18462                        or else
18463                          (Is_Class_Wide_Type (Entity (Subt))
18464                            and then
18465                            Chars (Etype (Base_Type (Entity (Subt)))) =
18466                                                                   Type_Id));
18467             end if;
18468
18469          --  A reference to the current type may appear as the prefix of
18470          --  a 'Class attribute.
18471
18472          elsif Nkind (Subt) = N_Attribute_Reference
18473            and then Attribute_Name (Subt) = Name_Class
18474          then
18475             return Names_T (Prefix (Subt));
18476
18477          else
18478             return False;
18479          end if;
18480       end Designates_T;
18481
18482       ----------------
18483       -- Mentions_T --
18484       ----------------
18485
18486       function Mentions_T (Acc_Def : Node_Id) return Boolean is
18487          Param_Spec : Node_Id;
18488
18489          Acc_Subprg : constant Node_Id :=
18490                         Access_To_Subprogram_Definition (Acc_Def);
18491
18492       begin
18493          if No (Acc_Subprg) then
18494             return Designates_T (Subtype_Mark (Acc_Def));
18495          end if;
18496
18497          --  Component is an access_to_subprogram: examine its formals,
18498          --  and result definition in the case of an access_to_function.
18499
18500          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
18501          while Present (Param_Spec) loop
18502             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
18503               and then Mentions_T (Parameter_Type (Param_Spec))
18504             then
18505                return True;
18506
18507             elsif Designates_T (Parameter_Type (Param_Spec)) then
18508                return True;
18509             end if;
18510
18511             Next (Param_Spec);
18512          end loop;
18513
18514          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
18515             if Nkind (Result_Definition (Acc_Subprg)) =
18516                  N_Access_Definition
18517             then
18518                return Mentions_T (Result_Definition (Acc_Subprg));
18519             else
18520                return Designates_T (Result_Definition (Acc_Subprg));
18521             end if;
18522          end if;
18523
18524          return False;
18525       end Mentions_T;
18526
18527    --  Start of processing for Check_Anonymous_Access_Components
18528
18529    begin
18530       if No (Comp_List) then
18531          return;
18532       end if;
18533
18534       Comp := First (Component_Items (Comp_List));
18535       while Present (Comp) loop
18536          if Nkind (Comp) = N_Component_Declaration
18537            and then Present
18538              (Access_Definition (Component_Definition (Comp)))
18539            and then
18540              Mentions_T (Access_Definition (Component_Definition (Comp)))
18541          then
18542             Comp_Def := Component_Definition (Comp);
18543             Acc_Def :=
18544               Access_To_Subprogram_Definition
18545                 (Access_Definition (Comp_Def));
18546
18547             Build_Incomplete_Type_Declaration;
18548             Anon_Access := Make_Temporary (Loc, 'S');
18549
18550             --  Create a declaration for the anonymous access type: either
18551             --  an access_to_object or an access_to_subprogram.
18552
18553             if Present (Acc_Def) then
18554                if Nkind  (Acc_Def) = N_Access_Function_Definition then
18555                   Type_Def :=
18556                     Make_Access_Function_Definition (Loc,
18557                       Parameter_Specifications =>
18558                         Parameter_Specifications (Acc_Def),
18559                       Result_Definition => Result_Definition (Acc_Def));
18560                else
18561                   Type_Def :=
18562                     Make_Access_Procedure_Definition (Loc,
18563                       Parameter_Specifications =>
18564                         Parameter_Specifications (Acc_Def));
18565                end if;
18566
18567             else
18568                Type_Def :=
18569                  Make_Access_To_Object_Definition (Loc,
18570                    Subtype_Indication =>
18571                       Relocate_Node
18572                         (Subtype_Mark
18573                           (Access_Definition (Comp_Def))));
18574
18575                Set_Constant_Present
18576                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
18577                Set_All_Present
18578                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
18579             end if;
18580
18581             Set_Null_Exclusion_Present
18582               (Type_Def,
18583                Null_Exclusion_Present (Access_Definition (Comp_Def)));
18584
18585             Decl :=
18586               Make_Full_Type_Declaration (Loc,
18587                 Defining_Identifier => Anon_Access,
18588                 Type_Definition     => Type_Def);
18589
18590             Insert_Before (Typ_Decl, Decl);
18591             Analyze (Decl);
18592
18593             --  If an access to object, Preserve entity of designated type,
18594             --  for ASIS use, before rewriting the component definition.
18595
18596             if No (Acc_Def) then
18597                declare
18598                   Desig : Entity_Id;
18599
18600                begin
18601                   Desig := Entity (Subtype_Indication (Type_Def));
18602
18603                   --  If the access definition is to the current  record,
18604                   --  the visible entity at this point is an  incomplete
18605                   --  type. Retrieve the full view to simplify  ASIS queries
18606
18607                   if Ekind (Desig) = E_Incomplete_Type then
18608                      Desig := Full_View (Desig);
18609                   end if;
18610
18611                   Set_Entity
18612                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
18613                end;
18614             end if;
18615
18616             Rewrite (Comp_Def,
18617               Make_Component_Definition (Loc,
18618                 Subtype_Indication =>
18619                New_Occurrence_Of (Anon_Access, Loc)));
18620
18621             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
18622                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
18623             else
18624                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
18625             end if;
18626
18627             Set_Is_Local_Anonymous_Access (Anon_Access);
18628          end if;
18629
18630          Next (Comp);
18631       end loop;
18632
18633       if Present (Variant_Part (Comp_List)) then
18634          declare
18635             V : Node_Id;
18636          begin
18637             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
18638             while Present (V) loop
18639                Check_Anonymous_Access_Components
18640                  (Typ_Decl, Typ, Prev, Component_List (V));
18641                Next_Non_Pragma (V);
18642             end loop;
18643          end;
18644       end if;
18645    end Check_Anonymous_Access_Components;
18646
18647    --------------------------------
18648    -- Preanalyze_Spec_Expression --
18649    --------------------------------
18650
18651    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
18652       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
18653    begin
18654       In_Spec_Expression := True;
18655       Preanalyze_And_Resolve (N, T);
18656       In_Spec_Expression := Save_In_Spec_Expression;
18657    end Preanalyze_Spec_Expression;
18658
18659    -----------------------------
18660    -- Record_Type_Declaration --
18661    -----------------------------
18662
18663    procedure Record_Type_Declaration
18664      (T    : Entity_Id;
18665       N    : Node_Id;
18666       Prev : Entity_Id)
18667    is
18668       Def       : constant Node_Id := Type_Definition (N);
18669       Is_Tagged : Boolean;
18670       Tag_Comp  : Entity_Id;
18671
18672    begin
18673       --  These flags must be initialized before calling Process_Discriminants
18674       --  because this routine makes use of them.
18675
18676       Set_Ekind             (T, E_Record_Type);
18677       Set_Etype             (T, T);
18678       Init_Size_Align       (T);
18679       Set_Interfaces        (T, No_Elist);
18680       Set_Stored_Constraint (T, No_Elist);
18681
18682       --  Normal case
18683
18684       if Ada_Version < Ada_2005
18685         or else not Interface_Present (Def)
18686       then
18687          --  The flag Is_Tagged_Type might have already been set by
18688          --  Find_Type_Name if it detected an error for declaration T. This
18689          --  arises in the case of private tagged types where the full view
18690          --  omits the word tagged.
18691
18692          Is_Tagged :=
18693            Tagged_Present (Def)
18694              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
18695
18696          Set_Is_Tagged_Type      (T, Is_Tagged);
18697          Set_Is_Limited_Record   (T, Limited_Present (Def));
18698
18699          --  Type is abstract if full declaration carries keyword, or if
18700          --  previous partial view did.
18701
18702          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
18703                                       or else Abstract_Present (Def));
18704
18705       else
18706          Is_Tagged := True;
18707          Analyze_Interface_Declaration (T, Def);
18708
18709          if Present (Discriminant_Specifications (N)) then
18710             Error_Msg_N
18711               ("interface types cannot have discriminants",
18712                 Defining_Identifier
18713                   (First (Discriminant_Specifications (N))));
18714          end if;
18715       end if;
18716
18717       --  First pass: if there are self-referential access components,
18718       --  create the required anonymous access type declarations, and if
18719       --  need be an incomplete type declaration for T itself.
18720
18721       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
18722
18723       if Ada_Version >= Ada_2005
18724         and then Present (Interface_List (Def))
18725       then
18726          Check_Interfaces (N, Def);
18727
18728          declare
18729             Ifaces_List : Elist_Id;
18730
18731          begin
18732             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
18733             --  already in the parents.
18734
18735             Collect_Interfaces
18736               (T               => T,
18737                Ifaces_List     => Ifaces_List,
18738                Exclude_Parents => True);
18739
18740             Set_Interfaces (T, Ifaces_List);
18741          end;
18742       end if;
18743
18744       --  Records constitute a scope for the component declarations within.
18745       --  The scope is created prior to the processing of these declarations.
18746       --  Discriminants are processed first, so that they are visible when
18747       --  processing the other components. The Ekind of the record type itself
18748       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
18749
18750       --  Enter record scope
18751
18752       Push_Scope (T);
18753
18754       --  If an incomplete or private type declaration was already given for
18755       --  the type, then this scope already exists, and the discriminants have
18756       --  been declared within. We must verify that the full declaration
18757       --  matches the incomplete one.
18758
18759       Check_Or_Process_Discriminants (N, T, Prev);
18760
18761       Set_Is_Constrained     (T, not Has_Discriminants (T));
18762       Set_Has_Delayed_Freeze (T, True);
18763
18764       --  For tagged types add a manually analyzed component corresponding
18765       --  to the component _tag, the corresponding piece of tree will be
18766       --  expanded as part of the freezing actions if it is not a CPP_Class.
18767
18768       if Is_Tagged then
18769
18770          --  Do not add the tag unless we are in expansion mode
18771
18772          if Expander_Active then
18773             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
18774             Enter_Name (Tag_Comp);
18775
18776             Set_Ekind                     (Tag_Comp, E_Component);
18777             Set_Is_Tag                    (Tag_Comp);
18778             Set_Is_Aliased                (Tag_Comp);
18779             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
18780             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
18781             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
18782             Init_Component_Location       (Tag_Comp);
18783
18784             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
18785             --  implemented interfaces.
18786
18787             if Has_Interfaces (T) then
18788                Add_Interface_Tag_Components (N, T);
18789             end if;
18790          end if;
18791
18792          Make_Class_Wide_Type (T);
18793          Set_Direct_Primitive_Operations (T, New_Elmt_List);
18794       end if;
18795
18796       --  We must suppress range checks when processing record components in
18797       --  the presence of discriminants, since we don't want spurious checks to
18798       --  be generated during their analysis, but Suppress_Range_Checks flags
18799       --  must be reset the after processing the record definition.
18800
18801       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
18802       --  couldn't we just use the normal range check suppression method here.
18803       --  That would seem cleaner ???
18804
18805       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
18806          Set_Kill_Range_Checks (T, True);
18807          Record_Type_Definition (Def, Prev);
18808          Set_Kill_Range_Checks (T, False);
18809       else
18810          Record_Type_Definition (Def, Prev);
18811       end if;
18812
18813       --  Exit from record scope
18814
18815       End_Scope;
18816
18817       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
18818       --  the implemented interfaces and associate them an aliased entity.
18819
18820       if Is_Tagged
18821         and then not Is_Empty_List (Interface_List (Def))
18822       then
18823          Derive_Progenitor_Subprograms (T, T);
18824       end if;
18825    end Record_Type_Declaration;
18826
18827    ----------------------------
18828    -- Record_Type_Definition --
18829    ----------------------------
18830
18831    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
18832       Component          : Entity_Id;
18833       Ctrl_Components    : Boolean := False;
18834       Final_Storage_Only : Boolean;
18835       T                  : Entity_Id;
18836
18837    begin
18838       if Ekind (Prev_T) = E_Incomplete_Type then
18839          T := Full_View (Prev_T);
18840       else
18841          T := Prev_T;
18842       end if;
18843
18844       Final_Storage_Only := not Is_Controlled (T);
18845
18846       --  Ada 2005: check whether an explicit Limited is present in a derived
18847       --  type declaration.
18848
18849       if Nkind (Parent (Def)) = N_Derived_Type_Definition
18850         and then Limited_Present (Parent (Def))
18851       then
18852          Set_Is_Limited_Record (T);
18853       end if;
18854
18855       --  If the component list of a record type is defined by the reserved
18856       --  word null and there is no discriminant part, then the record type has
18857       --  no components and all records of the type are null records (RM 3.7)
18858       --  This procedure is also called to process the extension part of a
18859       --  record extension, in which case the current scope may have inherited
18860       --  components.
18861
18862       if No (Def)
18863         or else No (Component_List (Def))
18864         or else Null_Present (Component_List (Def))
18865       then
18866          null;
18867
18868       else
18869          Analyze_Declarations (Component_Items (Component_List (Def)));
18870
18871          if Present (Variant_Part (Component_List (Def))) then
18872             Analyze (Variant_Part (Component_List (Def)));
18873          end if;
18874       end if;
18875
18876       --  After completing the semantic analysis of the record definition,
18877       --  record components, both new and inherited, are accessible. Set their
18878       --  kind accordingly. Exclude malformed itypes from illegal declarations,
18879       --  whose Ekind may be void.
18880
18881       Component := First_Entity (Current_Scope);
18882       while Present (Component) loop
18883          if Ekind (Component) = E_Void
18884            and then not Is_Itype (Component)
18885          then
18886             Set_Ekind (Component, E_Component);
18887             Init_Component_Location (Component);
18888          end if;
18889
18890          if Has_Task (Etype (Component)) then
18891             Set_Has_Task (T);
18892          end if;
18893
18894          if Ekind (Component) /= E_Component then
18895             null;
18896
18897          --  Do not set Has_Controlled_Component on a class-wide equivalent
18898          --  type. See Make_CW_Equivalent_Type.
18899
18900          elsif not Is_Class_Wide_Equivalent_Type (T)
18901            and then (Has_Controlled_Component (Etype (Component))
18902                       or else (Chars (Component) /= Name_uParent
18903                                 and then Is_Controlled (Etype (Component))))
18904          then
18905             Set_Has_Controlled_Component (T, True);
18906             Final_Storage_Only :=
18907               Final_Storage_Only
18908                 and then Finalize_Storage_Only (Etype (Component));
18909             Ctrl_Components := True;
18910          end if;
18911
18912          Next_Entity (Component);
18913       end loop;
18914
18915       --  A Type is Finalize_Storage_Only only if all its controlled components
18916       --  are also.
18917
18918       if Ctrl_Components then
18919          Set_Finalize_Storage_Only (T, Final_Storage_Only);
18920       end if;
18921
18922       --  Place reference to end record on the proper entity, which may
18923       --  be a partial view.
18924
18925       if Present (Def) then
18926          Process_End_Label (Def, 'e', Prev_T);
18927       end if;
18928    end Record_Type_Definition;
18929
18930    ------------------------
18931    -- Replace_Components --
18932    ------------------------
18933
18934    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
18935       function Process (N : Node_Id) return Traverse_Result;
18936
18937       -------------
18938       -- Process --
18939       -------------
18940
18941       function Process (N : Node_Id) return Traverse_Result is
18942          Comp : Entity_Id;
18943
18944       begin
18945          if Nkind (N) = N_Discriminant_Specification then
18946             Comp := First_Discriminant (Typ);
18947             while Present (Comp) loop
18948                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18949                   Set_Defining_Identifier (N, Comp);
18950                   exit;
18951                end if;
18952
18953                Next_Discriminant (Comp);
18954             end loop;
18955
18956          elsif Nkind (N) = N_Component_Declaration then
18957             Comp := First_Component (Typ);
18958             while Present (Comp) loop
18959                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18960                   Set_Defining_Identifier (N, Comp);
18961                   exit;
18962                end if;
18963
18964                Next_Component (Comp);
18965             end loop;
18966          end if;
18967
18968          return OK;
18969       end Process;
18970
18971       procedure Replace is new Traverse_Proc (Process);
18972
18973    --  Start of processing for Replace_Components
18974
18975    begin
18976       Replace (Decl);
18977    end Replace_Components;
18978
18979    -------------------------------
18980    -- Set_Completion_Referenced --
18981    -------------------------------
18982
18983    procedure Set_Completion_Referenced (E : Entity_Id) is
18984    begin
18985       --  If in main unit, mark entity that is a completion as referenced,
18986       --  warnings go on the partial view when needed.
18987
18988       if In_Extended_Main_Source_Unit (E) then
18989          Set_Referenced (E);
18990       end if;
18991    end Set_Completion_Referenced;
18992
18993    ---------------------
18994    -- Set_Fixed_Range --
18995    ---------------------
18996
18997    --  The range for fixed-point types is complicated by the fact that we
18998    --  do not know the exact end points at the time of the declaration. This
18999    --  is true for three reasons:
19000
19001    --     A size clause may affect the fudging of the end-points
19002    --     A small clause may affect the values of the end-points
19003    --     We try to include the end-points if it does not affect the size
19004
19005    --  This means that the actual end-points must be established at the point
19006    --  when the type is frozen. Meanwhile, we first narrow the range as
19007    --  permitted (so that it will fit if necessary in a small specified size),
19008    --  and then build a range subtree with these narrowed bounds.
19009
19010    --  Set_Fixed_Range constructs the range from real literal values, and sets
19011    --  the range as the Scalar_Range of the given fixed-point type entity.
19012
19013    --  The parent of this range is set to point to the entity so that it is
19014    --  properly hooked into the tree (unlike normal Scalar_Range entries for
19015    --  other scalar types, which are just pointers to the range in the
19016    --  original tree, this would otherwise be an orphan).
19017
19018    --  The tree is left unanalyzed. When the type is frozen, the processing
19019    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
19020    --  analyzed, and uses this as an indication that it should complete
19021    --  work on the range (it will know the final small and size values).
19022
19023    procedure Set_Fixed_Range
19024      (E   : Entity_Id;
19025       Loc : Source_Ptr;
19026       Lo  : Ureal;
19027       Hi  : Ureal)
19028    is
19029       S : constant Node_Id :=
19030             Make_Range (Loc,
19031               Low_Bound  => Make_Real_Literal (Loc, Lo),
19032               High_Bound => Make_Real_Literal (Loc, Hi));
19033    begin
19034       Set_Scalar_Range (E, S);
19035       Set_Parent (S, E);
19036    end Set_Fixed_Range;
19037
19038    ----------------------------------
19039    -- Set_Scalar_Range_For_Subtype --
19040    ----------------------------------
19041
19042    procedure Set_Scalar_Range_For_Subtype
19043      (Def_Id : Entity_Id;
19044       R      : Node_Id;
19045       Subt   : Entity_Id)
19046    is
19047       Kind : constant Entity_Kind :=  Ekind (Def_Id);
19048
19049    begin
19050       --  Defend against previous error
19051
19052       if Nkind (R) = N_Error then
19053          return;
19054       end if;
19055
19056       Set_Scalar_Range (Def_Id, R);
19057
19058       --  We need to link the range into the tree before resolving it so
19059       --  that types that are referenced, including importantly the subtype
19060       --  itself, are properly frozen (Freeze_Expression requires that the
19061       --  expression be properly linked into the tree). Of course if it is
19062       --  already linked in, then we do not disturb the current link.
19063
19064       if No (Parent (R)) then
19065          Set_Parent (R, Def_Id);
19066       end if;
19067
19068       --  Reset the kind of the subtype during analysis of the range, to
19069       --  catch possible premature use in the bounds themselves.
19070
19071       Set_Ekind (Def_Id, E_Void);
19072       Process_Range_Expr_In_Decl (R, Subt);
19073       Set_Ekind (Def_Id, Kind);
19074    end Set_Scalar_Range_For_Subtype;
19075
19076    --------------------------------------------------------
19077    -- Set_Stored_Constraint_From_Discriminant_Constraint --
19078    --------------------------------------------------------
19079
19080    procedure Set_Stored_Constraint_From_Discriminant_Constraint
19081      (E : Entity_Id)
19082    is
19083    begin
19084       --  Make sure set if encountered during Expand_To_Stored_Constraint
19085
19086       Set_Stored_Constraint (E, No_Elist);
19087
19088       --  Give it the right value
19089
19090       if Is_Constrained (E) and then Has_Discriminants (E) then
19091          Set_Stored_Constraint (E,
19092            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
19093       end if;
19094    end Set_Stored_Constraint_From_Discriminant_Constraint;
19095
19096    -------------------------------------
19097    -- Signed_Integer_Type_Declaration --
19098    -------------------------------------
19099
19100    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
19101       Implicit_Base : Entity_Id;
19102       Base_Typ      : Entity_Id;
19103       Lo_Val        : Uint;
19104       Hi_Val        : Uint;
19105       Errs          : Boolean := False;
19106       Lo            : Node_Id;
19107       Hi            : Node_Id;
19108
19109       function Can_Derive_From (E : Entity_Id) return Boolean;
19110       --  Determine whether given bounds allow derivation from specified type
19111
19112       procedure Check_Bound (Expr : Node_Id);
19113       --  Check bound to make sure it is integral and static. If not, post
19114       --  appropriate error message and set Errs flag
19115
19116       ---------------------
19117       -- Can_Derive_From --
19118       ---------------------
19119
19120       --  Note we check both bounds against both end values, to deal with
19121       --  strange types like ones with a range of 0 .. -12341234.
19122
19123       function Can_Derive_From (E : Entity_Id) return Boolean is
19124          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
19125          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
19126       begin
19127          return Lo <= Lo_Val and then Lo_Val <= Hi
19128                   and then
19129                 Lo <= Hi_Val and then Hi_Val <= Hi;
19130       end Can_Derive_From;
19131
19132       -----------------
19133       -- Check_Bound --
19134       -----------------
19135
19136       procedure Check_Bound (Expr : Node_Id) is
19137       begin
19138          --  If a range constraint is used as an integer type definition, each
19139          --  bound of the range must be defined by a static expression of some
19140          --  integer type, but the two bounds need not have the same integer
19141          --  type (Negative bounds are allowed.) (RM 3.5.4)
19142
19143          if not Is_Integer_Type (Etype (Expr)) then
19144             Error_Msg_N
19145               ("integer type definition bounds must be of integer type", Expr);
19146             Errs := True;
19147
19148          elsif not Is_OK_Static_Expression (Expr) then
19149             Flag_Non_Static_Expr
19150               ("non-static expression used for integer type bound!", Expr);
19151             Errs := True;
19152
19153          --  The bounds are folded into literals, and we set their type to be
19154          --  universal, to avoid typing difficulties: we cannot set the type
19155          --  of the literal to the new type, because this would be a forward
19156          --  reference for the back end,  and if the original type is user-
19157          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
19158
19159          else
19160             if Is_Entity_Name (Expr) then
19161                Fold_Uint (Expr, Expr_Value (Expr), True);
19162             end if;
19163
19164             Set_Etype (Expr, Universal_Integer);
19165          end if;
19166       end Check_Bound;
19167
19168    --  Start of processing for Signed_Integer_Type_Declaration
19169
19170    begin
19171       --  Create an anonymous base type
19172
19173       Implicit_Base :=
19174         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
19175
19176       --  Analyze and check the bounds, they can be of any integer type
19177
19178       Lo := Low_Bound (Def);
19179       Hi := High_Bound (Def);
19180
19181       --  Arbitrarily use Integer as the type if either bound had an error
19182
19183       if Hi = Error or else Lo = Error then
19184          Base_Typ := Any_Integer;
19185          Set_Error_Posted (T, True);
19186
19187       --  Here both bounds are OK expressions
19188
19189       else
19190          Analyze_And_Resolve (Lo, Any_Integer);
19191          Analyze_And_Resolve (Hi, Any_Integer);
19192
19193          Check_Bound (Lo);
19194          Check_Bound (Hi);
19195
19196          if Errs then
19197             Hi := Type_High_Bound (Standard_Long_Long_Integer);
19198             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
19199          end if;
19200
19201          --  Find type to derive from
19202
19203          Lo_Val := Expr_Value (Lo);
19204          Hi_Val := Expr_Value (Hi);
19205
19206          if Can_Derive_From (Standard_Short_Short_Integer) then
19207             Base_Typ := Base_Type (Standard_Short_Short_Integer);
19208
19209          elsif Can_Derive_From (Standard_Short_Integer) then
19210             Base_Typ := Base_Type (Standard_Short_Integer);
19211
19212          elsif Can_Derive_From (Standard_Integer) then
19213             Base_Typ := Base_Type (Standard_Integer);
19214
19215          elsif Can_Derive_From (Standard_Long_Integer) then
19216             Base_Typ := Base_Type (Standard_Long_Integer);
19217
19218          elsif Can_Derive_From (Standard_Long_Long_Integer) then
19219             Base_Typ := Base_Type (Standard_Long_Long_Integer);
19220
19221          else
19222             Base_Typ := Base_Type (Standard_Long_Long_Integer);
19223             Error_Msg_N ("integer type definition bounds out of range", Def);
19224             Hi := Type_High_Bound (Standard_Long_Long_Integer);
19225             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
19226          end if;
19227       end if;
19228
19229       --  Complete both implicit base and declared first subtype entities
19230
19231       Set_Etype          (Implicit_Base, Base_Typ);
19232       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
19233       Set_Size_Info      (Implicit_Base,                (Base_Typ));
19234       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
19235       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
19236
19237       Set_Ekind          (T, E_Signed_Integer_Subtype);
19238       Set_Etype          (T, Implicit_Base);
19239
19240       Set_Size_Info      (T,                (Implicit_Base));
19241       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
19242       Set_Scalar_Range   (T, Def);
19243       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
19244       Set_Is_Constrained (T);
19245    end Signed_Integer_Type_Declaration;
19246
19247 end Sem_Ch3;