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-2015, 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
26with Aspects;  use Aspects;
27with Atree;    use Atree;
28with Checks;   use Checks;
29with Debug;    use Debug;
30with Elists;   use Elists;
31with Einfo;    use Einfo;
32with Errout;   use Errout;
33with Eval_Fat; use Eval_Fat;
34with Exp_Ch3;  use Exp_Ch3;
35with Exp_Ch9;  use Exp_Ch9;
36with Exp_Disp; use Exp_Disp;
37with Exp_Dist; use Exp_Dist;
38with Exp_Tss;  use Exp_Tss;
39with Exp_Util; use Exp_Util;
40with Fname;    use Fname;
41with Freeze;   use Freeze;
42with Ghost;    use Ghost;
43with Itypes;   use Itypes;
44with Layout;   use Layout;
45with Lib;      use Lib;
46with Lib.Xref; use Lib.Xref;
47with Namet;    use Namet;
48with Nmake;    use Nmake;
49with Opt;      use Opt;
50with Restrict; use Restrict;
51with Rident;   use Rident;
52with Rtsfind;  use Rtsfind;
53with Sem;      use Sem;
54with Sem_Aux;  use Sem_Aux;
55with Sem_Case; use Sem_Case;
56with Sem_Cat;  use Sem_Cat;
57with Sem_Ch6;  use Sem_Ch6;
58with Sem_Ch7;  use Sem_Ch7;
59with Sem_Ch8;  use Sem_Ch8;
60with Sem_Ch10; use Sem_Ch10;
61with Sem_Ch13; use Sem_Ch13;
62with Sem_Dim;  use Sem_Dim;
63with Sem_Disp; use Sem_Disp;
64with Sem_Dist; use Sem_Dist;
65with Sem_Elim; use Sem_Elim;
66with Sem_Eval; use Sem_Eval;
67with Sem_Mech; use Sem_Mech;
68with Sem_Prag; use Sem_Prag;
69with Sem_Res;  use Sem_Res;
70with Sem_Smem; use Sem_Smem;
71with Sem_Type; use Sem_Type;
72with Sem_Util; use Sem_Util;
73with Sem_Warn; use Sem_Warn;
74with Stand;    use Stand;
75with Sinfo;    use Sinfo;
76with Sinput;   use Sinput;
77with Snames;   use Snames;
78with Targparm; use Targparm;
79with Tbuild;   use Tbuild;
80with Ttypes;   use Ttypes;
81with Uintp;    use Uintp;
82with Urealp;   use Urealp;
83
84package body Sem_Ch3 is
85
86   -----------------------
87   -- Local Subprograms --
88   -----------------------
89
90   procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
91   --  Ada 2005 (AI-251): Add the tag components corresponding to all the
92   --  abstract interface types implemented by a record type or a derived
93   --  record type.
94
95   procedure Analyze_Object_Contract (Obj_Id : Entity_Id);
96   --  Analyze all delayed pragmas chained on the contract of object Obj_Id as
97   --  if they appeared at the end of the declarative region. The pragmas to be
98   --  considered are:
99   --    Async_Readers
100   --    Async_Writers
101   --    Effective_Reads
102   --    Effective_Writes
103   --    Part_Of
104
105   procedure Build_Derived_Type
106     (N             : Node_Id;
107      Parent_Type   : Entity_Id;
108      Derived_Type  : Entity_Id;
109      Is_Completion : Boolean;
110      Derive_Subps  : Boolean := True);
111   --  Create and decorate a Derived_Type given the Parent_Type entity. N is
112   --  the N_Full_Type_Declaration node containing the derived type definition.
113   --  Parent_Type is the entity for the parent type in the derived type
114   --  definition and Derived_Type the actual derived type. Is_Completion must
115   --  be set to False if Derived_Type is the N_Defining_Identifier node in N
116   --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
117   --  completion of a private type declaration. If Is_Completion is set to
118   --  True, N is the completion of a private type declaration and Derived_Type
119   --  is different from the defining identifier inside N (i.e. Derived_Type /=
120   --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
121   --  subprograms should be derived. The only case where this parameter is
122   --  False is when Build_Derived_Type is recursively called to process an
123   --  implicit derived full type for a type derived from a private type (in
124   --  that case the subprograms must only be derived for the private view of
125   --  the type).
126   --
127   --  ??? These flags need a bit of re-examination and re-documentation:
128   --  ???  are they both necessary (both seem related to the recursion)?
129
130   procedure Build_Derived_Access_Type
131     (N            : Node_Id;
132      Parent_Type  : Entity_Id;
133      Derived_Type : Entity_Id);
134   --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
135   --  create an implicit base if the parent type is constrained or if the
136   --  subtype indication has a constraint.
137
138   procedure Build_Derived_Array_Type
139     (N            : Node_Id;
140      Parent_Type  : Entity_Id;
141      Derived_Type : Entity_Id);
142   --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
143   --  create an implicit base if the parent type is constrained or if the
144   --  subtype indication has a constraint.
145
146   procedure Build_Derived_Concurrent_Type
147     (N            : Node_Id;
148      Parent_Type  : Entity_Id;
149      Derived_Type : Entity_Id);
150   --  Subsidiary procedure to Build_Derived_Type. For a derived task or
151   --  protected type, inherit entries and protected subprograms, check
152   --  legality of discriminant constraints if any.
153
154   procedure Build_Derived_Enumeration_Type
155     (N            : Node_Id;
156      Parent_Type  : Entity_Id;
157      Derived_Type : Entity_Id);
158   --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
159   --  type, we must create a new list of literals. Types derived from
160   --  Character and [Wide_]Wide_Character are special-cased.
161
162   procedure Build_Derived_Numeric_Type
163     (N            : Node_Id;
164      Parent_Type  : Entity_Id;
165      Derived_Type : Entity_Id);
166   --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
167   --  an anonymous base type, and propagate constraint to subtype if needed.
168
169   procedure Build_Derived_Private_Type
170     (N             : Node_Id;
171      Parent_Type   : Entity_Id;
172      Derived_Type  : Entity_Id;
173      Is_Completion : Boolean;
174      Derive_Subps  : Boolean := True);
175   --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
176   --  because the parent may or may not have a completion, and the derivation
177   --  may itself be a completion.
178
179   procedure Build_Derived_Record_Type
180     (N            : Node_Id;
181      Parent_Type  : Entity_Id;
182      Derived_Type : Entity_Id;
183      Derive_Subps : Boolean := True);
184   --  Subsidiary procedure used for tagged and untagged record types
185   --  by Build_Derived_Type and Analyze_Private_Extension_Declaration.
186   --  All parameters are as in Build_Derived_Type except that N, in
187   --  addition to being an N_Full_Type_Declaration node, can also be an
188   --  N_Private_Extension_Declaration node. See the definition of this routine
189   --  for much more info. Derive_Subps indicates whether subprograms should be
190   --  derived from the parent type. The only case where Derive_Subps is False
191   --  is for an implicit derived full type for a type derived from a private
192   --  type (see Build_Derived_Type).
193
194   procedure Build_Discriminal (Discrim : Entity_Id);
195   --  Create the discriminal corresponding to discriminant Discrim, that is
196   --  the parameter corresponding to Discrim to be used in initialization
197   --  procedures for the type where Discrim is a discriminant. Discriminals
198   --  are not used during semantic analysis, and are not fully defined
199   --  entities until expansion. Thus they are not given a scope until
200   --  initialization procedures are built.
201
202   function Build_Discriminant_Constraints
203     (T           : Entity_Id;
204      Def         : Node_Id;
205      Derived_Def : Boolean := False) return Elist_Id;
206   --  Validate discriminant constraints and return the list of the constraints
207   --  in order of discriminant declarations, where T is the discriminated
208   --  unconstrained type. Def is the N_Subtype_Indication node where the
209   --  discriminants constraints for T are specified. Derived_Def is True
210   --  when building the discriminant constraints in a derived type definition
211   --  of the form "type D (...) is new T (xxx)". In this case T is the parent
212   --  type and Def is the constraint "(xxx)" on T and this routine sets the
213   --  Corresponding_Discriminant field of the discriminants in the derived
214   --  type D to point to the corresponding discriminants in the parent type T.
215
216   procedure Build_Discriminated_Subtype
217     (T           : Entity_Id;
218      Def_Id      : Entity_Id;
219      Elist       : Elist_Id;
220      Related_Nod : Node_Id;
221      For_Access  : Boolean := False);
222   --  Subsidiary procedure to Constrain_Discriminated_Type and to
223   --  Process_Incomplete_Dependents. Given
224   --
225   --     T (a possibly discriminated base type)
226   --     Def_Id (a very partially built subtype for T),
227   --
228   --  the call completes Def_Id to be the appropriate E_*_Subtype.
229   --
230   --  The Elist is the list of discriminant constraints if any (it is set
231   --  to No_Elist if T is not a discriminated type, and to an empty list if
232   --  T has discriminants but there are no discriminant constraints). The
233   --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
234   --  The For_Access says whether or not this subtype is really constraining
235   --  an access type. That is its sole purpose is the designated type of an
236   --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
237   --  is built to avoid freezing T when the access subtype is frozen.
238
239   function Build_Scalar_Bound
240     (Bound : Node_Id;
241      Par_T : Entity_Id;
242      Der_T : Entity_Id) return Node_Id;
243   --  The bounds of a derived scalar type are conversions of the bounds of
244   --  the parent type. Optimize the representation if the bounds are literals.
245   --  Needs a more complete spec--what are the parameters exactly, and what
246   --  exactly is the returned value, and how is Bound affected???
247
248   procedure Build_Underlying_Full_View
249     (N   : Node_Id;
250      Typ : Entity_Id;
251      Par : Entity_Id);
252   --  If the completion of a private type is itself derived from a private
253   --  type, or if the full view of a private subtype is itself private, the
254   --  back-end has no way to compute the actual size of this type. We build
255   --  an internal subtype declaration of the proper parent type to convey
256   --  this information. This extra mechanism is needed because a full
257   --  view cannot itself have a full view (it would get clobbered during
258   --  view exchanges).
259
260   procedure Check_Access_Discriminant_Requires_Limited
261     (D   : Node_Id;
262      Loc : Node_Id);
263   --  Check the restriction that the type to which an access discriminant
264   --  belongs must be a concurrent type or a descendant of a type with
265   --  the reserved word 'limited' in its declaration.
266
267   procedure Check_Anonymous_Access_Components
268      (Typ_Decl  : Node_Id;
269       Typ       : Entity_Id;
270       Prev      : Entity_Id;
271       Comp_List : Node_Id);
272   --  Ada 2005 AI-382: an access component in a record definition can refer to
273   --  the enclosing record, in which case it denotes the type itself, and not
274   --  the current instance of the type. We create an anonymous access type for
275   --  the component, and flag it as an access to a component, so accessibility
276   --  checks are properly performed on it. The declaration of the access type
277   --  is placed ahead of that of the record to prevent order-of-elaboration
278   --  circularity issues in Gigi. We create an incomplete type for the record
279   --  declaration, which is the designated type of the anonymous access.
280
281   procedure Check_Delta_Expression (E : Node_Id);
282   --  Check that the expression represented by E is suitable for use as a
283   --  delta expression, i.e. it is of real type and is static.
284
285   procedure Check_Digits_Expression (E : Node_Id);
286   --  Check that the expression represented by E is suitable for use as a
287   --  digits expression, i.e. it is of integer type, positive and static.
288
289   procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
290   --  Validate the initialization of an object declaration. T is the required
291   --  type, and Exp is the initialization expression.
292
293   procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
294   --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
295
296   procedure Check_Or_Process_Discriminants
297     (N    : Node_Id;
298      T    : Entity_Id;
299      Prev : Entity_Id := Empty);
300   --  If N is the full declaration of the completion T of an incomplete or
301   --  private type, check its discriminants (which are already known to be
302   --  conformant with those of the partial view, see Find_Type_Name),
303   --  otherwise process them. Prev is the entity of the partial declaration,
304   --  if any.
305
306   procedure Check_Real_Bound (Bound : Node_Id);
307   --  Check given bound for being of real type and static. If not, post an
308   --  appropriate message, and rewrite the bound with the real literal zero.
309
310   procedure Constant_Redeclaration
311     (Id : Entity_Id;
312      N  : Node_Id;
313      T  : out Entity_Id);
314   --  Various checks on legality of full declaration of deferred constant.
315   --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
316   --  node. The caller has not yet set any attributes of this entity.
317
318   function Contain_Interface
319     (Iface  : Entity_Id;
320      Ifaces : Elist_Id) return Boolean;
321   --  Ada 2005: Determine whether Iface is present in the list Ifaces
322
323   procedure Convert_Scalar_Bounds
324     (N            : Node_Id;
325      Parent_Type  : Entity_Id;
326      Derived_Type : Entity_Id;
327      Loc          : Source_Ptr);
328   --  For derived scalar types, convert the bounds in the type definition to
329   --  the derived type, and complete their analysis. Given a constraint of the
330   --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
331   --  T'Base, the parent_type. The bounds of the derived type (the anonymous
332   --  base) are copies of Lo and Hi. Finally, the bounds of the derived
333   --  subtype are conversions of those bounds to the derived_type, so that
334   --  their typing is consistent.
335
336   procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
337   --  Copies attributes from array base type T2 to array base type T1. Copies
338   --  only attributes that apply to base types, but not subtypes.
339
340   procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
341   --  Copies attributes from array subtype T2 to array subtype T1. Copies
342   --  attributes that apply to both subtypes and base types.
343
344   procedure Create_Constrained_Components
345     (Subt        : Entity_Id;
346      Decl_Node   : Node_Id;
347      Typ         : Entity_Id;
348      Constraints : Elist_Id);
349   --  Build the list of entities for a constrained discriminated record
350   --  subtype. If a component depends on a discriminant, replace its subtype
351   --  using the discriminant values in the discriminant constraint. Subt
352   --  is the defining identifier for the subtype whose list of constrained
353   --  entities we will create. Decl_Node is the type declaration node where
354   --  we will attach all the itypes created. Typ is the base discriminated
355   --  type for the subtype Subt. Constraints is the list of discriminant
356   --  constraints for Typ.
357
358   function Constrain_Component_Type
359     (Comp            : Entity_Id;
360      Constrained_Typ : Entity_Id;
361      Related_Node    : Node_Id;
362      Typ             : Entity_Id;
363      Constraints     : Elist_Id) return Entity_Id;
364   --  Given a discriminated base type Typ, a list of discriminant constraints,
365   --  Constraints, for Typ and a component Comp of Typ, create and return the
366   --  type corresponding to Etype (Comp) where all discriminant references
367   --  are replaced with the corresponding constraint. If Etype (Comp) contains
368   --  no discriminant references then it is returned as-is. Constrained_Typ
369   --  is the final constrained subtype to which the constrained component
370   --  belongs. Related_Node is the node where we attach all created itypes.
371
372   procedure Constrain_Access
373     (Def_Id      : in out Entity_Id;
374      S           : Node_Id;
375      Related_Nod : Node_Id);
376   --  Apply a list of constraints to an access type. If Def_Id is empty, it is
377   --  an anonymous type created for a subtype indication. In that case it is
378   --  created in the procedure and attached to Related_Nod.
379
380   procedure Constrain_Array
381     (Def_Id      : in out Entity_Id;
382      SI          : Node_Id;
383      Related_Nod : Node_Id;
384      Related_Id  : Entity_Id;
385      Suffix      : Character);
386   --  Apply a list of index constraints to an unconstrained array type. The
387   --  first parameter is the entity for the resulting subtype. A value of
388   --  Empty for Def_Id indicates that an implicit type must be created, but
389   --  creation is delayed (and must be done by this procedure) because other
390   --  subsidiary implicit types must be created first (which is why Def_Id
391   --  is an in/out parameter). The second parameter is a subtype indication
392   --  node for the constrained array to be created (e.g. something of the
393   --  form string (1 .. 10)). Related_Nod gives the place where this type
394   --  has to be inserted in the tree. The Related_Id and Suffix parameters
395   --  are used to build the associated Implicit type name.
396
397   procedure Constrain_Concurrent
398     (Def_Id      : in out Entity_Id;
399      SI          : Node_Id;
400      Related_Nod : Node_Id;
401      Related_Id  : Entity_Id;
402      Suffix      : Character);
403   --  Apply list of discriminant constraints to an unconstrained concurrent
404   --  type.
405   --
406   --    SI is the N_Subtype_Indication node containing the constraint and
407   --    the unconstrained type to constrain.
408   --
409   --    Def_Id is the entity for the resulting constrained subtype. A value
410   --    of Empty for Def_Id indicates that an implicit type must be created,
411   --    but creation is delayed (and must be done by this procedure) because
412   --    other subsidiary implicit types must be created first (which is why
413   --    Def_Id is an in/out parameter).
414   --
415   --    Related_Nod gives the place where this type has to be inserted
416   --    in the tree.
417   --
418   --  The last two arguments are used to create its external name if needed.
419
420   function Constrain_Corresponding_Record
421     (Prot_Subt   : Entity_Id;
422      Corr_Rec    : Entity_Id;
423      Related_Nod : Node_Id) return Entity_Id;
424   --  When constraining a protected type or task type with discriminants,
425   --  constrain the corresponding record with the same discriminant values.
426
427   procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
428   --  Constrain a decimal fixed point type with a digits constraint and/or a
429   --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
430
431   procedure Constrain_Discriminated_Type
432     (Def_Id      : Entity_Id;
433      S           : Node_Id;
434      Related_Nod : Node_Id;
435      For_Access  : Boolean := False);
436   --  Process discriminant constraints of composite type. Verify that values
437   --  have been provided for all discriminants, that the original type is
438   --  unconstrained, and that the types of the supplied expressions match
439   --  the discriminant types. The first three parameters are like in routine
440   --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
441   --  of For_Access.
442
443   procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
444   --  Constrain an enumeration type with a range constraint. This is identical
445   --  to Constrain_Integer, but for the Ekind of the resulting subtype.
446
447   procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
448   --  Constrain a floating point type with either a digits constraint
449   --  and/or a range constraint, building a E_Floating_Point_Subtype.
450
451   procedure Constrain_Index
452     (Index        : Node_Id;
453      S            : Node_Id;
454      Related_Nod  : Node_Id;
455      Related_Id   : Entity_Id;
456      Suffix       : Character;
457      Suffix_Index : Nat);
458   --  Process an index constraint S in a constrained array declaration. The
459   --  constraint can be a subtype name, or a range with or without an explicit
460   --  subtype mark. The index is the corresponding index of the unconstrained
461   --  array. The Related_Id and Suffix parameters are used to build the
462   --  associated Implicit type name.
463
464   procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
465   --  Build subtype of a signed or modular integer type
466
467   procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
468   --  Constrain an ordinary fixed point type with a range constraint, and
469   --  build an E_Ordinary_Fixed_Point_Subtype entity.
470
471   procedure Copy_And_Swap (Priv, Full : Entity_Id);
472   --  Copy the Priv entity into the entity of its full declaration then swap
473   --  the two entities in such a manner that the former private type is now
474   --  seen as a full type.
475
476   procedure Decimal_Fixed_Point_Type_Declaration
477     (T   : Entity_Id;
478      Def : Node_Id);
479   --  Create a new decimal fixed point type, and apply the constraint to
480   --  obtain a subtype of this new type.
481
482   procedure Complete_Private_Subtype
483     (Priv        : Entity_Id;
484      Full        : Entity_Id;
485      Full_Base   : Entity_Id;
486      Related_Nod : Node_Id);
487   --  Complete the implicit full view of a private subtype by setting the
488   --  appropriate semantic fields. If the full view of the parent is a record
489   --  type, build constrained components of subtype.
490
491   procedure Derive_Progenitor_Subprograms
492     (Parent_Type : Entity_Id;
493      Tagged_Type : Entity_Id);
494   --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
495   --  operations of progenitors of Tagged_Type, and replace the subsidiary
496   --  subtypes with Tagged_Type, to build the specs of the inherited interface
497   --  primitives. The derived primitives are aliased to those of the
498   --  interface. This routine takes care also of transferring to the full view
499   --  subprograms associated with the partial view of Tagged_Type that cover
500   --  interface primitives.
501
502   procedure Derived_Standard_Character
503     (N             : Node_Id;
504      Parent_Type   : Entity_Id;
505      Derived_Type  : Entity_Id);
506   --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
507   --  derivations from types Standard.Character and Standard.Wide_Character.
508
509   procedure Derived_Type_Declaration
510     (T             : Entity_Id;
511      N             : Node_Id;
512      Is_Completion : Boolean);
513   --  Process a derived type declaration. Build_Derived_Type is invoked
514   --  to process the actual derived type definition. Parameters N and
515   --  Is_Completion have the same meaning as in Build_Derived_Type.
516   --  T is the N_Defining_Identifier for the entity defined in the
517   --  N_Full_Type_Declaration node N, that is T is the derived type.
518
519   procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
520   --  Insert each literal in symbol table, as an overloadable identifier. Each
521   --  enumeration type is mapped into a sequence of integers, and each literal
522   --  is defined as a constant with integer value. If any of the literals are
523   --  character literals, the type is a character type, which means that
524   --  strings are legal aggregates for arrays of components of the type.
525
526   function Expand_To_Stored_Constraint
527     (Typ        : Entity_Id;
528      Constraint : Elist_Id) return Elist_Id;
529   --  Given a constraint (i.e. a list of expressions) on the discriminants of
530   --  Typ, expand it into a constraint on the stored discriminants and return
531   --  the new list of expressions constraining the stored discriminants.
532
533   function Find_Type_Of_Object
534     (Obj_Def     : Node_Id;
535      Related_Nod : Node_Id) return Entity_Id;
536   --  Get type entity for object referenced by Obj_Def, attaching the implicit
537   --  types generated to Related_Nod.
538
539   procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
540   --  Create a new float and apply the constraint to obtain subtype of it
541
542   function Has_Range_Constraint (N : Node_Id) return Boolean;
543   --  Given an N_Subtype_Indication node N, return True if a range constraint
544   --  is present, either directly, or as part of a digits or delta constraint.
545   --  In addition, a digits constraint in the decimal case returns True, since
546   --  it establishes a default range if no explicit range is present.
547
548   function Inherit_Components
549     (N             : Node_Id;
550      Parent_Base   : Entity_Id;
551      Derived_Base  : Entity_Id;
552      Is_Tagged     : Boolean;
553      Inherit_Discr : Boolean;
554      Discs         : Elist_Id) return Elist_Id;
555   --  Called from Build_Derived_Record_Type to inherit the components of
556   --  Parent_Base (a base type) into the Derived_Base (the derived base type).
557   --  For more information on derived types and component inheritance please
558   --  consult the comment above the body of Build_Derived_Record_Type.
559   --
560   --    N is the original derived type declaration
561   --
562   --    Is_Tagged is set if we are dealing with tagged types
563   --
564   --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
565   --    Parent_Base, otherwise no discriminants are inherited.
566   --
567   --    Discs gives the list of constraints that apply to Parent_Base in the
568   --    derived type declaration. If Discs is set to No_Elist, then we have
569   --    the following situation:
570   --
571   --      type Parent (D1..Dn : ..) is [tagged] record ...;
572   --      type Derived is new Parent [with ...];
573   --
574   --    which gets treated as
575   --
576   --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
577   --
578   --  For untagged types the returned value is an association list. The list
579   --  starts from the association (Parent_Base => Derived_Base), and then it
580   --  contains a sequence of the associations of the form
581   --
582   --    (Old_Component => New_Component),
583   --
584   --  where Old_Component is the Entity_Id of a component in Parent_Base and
585   --  New_Component is the Entity_Id of the corresponding component in
586   --  Derived_Base. For untagged records, this association list is needed when
587   --  copying the record declaration for the derived base. In the tagged case
588   --  the value returned is irrelevant.
589
590   procedure Inherit_Predicate_Flags (Subt, Par : Entity_Id);
591   --  Propagate static and dynamic predicate flags from a parent to the
592   --  subtype in a subtype declaration with and without constraints.
593
594   function Is_EVF_Procedure (Subp : Entity_Id) return Boolean;
595   --  Subsidiary to Check_Abstract_Overriding and Derive_Subprogram.
596   --  Determine whether subprogram Subp is a procedure subject to pragma
597   --  Extensions_Visible with value False and has at least one controlling
598   --  parameter of mode OUT.
599
600   function Is_Valid_Constraint_Kind
601     (T_Kind          : Type_Kind;
602      Constraint_Kind : Node_Kind) return Boolean;
603   --  Returns True if it is legal to apply the given kind of constraint to the
604   --  given kind of type (index constraint to an array type, for example).
605
606   procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
607   --  Create new modular type. Verify that modulus is in bounds
608
609   procedure New_Concatenation_Op (Typ : Entity_Id);
610   --  Create an abbreviated declaration for an operator in order to
611   --  materialize concatenation on array types.
612
613   procedure Ordinary_Fixed_Point_Type_Declaration
614     (T   : Entity_Id;
615      Def : Node_Id);
616   --  Create a new ordinary fixed point type, and apply the constraint to
617   --  obtain subtype of it.
618
619   procedure Prepare_Private_Subtype_Completion
620     (Id          : Entity_Id;
621      Related_Nod : Node_Id);
622   --  Id is a subtype of some private type. Creates the full declaration
623   --  associated with Id whenever possible, i.e. when the full declaration
624   --  of the base type is already known. Records each subtype into
625   --  Private_Dependents of the base type.
626
627   procedure Process_Incomplete_Dependents
628     (N      : Node_Id;
629      Full_T : Entity_Id;
630      Inc_T  : Entity_Id);
631   --  Process all entities that depend on an incomplete type. There include
632   --  subtypes, subprogram types that mention the incomplete type in their
633   --  profiles, and subprogram with access parameters that designate the
634   --  incomplete type.
635
636   --  Inc_T is the defining identifier of an incomplete type declaration, its
637   --  Ekind is E_Incomplete_Type.
638   --
639   --    N is the corresponding N_Full_Type_Declaration for Inc_T.
640   --
641   --    Full_T is N's defining identifier.
642   --
643   --  Subtypes of incomplete types with discriminants are completed when the
644   --  parent type is. This is simpler than private subtypes, because they can
645   --  only appear in the same scope, and there is no need to exchange views.
646   --  Similarly, access_to_subprogram types may have a parameter or a return
647   --  type that is an incomplete type, and that must be replaced with the
648   --  full type.
649   --
650   --  If the full type is tagged, subprogram with access parameters that
651   --  designated the incomplete may be primitive operations of the full type,
652   --  and have to be processed accordingly.
653
654   procedure Process_Real_Range_Specification (Def : Node_Id);
655   --  Given the type definition for a real type, this procedure processes and
656   --  checks the real range specification of this type definition if one is
657   --  present. If errors are found, error messages are posted, and the
658   --  Real_Range_Specification of Def is reset to Empty.
659
660   procedure Propagate_Default_Init_Cond_Attributes
661     (From_Typ             : Entity_Id;
662      To_Typ               : Entity_Id;
663      Parent_To_Derivation : Boolean := False;
664      Private_To_Full_View : Boolean := False);
665   --  Subsidiary to routines Build_Derived_Type and Process_Full_View. Inherit
666   --  all attributes related to pragma Default_Initial_Condition from From_Typ
667   --  to To_Typ. Flag Parent_To_Derivation should be set when the context is
668   --  the creation of a derived type. Flag Private_To_Full_View should be set
669   --  when processing both views of a private type.
670
671   procedure Record_Type_Declaration
672     (T    : Entity_Id;
673      N    : Node_Id;
674      Prev : Entity_Id);
675   --  Process a record type declaration (for both untagged and tagged
676   --  records). Parameters T and N are exactly like in procedure
677   --  Derived_Type_Declaration, except that no flag Is_Completion is needed
678   --  for this routine. If this is the completion of an incomplete type
679   --  declaration, Prev is the entity of the incomplete declaration, used for
680   --  cross-referencing. Otherwise Prev = T.
681
682   procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
683   --  This routine is used to process the actual record type definition (both
684   --  for untagged and tagged records). Def is a record type definition node.
685   --  This procedure analyzes the components in this record type definition.
686   --  Prev_T is the entity for the enclosing record type. It is provided so
687   --  that its Has_Task flag can be set if any of the component have Has_Task
688   --  set. If the declaration is the completion of an incomplete type
689   --  declaration, Prev_T is the original incomplete type, whose full view is
690   --  the record type.
691
692   procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
693   --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
694   --  build a copy of the declaration tree of the parent, and we create
695   --  independently the list of components for the derived type. Semantic
696   --  information uses the component entities, but record representation
697   --  clauses are validated on the declaration tree. This procedure replaces
698   --  discriminants and components in the declaration with those that have
699   --  been created by Inherit_Components.
700
701   procedure Set_Fixed_Range
702     (E   : Entity_Id;
703      Loc : Source_Ptr;
704      Lo  : Ureal;
705      Hi  : Ureal);
706   --  Build a range node with the given bounds and set it as the Scalar_Range
707   --  of the given fixed-point type entity. Loc is the source location used
708   --  for the constructed range. See body for further details.
709
710   procedure Set_Scalar_Range_For_Subtype
711     (Def_Id : Entity_Id;
712      R      : Node_Id;
713      Subt   : Entity_Id);
714   --  This routine is used to set the scalar range field for a subtype given
715   --  Def_Id, the entity for the subtype, and R, the range expression for the
716   --  scalar range. Subt provides the parent subtype to be used to analyze,
717   --  resolve, and check the given range.
718
719   procedure Set_Default_SSO (T : Entity_Id);
720   --  T is the entity for an array or record being declared. This procedure
721   --  sets the flags SSO_Set_Low_By_Default/SSO_Set_High_By_Default according
722   --  to the setting of Opt.Default_SSO.
723
724   procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
725   --  Create a new signed integer entity, and apply the constraint to obtain
726   --  the required first named subtype of this type.
727
728   procedure Set_Stored_Constraint_From_Discriminant_Constraint
729     (E : Entity_Id);
730   --  E is some record type. This routine computes E's Stored_Constraint
731   --  from its Discriminant_Constraint.
732
733   procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
734   --  Check that an entity in a list of progenitors is an interface,
735   --  emit error otherwise.
736
737   -----------------------
738   -- Access_Definition --
739   -----------------------
740
741   function Access_Definition
742     (Related_Nod : Node_Id;
743      N           : Node_Id) return Entity_Id
744   is
745      Anon_Type           : Entity_Id;
746      Anon_Scope          : Entity_Id;
747      Desig_Type          : Entity_Id;
748      Enclosing_Prot_Type : Entity_Id := Empty;
749
750   begin
751      Check_SPARK_05_Restriction ("access type is not allowed", N);
752
753      if Is_Entry (Current_Scope)
754        and then Is_Task_Type (Etype (Scope (Current_Scope)))
755      then
756         Error_Msg_N ("task entries cannot have access parameters", N);
757         return Empty;
758      end if;
759
760      --  Ada 2005: For an object declaration the corresponding anonymous
761      --  type is declared in the current scope.
762
763      --  If the access definition is the return type of another access to
764      --  function, scope is the current one, because it is the one of the
765      --  current type declaration, except for the pathological case below.
766
767      if Nkind_In (Related_Nod, N_Object_Declaration,
768                                N_Access_Function_Definition)
769      then
770         Anon_Scope := Current_Scope;
771
772         --  A pathological case: function returning access functions that
773         --  return access functions, etc. Each anonymous access type created
774         --  is in the enclosing scope of the outermost function.
775
776         declare
777            Par : Node_Id;
778
779         begin
780            Par := Related_Nod;
781            while Nkind_In (Par, N_Access_Function_Definition,
782                                 N_Access_Definition)
783            loop
784               Par := Parent (Par);
785            end loop;
786
787            if Nkind (Par) = N_Function_Specification then
788               Anon_Scope := Scope (Defining_Entity (Par));
789            end if;
790         end;
791
792      --  For the anonymous function result case, retrieve the scope of the
793      --  function specification's associated entity rather than using the
794      --  current scope. The current scope will be the function itself if the
795      --  formal part is currently being analyzed, but will be the parent scope
796      --  in the case of a parameterless function, and we always want to use
797      --  the function's parent scope. Finally, if the function is a child
798      --  unit, we must traverse the tree to retrieve the proper entity.
799
800      elsif Nkind (Related_Nod) = N_Function_Specification
801        and then Nkind (Parent (N)) /= N_Parameter_Specification
802      then
803         --  If the current scope is a protected type, the anonymous access
804         --  is associated with one of the protected operations, and must
805         --  be available in the scope that encloses the protected declaration.
806         --  Otherwise the type is in the scope enclosing the subprogram.
807
808         --  If the function has formals, The return type of a subprogram
809         --  declaration is analyzed in the scope of the subprogram (see
810         --  Process_Formals) and thus the protected type, if present, is
811         --  the scope of the current function scope.
812
813         if Ekind (Current_Scope) = E_Protected_Type then
814            Enclosing_Prot_Type := Current_Scope;
815
816         elsif Ekind (Current_Scope) = E_Function
817           and then Ekind (Scope (Current_Scope)) = E_Protected_Type
818         then
819            Enclosing_Prot_Type := Scope (Current_Scope);
820         end if;
821
822         if Present (Enclosing_Prot_Type) then
823            Anon_Scope := Scope (Enclosing_Prot_Type);
824
825         else
826            Anon_Scope := Scope (Defining_Entity (Related_Nod));
827         end if;
828
829      --  For an access type definition, if the current scope is a child
830      --  unit it is the scope of the type.
831
832      elsif Is_Compilation_Unit (Current_Scope) then
833         Anon_Scope := Current_Scope;
834
835      --  For access formals, access components, and access discriminants, the
836      --  scope is that of the enclosing declaration,
837
838      else
839         Anon_Scope := Scope (Current_Scope);
840      end if;
841
842      Anon_Type :=
843        Create_Itype
844          (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
845
846      if All_Present (N)
847        and then Ada_Version >= Ada_2005
848      then
849         Error_Msg_N ("ALL is not permitted for anonymous access types", N);
850      end if;
851
852      --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
853      --  the corresponding semantic routine
854
855      if Present (Access_To_Subprogram_Definition (N)) then
856
857         --  Compiler runtime units are compiled in Ada 2005 mode when building
858         --  the runtime library but must also be compilable in Ada 95 mode
859         --  (when bootstrapping the compiler).
860
861         Check_Compiler_Unit ("anonymous access to subprogram", N);
862
863         Access_Subprogram_Declaration
864           (T_Name => Anon_Type,
865            T_Def  => Access_To_Subprogram_Definition (N));
866
867         if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
868            Set_Ekind
869              (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
870         else
871            Set_Ekind (Anon_Type, E_Anonymous_Access_Subprogram_Type);
872         end if;
873
874         Set_Can_Use_Internal_Rep
875           (Anon_Type, not Always_Compatible_Rep_On_Target);
876
877         --  If the anonymous access is associated with a protected operation,
878         --  create a reference to it after the enclosing protected definition
879         --  because the itype will be used in the subsequent bodies.
880
881         --  If the anonymous access itself is protected, a full type
882         --  declaratiton will be created for it, so that the equivalent
883         --  record type can be constructed. For further details, see
884         --  Replace_Anonymous_Access_To_Protected-Subprogram.
885
886         if Ekind (Current_Scope) = E_Protected_Type
887           and then not Protected_Present (Access_To_Subprogram_Definition (N))
888         then
889            Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
890         end if;
891
892         return Anon_Type;
893      end if;
894
895      Find_Type (Subtype_Mark (N));
896      Desig_Type := Entity (Subtype_Mark (N));
897
898      Set_Directly_Designated_Type (Anon_Type, Desig_Type);
899      Set_Etype (Anon_Type, Anon_Type);
900
901      --  Make sure the anonymous access type has size and alignment fields
902      --  set, as required by gigi. This is necessary in the case of the
903      --  Task_Body_Procedure.
904
905      if not Has_Private_Component (Desig_Type) then
906         Layout_Type (Anon_Type);
907      end if;
908
909      --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
910      --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
911      --  the null value is allowed. In Ada 95 the null value is never allowed.
912
913      if Ada_Version >= Ada_2005 then
914         Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
915      else
916         Set_Can_Never_Be_Null (Anon_Type, True);
917      end if;
918
919      --  The anonymous access type is as public as the discriminated type or
920      --  subprogram that defines it. It is imported (for back-end purposes)
921      --  if the designated type is.
922
923      Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
924
925      --  Ada 2005 (AI-231): Propagate the access-constant attribute
926
927      Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
928
929      --  The context is either a subprogram declaration, object declaration,
930      --  or an access discriminant, in a private or a full type declaration.
931      --  In the case of a subprogram, if the designated type is incomplete,
932      --  the operation will be a primitive operation of the full type, to be
933      --  updated subsequently. If the type is imported through a limited_with
934      --  clause, the subprogram is not a primitive operation of the type
935      --  (which is declared elsewhere in some other scope).
936
937      if Ekind (Desig_Type) = E_Incomplete_Type
938        and then not From_Limited_With (Desig_Type)
939        and then Is_Overloadable (Current_Scope)
940      then
941         Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
942         Set_Has_Delayed_Freeze (Current_Scope);
943      end if;
944
945      --  Ada 2005: If the designated type is an interface that may contain
946      --  tasks, create a Master entity for the declaration. This must be done
947      --  before expansion of the full declaration, because the declaration may
948      --  include an expression that is an allocator, whose expansion needs the
949      --  proper Master for the created tasks.
950
951      if Nkind (Related_Nod) = N_Object_Declaration and then Expander_Active
952      then
953         if Is_Interface (Desig_Type) and then Is_Limited_Record (Desig_Type)
954         then
955            Build_Class_Wide_Master (Anon_Type);
956
957         --  Similarly, if the type is an anonymous access that designates
958         --  tasks, create a master entity for it in the current context.
959
960         elsif Has_Task (Desig_Type) and then Comes_From_Source (Related_Nod)
961         then
962            Build_Master_Entity (Defining_Identifier (Related_Nod));
963            Build_Master_Renaming (Anon_Type);
964         end if;
965      end if;
966
967      --  For a private component of a protected type, it is imperative that
968      --  the back-end elaborate the type immediately after the protected
969      --  declaration, because this type will be used in the declarations
970      --  created for the component within each protected body, so we must
971      --  create an itype reference for it now.
972
973      if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
974         Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
975
976      --  Similarly, if the access definition is the return result of a
977      --  function, create an itype reference for it because it will be used
978      --  within the function body. For a regular function that is not a
979      --  compilation unit, insert reference after the declaration. For a
980      --  protected operation, insert it after the enclosing protected type
981      --  declaration. In either case, do not create a reference for a type
982      --  obtained through a limited_with clause, because this would introduce
983      --  semantic dependencies.
984
985      --  Similarly, do not create a reference if the designated type is a
986      --  generic formal, because no use of it will reach the backend.
987
988      elsif Nkind (Related_Nod) = N_Function_Specification
989        and then not From_Limited_With (Desig_Type)
990        and then not Is_Generic_Type (Desig_Type)
991      then
992         if Present (Enclosing_Prot_Type) then
993            Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
994
995         elsif Is_List_Member (Parent (Related_Nod))
996           and then Nkind (Parent (N)) /= N_Parameter_Specification
997         then
998            Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
999         end if;
1000
1001      --  Finally, create an itype reference for an object declaration of an
1002      --  anonymous access type. This is strictly necessary only for deferred
1003      --  constants, but in any case will avoid out-of-scope problems in the
1004      --  back-end.
1005
1006      elsif Nkind (Related_Nod) = N_Object_Declaration then
1007         Build_Itype_Reference (Anon_Type, Related_Nod);
1008      end if;
1009
1010      return Anon_Type;
1011   end Access_Definition;
1012
1013   -----------------------------------
1014   -- Access_Subprogram_Declaration --
1015   -----------------------------------
1016
1017   procedure Access_Subprogram_Declaration
1018     (T_Name : Entity_Id;
1019      T_Def  : Node_Id)
1020   is
1021      procedure Check_For_Premature_Usage (Def : Node_Id);
1022      --  Check that type T_Name is not used, directly or recursively, as a
1023      --  parameter or a return type in Def. Def is either a subtype, an
1024      --  access_definition, or an access_to_subprogram_definition.
1025
1026      -------------------------------
1027      -- Check_For_Premature_Usage --
1028      -------------------------------
1029
1030      procedure Check_For_Premature_Usage (Def : Node_Id) is
1031         Param : Node_Id;
1032
1033      begin
1034         --  Check for a subtype mark
1035
1036         if Nkind (Def) in N_Has_Etype then
1037            if Etype (Def) = T_Name then
1038               Error_Msg_N
1039                 ("type& cannot be used before end of its declaration", Def);
1040            end if;
1041
1042         --  If this is not a subtype, then this is an access_definition
1043
1044         elsif Nkind (Def) = N_Access_Definition then
1045            if Present (Access_To_Subprogram_Definition (Def)) then
1046               Check_For_Premature_Usage
1047                 (Access_To_Subprogram_Definition (Def));
1048            else
1049               Check_For_Premature_Usage (Subtype_Mark (Def));
1050            end if;
1051
1052         --  The only cases left are N_Access_Function_Definition and
1053         --  N_Access_Procedure_Definition.
1054
1055         else
1056            if Present (Parameter_Specifications (Def)) then
1057               Param := First (Parameter_Specifications (Def));
1058               while Present (Param) loop
1059                  Check_For_Premature_Usage (Parameter_Type (Param));
1060                  Param := Next (Param);
1061               end loop;
1062            end if;
1063
1064            if Nkind (Def) = N_Access_Function_Definition then
1065               Check_For_Premature_Usage (Result_Definition (Def));
1066            end if;
1067         end if;
1068      end Check_For_Premature_Usage;
1069
1070      --  Local variables
1071
1072      Formals    : constant List_Id := Parameter_Specifications (T_Def);
1073      Formal     : Entity_Id;
1074      D_Ityp     : Node_Id;
1075      Desig_Type : constant Entity_Id :=
1076                     Create_Itype (E_Subprogram_Type, Parent (T_Def));
1077
1078   --  Start of processing for Access_Subprogram_Declaration
1079
1080   begin
1081      Check_SPARK_05_Restriction ("access type is not allowed", T_Def);
1082
1083      --  Associate the Itype node with the inner full-type declaration or
1084      --  subprogram spec or entry body. This is required to handle nested
1085      --  anonymous declarations. For example:
1086
1087      --      procedure P
1088      --       (X : access procedure
1089      --                     (Y : access procedure
1090      --                                   (Z : access T)))
1091
1092      D_Ityp := Associated_Node_For_Itype (Desig_Type);
1093      while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1094                                   N_Private_Type_Declaration,
1095                                   N_Private_Extension_Declaration,
1096                                   N_Procedure_Specification,
1097                                   N_Function_Specification,
1098                                   N_Entry_Body)
1099
1100                   or else
1101                 Nkind_In (D_Ityp, N_Object_Declaration,
1102                                   N_Object_Renaming_Declaration,
1103                                   N_Formal_Object_Declaration,
1104                                   N_Formal_Type_Declaration,
1105                                   N_Task_Type_Declaration,
1106                                   N_Protected_Type_Declaration))
1107      loop
1108         D_Ityp := Parent (D_Ityp);
1109         pragma Assert (D_Ityp /= Empty);
1110      end loop;
1111
1112      Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1113
1114      if Nkind_In (D_Ityp, N_Procedure_Specification,
1115                           N_Function_Specification)
1116      then
1117         Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1118
1119      elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1120                              N_Object_Declaration,
1121                              N_Object_Renaming_Declaration,
1122                              N_Formal_Type_Declaration)
1123      then
1124         Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1125      end if;
1126
1127      if Nkind (T_Def) = N_Access_Function_Definition then
1128         if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1129            declare
1130               Acc : constant Node_Id := Result_Definition (T_Def);
1131
1132            begin
1133               if Present (Access_To_Subprogram_Definition (Acc))
1134                 and then
1135                   Protected_Present (Access_To_Subprogram_Definition (Acc))
1136               then
1137                  Set_Etype
1138                    (Desig_Type,
1139                       Replace_Anonymous_Access_To_Protected_Subprogram
1140                         (T_Def));
1141
1142               else
1143                  Set_Etype
1144                    (Desig_Type,
1145                       Access_Definition (T_Def, Result_Definition (T_Def)));
1146               end if;
1147            end;
1148
1149         else
1150            Analyze (Result_Definition (T_Def));
1151
1152            declare
1153               Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1154
1155            begin
1156               --  If a null exclusion is imposed on the result type, then
1157               --  create a null-excluding itype (an access subtype) and use
1158               --  it as the function's Etype.
1159
1160               if Is_Access_Type (Typ)
1161                 and then Null_Exclusion_In_Return_Present (T_Def)
1162               then
1163                  Set_Etype  (Desig_Type,
1164                    Create_Null_Excluding_Itype
1165                      (T           => Typ,
1166                       Related_Nod => T_Def,
1167                       Scope_Id    => Current_Scope));
1168
1169               else
1170                  if From_Limited_With (Typ) then
1171
1172                     --  AI05-151: Incomplete types are allowed in all basic
1173                     --  declarations, including access to subprograms.
1174
1175                     if Ada_Version >= Ada_2012 then
1176                        null;
1177
1178                     else
1179                        Error_Msg_NE
1180                         ("illegal use of incomplete type&",
1181                          Result_Definition (T_Def), Typ);
1182                     end if;
1183
1184                  elsif Ekind (Current_Scope) = E_Package
1185                    and then In_Private_Part (Current_Scope)
1186                  then
1187                     if Ekind (Typ) = E_Incomplete_Type then
1188                        Append_Elmt (Desig_Type, Private_Dependents (Typ));
1189
1190                     elsif Is_Class_Wide_Type (Typ)
1191                       and then Ekind (Etype (Typ)) = E_Incomplete_Type
1192                     then
1193                        Append_Elmt
1194                          (Desig_Type, Private_Dependents (Etype (Typ)));
1195                     end if;
1196                  end if;
1197
1198                  Set_Etype (Desig_Type, Typ);
1199               end if;
1200            end;
1201         end if;
1202
1203         if not (Is_Type (Etype (Desig_Type))) then
1204            Error_Msg_N
1205              ("expect type in function specification",
1206               Result_Definition (T_Def));
1207         end if;
1208
1209      else
1210         Set_Etype (Desig_Type, Standard_Void_Type);
1211      end if;
1212
1213      if Present (Formals) then
1214         Push_Scope (Desig_Type);
1215
1216         --  Some special tests here. These special tests can be removed
1217         --  if and when Itypes always have proper parent pointers to their
1218         --  declarations???
1219
1220         --  Special test 1) Link defining_identifier of formals. Required by
1221         --  First_Formal to provide its functionality.
1222
1223         declare
1224            F : Node_Id;
1225
1226         begin
1227            F := First (Formals);
1228
1229            --  In ASIS mode, the access_to_subprogram may be analyzed twice,
1230            --  when it is part of an unconstrained type and subtype expansion
1231            --  is disabled. To avoid back-end problems with shared profiles,
1232            --  use previous subprogram type as the designated type, and then
1233            --  remove scope added above.
1234
1235            if ASIS_Mode and then Present (Scope (Defining_Identifier (F)))
1236            then
1237               Set_Etype                    (T_Name, T_Name);
1238               Init_Size_Align              (T_Name);
1239               Set_Directly_Designated_Type (T_Name,
1240                 Scope (Defining_Identifier (F)));
1241               End_Scope;
1242               return;
1243            end if;
1244
1245            while Present (F) loop
1246               if No (Parent (Defining_Identifier (F))) then
1247                  Set_Parent (Defining_Identifier (F), F);
1248               end if;
1249
1250               Next (F);
1251            end loop;
1252         end;
1253
1254         Process_Formals (Formals, Parent (T_Def));
1255
1256         --  Special test 2) End_Scope requires that the parent pointer be set
1257         --  to something reasonable, but Itypes don't have parent pointers. So
1258         --  we set it and then unset it ???
1259
1260         Set_Parent (Desig_Type, T_Name);
1261         End_Scope;
1262         Set_Parent (Desig_Type, Empty);
1263      end if;
1264
1265      --  Check for premature usage of the type being defined
1266
1267      Check_For_Premature_Usage (T_Def);
1268
1269      --  The return type and/or any parameter type may be incomplete. Mark the
1270      --  subprogram_type as depending on the incomplete type, so that it can
1271      --  be updated when the full type declaration is seen. This only applies
1272      --  to incomplete types declared in some enclosing scope, not to limited
1273      --  views from other packages.
1274
1275      --  Prior to Ada 2012, access to functions can only have in_parameters.
1276
1277      if Present (Formals) then
1278         Formal := First_Formal (Desig_Type);
1279         while Present (Formal) loop
1280            if Ekind (Formal) /= E_In_Parameter
1281              and then Nkind (T_Def) = N_Access_Function_Definition
1282              and then Ada_Version < Ada_2012
1283            then
1284               Error_Msg_N ("functions can only have IN parameters", Formal);
1285            end if;
1286
1287            if Ekind (Etype (Formal)) = E_Incomplete_Type
1288              and then In_Open_Scopes (Scope (Etype (Formal)))
1289            then
1290               Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1291               Set_Has_Delayed_Freeze (Desig_Type);
1292            end if;
1293
1294            Next_Formal (Formal);
1295         end loop;
1296      end if;
1297
1298      --  Check whether an indirect call without actuals may be possible. This
1299      --  is used when resolving calls whose result is then indexed.
1300
1301      May_Need_Actuals (Desig_Type);
1302
1303      --  If the return type is incomplete, this is legal as long as the type
1304      --  is declared in the current scope and will be completed in it (rather
1305      --  than being part of limited view).
1306
1307      if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1308        and then not Has_Delayed_Freeze (Desig_Type)
1309        and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1310      then
1311         Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1312         Set_Has_Delayed_Freeze (Desig_Type);
1313      end if;
1314
1315      Check_Delayed_Subprogram (Desig_Type);
1316
1317      if Protected_Present (T_Def) then
1318         Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1319         Set_Convention (Desig_Type, Convention_Protected);
1320      else
1321         Set_Ekind (T_Name, E_Access_Subprogram_Type);
1322      end if;
1323
1324      Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1325
1326      Set_Etype                    (T_Name, T_Name);
1327      Init_Size_Align              (T_Name);
1328      Set_Directly_Designated_Type (T_Name, Desig_Type);
1329
1330      Generate_Reference_To_Formals (T_Name);
1331
1332      --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1333
1334      Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1335
1336      Check_Restriction (No_Access_Subprograms, T_Def);
1337   end Access_Subprogram_Declaration;
1338
1339   ----------------------------
1340   -- Access_Type_Declaration --
1341   ----------------------------
1342
1343   procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1344      P : constant Node_Id := Parent (Def);
1345      S : constant Node_Id := Subtype_Indication (Def);
1346
1347      Full_Desig : Entity_Id;
1348
1349   begin
1350      Check_SPARK_05_Restriction ("access type is not allowed", Def);
1351
1352      --  Check for permissible use of incomplete type
1353
1354      if Nkind (S) /= N_Subtype_Indication then
1355         Analyze (S);
1356
1357         if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1358            Set_Directly_Designated_Type (T, Entity (S));
1359
1360            --  If the designated type is a limited view, we cannot tell if
1361            --  the full view contains tasks, and there is no way to handle
1362            --  that full view in a client. We create a master entity for the
1363            --  scope, which will be used when a client determines that one
1364            --  is needed.
1365
1366            if From_Limited_With (Entity (S))
1367              and then not Is_Class_Wide_Type (Entity (S))
1368            then
1369               Set_Ekind (T, E_Access_Type);
1370               Build_Master_Entity (T);
1371               Build_Master_Renaming (T);
1372            end if;
1373
1374         else
1375            Set_Directly_Designated_Type (T, Process_Subtype (S, P, T, 'P'));
1376         end if;
1377
1378         --  If the access definition is of the form: ACCESS NOT NULL ..
1379         --  the subtype indication must be of an access type. Create
1380         --  a null-excluding subtype of it.
1381
1382         if Null_Excluding_Subtype (Def) then
1383            if not Is_Access_Type (Entity (S)) then
1384               Error_Msg_N ("null exclusion must apply to access type", Def);
1385
1386            else
1387               declare
1388                  Loc  : constant Source_Ptr := Sloc (S);
1389                  Decl : Node_Id;
1390                  Nam  : constant Entity_Id := Make_Temporary (Loc, 'S');
1391
1392               begin
1393                  Decl :=
1394                    Make_Subtype_Declaration (Loc,
1395                      Defining_Identifier => Nam,
1396                      Subtype_Indication  =>
1397                        New_Occurrence_Of (Entity (S), Loc));
1398                  Set_Null_Exclusion_Present (Decl);
1399                  Insert_Before (Parent (Def), Decl);
1400                  Analyze (Decl);
1401                  Set_Entity (S, Nam);
1402               end;
1403            end if;
1404         end if;
1405
1406      else
1407         Set_Directly_Designated_Type (T,
1408           Process_Subtype (S, P, T, 'P'));
1409      end if;
1410
1411      if All_Present (Def) or Constant_Present (Def) then
1412         Set_Ekind (T, E_General_Access_Type);
1413      else
1414         Set_Ekind (T, E_Access_Type);
1415      end if;
1416
1417      Full_Desig := Designated_Type (T);
1418
1419      if Base_Type (Full_Desig) = T then
1420         Error_Msg_N ("access type cannot designate itself", S);
1421
1422      --  In Ada 2005, the type may have a limited view through some unit in
1423      --  its own context, allowing the following circularity that cannot be
1424      --  detected earlier.
1425
1426      elsif Is_Class_Wide_Type (Full_Desig) and then Etype (Full_Desig) = T
1427      then
1428         Error_Msg_N
1429           ("access type cannot designate its own classwide type", S);
1430
1431         --  Clean up indication of tagged status to prevent cascaded errors
1432
1433         Set_Is_Tagged_Type (T, False);
1434      end if;
1435
1436      Set_Etype (T, T);
1437
1438      --  If the type has appeared already in a with_type clause, it is frozen
1439      --  and the pointer size is already set. Else, initialize.
1440
1441      if not From_Limited_With (T) then
1442         Init_Size_Align (T);
1443      end if;
1444
1445      --  Note that Has_Task is always false, since the access type itself
1446      --  is not a task type. See Einfo for more description on this point.
1447      --  Exactly the same consideration applies to Has_Controlled_Component
1448      --  and to Has_Protected.
1449
1450      Set_Has_Task                 (T, False);
1451      Set_Has_Controlled_Component (T, False);
1452      Set_Has_Protected            (T, False);
1453
1454      --  Initialize field Finalization_Master explicitly to Empty, to avoid
1455      --  problems where an incomplete view of this entity has been previously
1456      --  established by a limited with and an overlaid version of this field
1457      --  (Stored_Constraint) was initialized for the incomplete view.
1458
1459      --  This reset is performed in most cases except where the access type
1460      --  has been created for the purposes of allocating or deallocating a
1461      --  build-in-place object. Such access types have explicitly set pools
1462      --  and finalization masters.
1463
1464      if No (Associated_Storage_Pool (T)) then
1465         Set_Finalization_Master (T, Empty);
1466      end if;
1467
1468      --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1469      --  attributes
1470
1471      Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1472      Set_Is_Access_Constant (T, Constant_Present (Def));
1473   end Access_Type_Declaration;
1474
1475   ----------------------------------
1476   -- Add_Interface_Tag_Components --
1477   ----------------------------------
1478
1479   procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1480      Loc      : constant Source_Ptr := Sloc (N);
1481      L        : List_Id;
1482      Last_Tag : Node_Id;
1483
1484      procedure Add_Tag (Iface : Entity_Id);
1485      --  Add tag for one of the progenitor interfaces
1486
1487      -------------
1488      -- Add_Tag --
1489      -------------
1490
1491      procedure Add_Tag (Iface : Entity_Id) is
1492         Decl   : Node_Id;
1493         Def    : Node_Id;
1494         Tag    : Entity_Id;
1495         Offset : Entity_Id;
1496
1497      begin
1498         pragma Assert (Is_Tagged_Type (Iface) and then Is_Interface (Iface));
1499
1500         --  This is a reasonable place to propagate predicates
1501
1502         if Has_Predicates (Iface) then
1503            Set_Has_Predicates (Typ);
1504         end if;
1505
1506         Def :=
1507           Make_Component_Definition (Loc,
1508             Aliased_Present    => True,
1509             Subtype_Indication =>
1510               New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1511
1512         Tag := Make_Temporary (Loc, 'V');
1513
1514         Decl :=
1515           Make_Component_Declaration (Loc,
1516             Defining_Identifier  => Tag,
1517             Component_Definition => Def);
1518
1519         Analyze_Component_Declaration (Decl);
1520
1521         Set_Analyzed (Decl);
1522         Set_Ekind               (Tag, E_Component);
1523         Set_Is_Tag              (Tag);
1524         Set_Is_Aliased          (Tag);
1525         Set_Related_Type        (Tag, Iface);
1526         Init_Component_Location (Tag);
1527
1528         pragma Assert (Is_Frozen (Iface));
1529
1530         Set_DT_Entry_Count    (Tag,
1531           DT_Entry_Count (First_Entity (Iface)));
1532
1533         if No (Last_Tag) then
1534            Prepend (Decl, L);
1535         else
1536            Insert_After (Last_Tag, Decl);
1537         end if;
1538
1539         Last_Tag := Decl;
1540
1541         --  If the ancestor has discriminants we need to give special support
1542         --  to store the offset_to_top value of the secondary dispatch tables.
1543         --  For this purpose we add a supplementary component just after the
1544         --  field that contains the tag associated with each secondary DT.
1545
1546         if Typ /= Etype (Typ) and then Has_Discriminants (Etype (Typ)) then
1547            Def :=
1548              Make_Component_Definition (Loc,
1549                Subtype_Indication =>
1550                  New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1551
1552            Offset := Make_Temporary (Loc, 'V');
1553
1554            Decl :=
1555              Make_Component_Declaration (Loc,
1556                Defining_Identifier  => Offset,
1557                Component_Definition => Def);
1558
1559            Analyze_Component_Declaration (Decl);
1560
1561            Set_Analyzed (Decl);
1562            Set_Ekind               (Offset, E_Component);
1563            Set_Is_Aliased          (Offset);
1564            Set_Related_Type        (Offset, Iface);
1565            Init_Component_Location (Offset);
1566            Insert_After (Last_Tag, Decl);
1567            Last_Tag := Decl;
1568         end if;
1569      end Add_Tag;
1570
1571      --  Local variables
1572
1573      Elmt : Elmt_Id;
1574      Ext  : Node_Id;
1575      Comp : Node_Id;
1576
1577   --  Start of processing for Add_Interface_Tag_Components
1578
1579   begin
1580      if not RTE_Available (RE_Interface_Tag) then
1581         Error_Msg
1582           ("(Ada 2005) interface types not supported by this run-time!",
1583            Sloc (N));
1584         return;
1585      end if;
1586
1587      if Ekind (Typ) /= E_Record_Type
1588        or else (Is_Concurrent_Record_Type (Typ)
1589                  and then Is_Empty_List (Abstract_Interface_List (Typ)))
1590        or else (not Is_Concurrent_Record_Type (Typ)
1591                  and then No (Interfaces (Typ))
1592                  and then Is_Empty_Elmt_List (Interfaces (Typ)))
1593      then
1594         return;
1595      end if;
1596
1597      --  Find the current last tag
1598
1599      if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1600         Ext := Record_Extension_Part (Type_Definition (N));
1601      else
1602         pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1603         Ext := Type_Definition (N);
1604      end if;
1605
1606      Last_Tag := Empty;
1607
1608      if not (Present (Component_List (Ext))) then
1609         Set_Null_Present (Ext, False);
1610         L := New_List;
1611         Set_Component_List (Ext,
1612           Make_Component_List (Loc,
1613             Component_Items => L,
1614             Null_Present => False));
1615      else
1616         if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1617            L := Component_Items
1618                   (Component_List
1619                     (Record_Extension_Part
1620                       (Type_Definition (N))));
1621         else
1622            L := Component_Items
1623                   (Component_List
1624                     (Type_Definition (N)));
1625         end if;
1626
1627         --  Find the last tag component
1628
1629         Comp := First (L);
1630         while Present (Comp) loop
1631            if Nkind (Comp) = N_Component_Declaration
1632              and then Is_Tag (Defining_Identifier (Comp))
1633            then
1634               Last_Tag := Comp;
1635            end if;
1636
1637            Next (Comp);
1638         end loop;
1639      end if;
1640
1641      --  At this point L references the list of components and Last_Tag
1642      --  references the current last tag (if any). Now we add the tag
1643      --  corresponding with all the interfaces that are not implemented
1644      --  by the parent.
1645
1646      if Present (Interfaces (Typ)) then
1647         Elmt := First_Elmt (Interfaces (Typ));
1648         while Present (Elmt) loop
1649            Add_Tag (Node (Elmt));
1650            Next_Elmt (Elmt);
1651         end loop;
1652      end if;
1653   end Add_Interface_Tag_Components;
1654
1655   -------------------------------------
1656   -- Add_Internal_Interface_Entities --
1657   -------------------------------------
1658
1659   procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1660      Elmt          : Elmt_Id;
1661      Iface         : Entity_Id;
1662      Iface_Elmt    : Elmt_Id;
1663      Iface_Prim    : Entity_Id;
1664      Ifaces_List   : Elist_Id;
1665      New_Subp      : Entity_Id := Empty;
1666      Prim          : Entity_Id;
1667      Restore_Scope : Boolean := False;
1668
1669   begin
1670      pragma Assert (Ada_Version >= Ada_2005
1671        and then Is_Record_Type (Tagged_Type)
1672        and then Is_Tagged_Type (Tagged_Type)
1673        and then Has_Interfaces (Tagged_Type)
1674        and then not Is_Interface (Tagged_Type));
1675
1676      --  Ensure that the internal entities are added to the scope of the type
1677
1678      if Scope (Tagged_Type) /= Current_Scope then
1679         Push_Scope (Scope (Tagged_Type));
1680         Restore_Scope := True;
1681      end if;
1682
1683      Collect_Interfaces (Tagged_Type, Ifaces_List);
1684
1685      Iface_Elmt := First_Elmt (Ifaces_List);
1686      while Present (Iface_Elmt) loop
1687         Iface := Node (Iface_Elmt);
1688
1689         --  Originally we excluded here from this processing interfaces that
1690         --  are parents of Tagged_Type because their primitives are located
1691         --  in the primary dispatch table (and hence no auxiliary internal
1692         --  entities are required to handle secondary dispatch tables in such
1693         --  case). However, these auxiliary entities are also required to
1694         --  handle derivations of interfaces in formals of generics (see
1695         --  Derive_Subprograms).
1696
1697         Elmt := First_Elmt (Primitive_Operations (Iface));
1698         while Present (Elmt) loop
1699            Iface_Prim := Node (Elmt);
1700
1701            if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1702               Prim :=
1703                 Find_Primitive_Covering_Interface
1704                   (Tagged_Type => Tagged_Type,
1705                    Iface_Prim  => Iface_Prim);
1706
1707               if No (Prim) and then Serious_Errors_Detected > 0 then
1708                  goto Continue;
1709               end if;
1710
1711               pragma Assert (Present (Prim));
1712
1713               --  Ada 2012 (AI05-0197): If the name of the covering primitive
1714               --  differs from the name of the interface primitive then it is
1715               --  a private primitive inherited from a parent type. In such
1716               --  case, given that Tagged_Type covers the interface, the
1717               --  inherited private primitive becomes visible. For such
1718               --  purpose we add a new entity that renames the inherited
1719               --  private primitive.
1720
1721               if Chars (Prim) /= Chars (Iface_Prim) then
1722                  pragma Assert (Has_Suffix (Prim, 'P'));
1723                  Derive_Subprogram
1724                    (New_Subp     => New_Subp,
1725                     Parent_Subp  => Iface_Prim,
1726                     Derived_Type => Tagged_Type,
1727                     Parent_Type  => Iface);
1728                  Set_Alias (New_Subp, Prim);
1729                  Set_Is_Abstract_Subprogram
1730                    (New_Subp, Is_Abstract_Subprogram (Prim));
1731               end if;
1732
1733               Derive_Subprogram
1734                 (New_Subp     => New_Subp,
1735                  Parent_Subp  => Iface_Prim,
1736                  Derived_Type => Tagged_Type,
1737                  Parent_Type  => Iface);
1738
1739               --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1740               --  associated with interface types. These entities are
1741               --  only registered in the list of primitives of its
1742               --  corresponding tagged type because they are only used
1743               --  to fill the contents of the secondary dispatch tables.
1744               --  Therefore they are removed from the homonym chains.
1745
1746               Set_Is_Hidden (New_Subp);
1747               Set_Is_Internal (New_Subp);
1748               Set_Alias (New_Subp, Prim);
1749               Set_Is_Abstract_Subprogram
1750                 (New_Subp, Is_Abstract_Subprogram (Prim));
1751               Set_Interface_Alias (New_Subp, Iface_Prim);
1752
1753               --  If the returned type is an interface then propagate it to
1754               --  the returned type. Needed by the thunk to generate the code
1755               --  which displaces "this" to reference the corresponding
1756               --  secondary dispatch table in the returned object.
1757
1758               if Is_Interface (Etype (Iface_Prim)) then
1759                  Set_Etype (New_Subp, Etype (Iface_Prim));
1760               end if;
1761
1762               --  Internal entities associated with interface types are
1763               --  only registered in the list of primitives of the tagged
1764               --  type. They are only used to fill the contents of the
1765               --  secondary dispatch tables. Therefore they are not needed
1766               --  in the homonym chains.
1767
1768               Remove_Homonym (New_Subp);
1769
1770               --  Hidden entities associated with interfaces must have set
1771               --  the Has_Delay_Freeze attribute to ensure that, in case of
1772               --  locally defined tagged types (or compiling with static
1773               --  dispatch tables generation disabled) the corresponding
1774               --  entry of the secondary dispatch table is filled when
1775               --  such an entity is frozen.
1776
1777               Set_Has_Delayed_Freeze (New_Subp);
1778            end if;
1779
1780            <<Continue>>
1781            Next_Elmt (Elmt);
1782         end loop;
1783
1784         Next_Elmt (Iface_Elmt);
1785      end loop;
1786
1787      if Restore_Scope then
1788         Pop_Scope;
1789      end if;
1790   end Add_Internal_Interface_Entities;
1791
1792   -----------------------------------
1793   -- Analyze_Component_Declaration --
1794   -----------------------------------
1795
1796   procedure Analyze_Component_Declaration (N : Node_Id) is
1797      Id  : constant Entity_Id := Defining_Identifier (N);
1798      E   : constant Node_Id   := Expression (N);
1799      Typ : constant Node_Id   :=
1800              Subtype_Indication (Component_Definition (N));
1801      T   : Entity_Id;
1802      P   : Entity_Id;
1803
1804      function Contains_POC (Constr : Node_Id) return Boolean;
1805      --  Determines whether a constraint uses the discriminant of a record
1806      --  type thus becoming a per-object constraint (POC).
1807
1808      function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1809      --  Typ is the type of the current component, check whether this type is
1810      --  a limited type. Used to validate declaration against that of
1811      --  enclosing record.
1812
1813      ------------------
1814      -- Contains_POC --
1815      ------------------
1816
1817      function Contains_POC (Constr : Node_Id) return Boolean is
1818      begin
1819         --  Prevent cascaded errors
1820
1821         if Error_Posted (Constr) then
1822            return False;
1823         end if;
1824
1825         case Nkind (Constr) is
1826            when N_Attribute_Reference =>
1827               return Attribute_Name (Constr) = Name_Access
1828                 and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1829
1830            when N_Discriminant_Association =>
1831               return Denotes_Discriminant (Expression (Constr));
1832
1833            when N_Identifier =>
1834               return Denotes_Discriminant (Constr);
1835
1836            when N_Index_Or_Discriminant_Constraint =>
1837               declare
1838                  IDC : Node_Id;
1839
1840               begin
1841                  IDC := First (Constraints (Constr));
1842                  while Present (IDC) loop
1843
1844                     --  One per-object constraint is sufficient
1845
1846                     if Contains_POC (IDC) then
1847                        return True;
1848                     end if;
1849
1850                     Next (IDC);
1851                  end loop;
1852
1853                  return False;
1854               end;
1855
1856            when N_Range =>
1857               return Denotes_Discriminant (Low_Bound (Constr))
1858                        or else
1859                      Denotes_Discriminant (High_Bound (Constr));
1860
1861            when N_Range_Constraint =>
1862               return Denotes_Discriminant (Range_Expression (Constr));
1863
1864            when others =>
1865               return False;
1866
1867         end case;
1868      end Contains_POC;
1869
1870      ----------------------
1871      -- Is_Known_Limited --
1872      ----------------------
1873
1874      function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1875         P : constant Entity_Id := Etype (Typ);
1876         R : constant Entity_Id := Root_Type (Typ);
1877
1878      begin
1879         if Is_Limited_Record (Typ) then
1880            return True;
1881
1882         --  If the root type is limited (and not a limited interface)
1883         --  so is the current type
1884
1885         elsif Is_Limited_Record (R)
1886           and then (not Is_Interface (R) or else not Is_Limited_Interface (R))
1887         then
1888            return True;
1889
1890         --  Else the type may have a limited interface progenitor, but a
1891         --  limited record parent.
1892
1893         elsif R /= P and then Is_Limited_Record (P) then
1894            return True;
1895
1896         else
1897            return False;
1898         end if;
1899      end Is_Known_Limited;
1900
1901   --  Start of processing for Analyze_Component_Declaration
1902
1903   begin
1904      Generate_Definition (Id);
1905      Enter_Name (Id);
1906
1907      if Present (Typ) then
1908         T := Find_Type_Of_Object
1909                (Subtype_Indication (Component_Definition (N)), N);
1910
1911         if not Nkind_In (Typ, N_Identifier, N_Expanded_Name) then
1912            Check_SPARK_05_Restriction ("subtype mark required", Typ);
1913         end if;
1914
1915      --  Ada 2005 (AI-230): Access Definition case
1916
1917      else
1918         pragma Assert (Present
1919                          (Access_Definition (Component_Definition (N))));
1920
1921         T := Access_Definition
1922                (Related_Nod => N,
1923                 N => Access_Definition (Component_Definition (N)));
1924         Set_Is_Local_Anonymous_Access (T);
1925
1926         --  Ada 2005 (AI-254)
1927
1928         if Present (Access_To_Subprogram_Definition
1929                      (Access_Definition (Component_Definition (N))))
1930           and then Protected_Present (Access_To_Subprogram_Definition
1931                                        (Access_Definition
1932                                          (Component_Definition (N))))
1933         then
1934            T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1935         end if;
1936      end if;
1937
1938      --  If the subtype is a constrained subtype of the enclosing record,
1939      --  (which must have a partial view) the back-end does not properly
1940      --  handle the recursion. Rewrite the component declaration with an
1941      --  explicit subtype indication, which is acceptable to Gigi. We can copy
1942      --  the tree directly because side effects have already been removed from
1943      --  discriminant constraints.
1944
1945      if Ekind (T) = E_Access_Subtype
1946        and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1947        and then Comes_From_Source (T)
1948        and then Nkind (Parent (T)) = N_Subtype_Declaration
1949        and then Etype (Directly_Designated_Type (T)) = Current_Scope
1950      then
1951         Rewrite
1952           (Subtype_Indication (Component_Definition (N)),
1953             New_Copy_Tree (Subtype_Indication (Parent (T))));
1954         T := Find_Type_Of_Object
1955                 (Subtype_Indication (Component_Definition (N)), N);
1956      end if;
1957
1958      --  If the component declaration includes a default expression, then we
1959      --  check that the component is not of a limited type (RM 3.7(5)),
1960      --  and do the special preanalysis of the expression (see section on
1961      --  "Handling of Default and Per-Object Expressions" in the spec of
1962      --  package Sem).
1963
1964      if Present (E) then
1965         Check_SPARK_05_Restriction ("default expression is not allowed", E);
1966         Preanalyze_Default_Expression (E, T);
1967         Check_Initialization (T, E);
1968
1969         if Ada_Version >= Ada_2005
1970           and then Ekind (T) = E_Anonymous_Access_Type
1971           and then Etype (E) /= Any_Type
1972         then
1973            --  Check RM 3.9.2(9): "if the expected type for an expression is
1974            --  an anonymous access-to-specific tagged type, then the object
1975            --  designated by the expression shall not be dynamically tagged
1976            --  unless it is a controlling operand in a call on a dispatching
1977            --  operation"
1978
1979            if Is_Tagged_Type (Directly_Designated_Type (T))
1980              and then
1981                Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1982              and then
1983                Ekind (Directly_Designated_Type (Etype (E))) =
1984                  E_Class_Wide_Type
1985            then
1986               Error_Msg_N
1987                 ("access to specific tagged type required (RM 3.9.2(9))", E);
1988            end if;
1989
1990            --  (Ada 2005: AI-230): Accessibility check for anonymous
1991            --  components
1992
1993            if Type_Access_Level (Etype (E)) >
1994               Deepest_Type_Access_Level (T)
1995            then
1996               Error_Msg_N
1997                 ("expression has deeper access level than component " &
1998                  "(RM 3.10.2 (12.2))", E);
1999            end if;
2000
2001            --  The initialization expression is a reference to an access
2002            --  discriminant. The type of the discriminant is always deeper
2003            --  than any access type.
2004
2005            if Ekind (Etype (E)) = E_Anonymous_Access_Type
2006              and then Is_Entity_Name (E)
2007              and then Ekind (Entity (E)) = E_In_Parameter
2008              and then Present (Discriminal_Link (Entity (E)))
2009            then
2010               Error_Msg_N
2011                 ("discriminant has deeper accessibility level than target",
2012                  E);
2013            end if;
2014         end if;
2015      end if;
2016
2017      --  The parent type may be a private view with unknown discriminants,
2018      --  and thus unconstrained. Regular components must be constrained.
2019
2020      if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
2021         if Is_Class_Wide_Type (T) then
2022            Error_Msg_N
2023               ("class-wide subtype with unknown discriminants" &
2024                 " in component declaration",
2025                 Subtype_Indication (Component_Definition (N)));
2026         else
2027            Error_Msg_N
2028              ("unconstrained subtype in component declaration",
2029               Subtype_Indication (Component_Definition (N)));
2030         end if;
2031
2032      --  Components cannot be abstract, except for the special case of
2033      --  the _Parent field (case of extending an abstract tagged type)
2034
2035      elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
2036         Error_Msg_N ("type of a component cannot be abstract", N);
2037      end if;
2038
2039      Set_Etype (Id, T);
2040      Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
2041
2042      --  The component declaration may have a per-object constraint, set
2043      --  the appropriate flag in the defining identifier of the subtype.
2044
2045      if Present (Subtype_Indication (Component_Definition (N))) then
2046         declare
2047            Sindic : constant Node_Id :=
2048                       Subtype_Indication (Component_Definition (N));
2049         begin
2050            if Nkind (Sindic) = N_Subtype_Indication
2051              and then Present (Constraint (Sindic))
2052              and then Contains_POC (Constraint (Sindic))
2053            then
2054               Set_Has_Per_Object_Constraint (Id);
2055            end if;
2056         end;
2057      end if;
2058
2059      --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2060      --  out some static checks.
2061
2062      if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (T) then
2063         Null_Exclusion_Static_Checks (N);
2064      end if;
2065
2066      --  If this component is private (or depends on a private type), flag the
2067      --  record type to indicate that some operations are not available.
2068
2069      P := Private_Component (T);
2070
2071      if Present (P) then
2072
2073         --  Check for circular definitions
2074
2075         if P = Any_Type then
2076            Set_Etype (Id, Any_Type);
2077
2078         --  There is a gap in the visibility of operations only if the
2079         --  component type is not defined in the scope of the record type.
2080
2081         elsif Scope (P) = Scope (Current_Scope) then
2082            null;
2083
2084         elsif Is_Limited_Type (P) then
2085            Set_Is_Limited_Composite (Current_Scope);
2086
2087         else
2088            Set_Is_Private_Composite (Current_Scope);
2089         end if;
2090      end if;
2091
2092      if P /= Any_Type
2093        and then Is_Limited_Type (T)
2094        and then Chars (Id) /= Name_uParent
2095        and then Is_Tagged_Type (Current_Scope)
2096      then
2097         if Is_Derived_Type (Current_Scope)
2098           and then not Is_Known_Limited (Current_Scope)
2099         then
2100            Error_Msg_N
2101              ("extension of nonlimited type cannot have limited components",
2102               N);
2103
2104            if Is_Interface (Root_Type (Current_Scope)) then
2105               Error_Msg_N
2106                 ("\limitedness is not inherited from limited interface", N);
2107               Error_Msg_N ("\add LIMITED to type indication", N);
2108            end if;
2109
2110            Explain_Limited_Type (T, N);
2111            Set_Etype (Id, Any_Type);
2112            Set_Is_Limited_Composite (Current_Scope, False);
2113
2114         elsif not Is_Derived_Type (Current_Scope)
2115           and then not Is_Limited_Record (Current_Scope)
2116           and then not Is_Concurrent_Type (Current_Scope)
2117         then
2118            Error_Msg_N
2119              ("nonlimited tagged type cannot have limited components", N);
2120            Explain_Limited_Type (T, N);
2121            Set_Etype (Id, Any_Type);
2122            Set_Is_Limited_Composite (Current_Scope, False);
2123         end if;
2124      end if;
2125
2126      Set_Original_Record_Component (Id, Id);
2127
2128      if Has_Aspects (N) then
2129         Analyze_Aspect_Specifications (N, Id);
2130      end if;
2131
2132      Analyze_Dimension (N);
2133   end Analyze_Component_Declaration;
2134
2135   --------------------------
2136   -- Analyze_Declarations --
2137   --------------------------
2138
2139   procedure Analyze_Declarations (L : List_Id) is
2140      Decl : Node_Id;
2141
2142      procedure Adjust_Decl;
2143      --  Adjust Decl not to include implicit label declarations, since these
2144      --  have strange Sloc values that result in elaboration check problems.
2145      --  (They have the sloc of the label as found in the source, and that
2146      --  is ahead of the current declarative part).
2147
2148      procedure Handle_Late_Controlled_Primitive (Body_Decl : Node_Id);
2149      --  Determine whether Body_Decl denotes the body of a late controlled
2150      --  primitive (either Initialize, Adjust or Finalize). If this is the
2151      --  case, add a proper spec if the body lacks one. The spec is inserted
2152      --  before Body_Decl and immedately analyzed.
2153
2154      procedure Remove_Visible_Refinements (Spec_Id : Entity_Id);
2155      --  Spec_Id is the entity of a package that may define abstract states.
2156      --  If the states have visible refinement, remove the visibility of each
2157      --  constituent at the end of the package body declarations.
2158
2159      -----------------
2160      -- Adjust_Decl --
2161      -----------------
2162
2163      procedure Adjust_Decl is
2164      begin
2165         while Present (Prev (Decl))
2166           and then Nkind (Decl) = N_Implicit_Label_Declaration
2167         loop
2168            Prev (Decl);
2169         end loop;
2170      end Adjust_Decl;
2171
2172      --------------------------------------
2173      -- Handle_Late_Controlled_Primitive --
2174      --------------------------------------
2175
2176      procedure Handle_Late_Controlled_Primitive (Body_Decl : Node_Id) is
2177         Body_Spec : constant Node_Id    := Specification (Body_Decl);
2178         Body_Id   : constant Entity_Id  := Defining_Entity (Body_Spec);
2179         Loc       : constant Source_Ptr := Sloc (Body_Id);
2180         Params    : constant List_Id    :=
2181                       Parameter_Specifications (Body_Spec);
2182         Spec      : Node_Id;
2183         Spec_Id   : Entity_Id;
2184         Typ       : Node_Id;
2185
2186      begin
2187         --  Consider only procedure bodies whose name matches one of the three
2188         --  controlled primitives.
2189
2190         if Nkind (Body_Spec) /= N_Procedure_Specification
2191           or else not Nam_In (Chars (Body_Id), Name_Adjust,
2192                                                Name_Finalize,
2193                                                Name_Initialize)
2194         then
2195            return;
2196
2197         --  A controlled primitive must have exactly one formal which is not
2198         --  an anonymous access type.
2199
2200         elsif List_Length (Params) /= 1 then
2201            return;
2202         end if;
2203
2204         Typ := Parameter_Type (First (Params));
2205
2206         if Nkind (Typ) = N_Access_Definition then
2207            return;
2208         end if;
2209
2210         Find_Type (Typ);
2211
2212         --  The type of the formal must be derived from [Limited_]Controlled
2213
2214         if not Is_Controlled (Entity (Typ)) then
2215            return;
2216         end if;
2217
2218         --  Check whether a specification exists for this body. We do not
2219         --  analyze the spec of the body in full, because it will be analyzed
2220         --  again when the body is properly analyzed, and we cannot create
2221         --  duplicate entries in the formals chain. We look for an explicit
2222         --  specification because the body may be an overriding operation and
2223         --  an inherited spec may be present.
2224
2225         Spec_Id := Current_Entity (Body_Id);
2226
2227         while Present (Spec_Id) loop
2228            if Ekind_In (Spec_Id, E_Procedure, E_Generic_Procedure)
2229              and then Scope (Spec_Id) = Current_Scope
2230              and then Present (First_Formal (Spec_Id))
2231              and then No (Next_Formal (First_Formal (Spec_Id)))
2232              and then Etype (First_Formal (Spec_Id)) = Entity (Typ)
2233              and then Comes_From_Source (Spec_Id)
2234            then
2235               return;
2236            end if;
2237
2238            Spec_Id := Homonym (Spec_Id);
2239         end loop;
2240
2241         --  At this point the body is known to be a late controlled primitive.
2242         --  Generate a matching spec and insert it before the body. Note the
2243         --  use of Copy_Separate_Tree - we want an entirely separate semantic
2244         --  tree in this case.
2245
2246         Spec := Copy_Separate_Tree (Body_Spec);
2247
2248         --  Ensure that the subprogram declaration does not inherit the null
2249         --  indicator from the body as we now have a proper spec/body pair.
2250
2251         Set_Null_Present (Spec, False);
2252
2253         Insert_Before_And_Analyze (Body_Decl,
2254           Make_Subprogram_Declaration (Loc, Specification => Spec));
2255      end Handle_Late_Controlled_Primitive;
2256
2257      --------------------------------
2258      -- Remove_Visible_Refinements --
2259      --------------------------------
2260
2261      procedure Remove_Visible_Refinements (Spec_Id : Entity_Id) is
2262         State_Elmt : Elmt_Id;
2263      begin
2264         if Present (Abstract_States (Spec_Id)) then
2265            State_Elmt := First_Elmt (Abstract_States (Spec_Id));
2266            while Present (State_Elmt) loop
2267               Set_Has_Visible_Refinement (Node (State_Elmt), False);
2268               Next_Elmt (State_Elmt);
2269            end loop;
2270         end if;
2271      end Remove_Visible_Refinements;
2272
2273      --  Local variables
2274
2275      Context     : Node_Id;
2276      Freeze_From : Entity_Id := Empty;
2277      Next_Decl   : Node_Id;
2278      Spec_Id     : Entity_Id;
2279
2280      Body_Seen : Boolean := False;
2281      --  Flag set when the first body [stub] is encountered
2282
2283      In_Package_Body : Boolean := False;
2284      --  Flag set when the current declaration list belongs to a package body
2285
2286   --  Start of processing for Analyze_Declarations
2287
2288   begin
2289      if Restriction_Check_Required (SPARK_05) then
2290         Check_Later_Vs_Basic_Declarations (L, During_Parsing => False);
2291      end if;
2292
2293      Decl := First (L);
2294      while Present (Decl) loop
2295
2296         --  Package spec cannot contain a package declaration in SPARK
2297
2298         if Nkind (Decl) = N_Package_Declaration
2299           and then Nkind (Parent (L)) = N_Package_Specification
2300         then
2301            Check_SPARK_05_Restriction
2302              ("package specification cannot contain a package declaration",
2303               Decl);
2304         end if;
2305
2306         --  Complete analysis of declaration
2307
2308         Analyze (Decl);
2309         Next_Decl := Next (Decl);
2310
2311         if No (Freeze_From) then
2312            Freeze_From := First_Entity (Current_Scope);
2313         end if;
2314
2315         --  At the end of a declarative part, freeze remaining entities
2316         --  declared in it. The end of the visible declarations of package
2317         --  specification is not the end of a declarative part if private
2318         --  declarations are present. The end of a package declaration is a
2319         --  freezing point only if it a library package. A task definition or
2320         --  protected type definition is not a freeze point either. Finally,
2321         --  we do not freeze entities in generic scopes, because there is no
2322         --  code generated for them and freeze nodes will be generated for
2323         --  the instance.
2324
2325         --  The end of a package instantiation is not a freeze point, but
2326         --  for now we make it one, because the generic body is inserted
2327         --  (currently) immediately after. Generic instantiations will not
2328         --  be a freeze point once delayed freezing of bodies is implemented.
2329         --  (This is needed in any case for early instantiations ???).
2330
2331         if No (Next_Decl) then
2332            if Nkind_In (Parent (L), N_Component_List,
2333                                     N_Task_Definition,
2334                                     N_Protected_Definition)
2335            then
2336               null;
2337
2338            elsif Nkind (Parent (L)) /= N_Package_Specification then
2339               if Nkind (Parent (L)) = N_Package_Body then
2340                  Freeze_From := First_Entity (Current_Scope);
2341               end if;
2342
2343               --  There may have been several freezing points previously,
2344               --  for example object declarations or subprogram bodies, but
2345               --  at the end of a declarative part we check freezing from
2346               --  the beginning, even though entities may already be frozen,
2347               --  in order to perform visibility checks on delayed aspects.
2348
2349               Adjust_Decl;
2350               Freeze_All (First_Entity (Current_Scope), Decl);
2351               Freeze_From := Last_Entity (Current_Scope);
2352
2353            elsif Scope (Current_Scope) /= Standard_Standard
2354              and then not Is_Child_Unit (Current_Scope)
2355              and then No (Generic_Parent (Parent (L)))
2356            then
2357               null;
2358
2359            elsif L /= Visible_Declarations (Parent (L))
2360               or else No (Private_Declarations (Parent (L)))
2361               or else Is_Empty_List (Private_Declarations (Parent (L)))
2362            then
2363               Adjust_Decl;
2364               Freeze_All (First_Entity (Current_Scope), Decl);
2365               Freeze_From := Last_Entity (Current_Scope);
2366            end if;
2367
2368         --  If next node is a body then freeze all types before the body.
2369         --  An exception occurs for some expander-generated bodies. If these
2370         --  are generated at places where in general language rules would not
2371         --  allow a freeze point, then we assume that the expander has
2372         --  explicitly checked that all required types are properly frozen,
2373         --  and we do not cause general freezing here. This special circuit
2374         --  is used when the encountered body is marked as having already
2375         --  been analyzed.
2376
2377         --  In all other cases (bodies that come from source, and expander
2378         --  generated bodies that have not been analyzed yet), freeze all
2379         --  types now. Note that in the latter case, the expander must take
2380         --  care to attach the bodies at a proper place in the tree so as to
2381         --  not cause unwanted freezing at that point.
2382
2383         elsif not Analyzed (Next_Decl) and then Is_Body (Next_Decl) then
2384
2385            --  When a controlled type is frozen, the expander generates stream
2386            --  and controlled type support routines. If the freeze is caused
2387            --  by the stand alone body of Initialize, Adjust and Finalize, the
2388            --  expander will end up using the wrong version of these routines
2389            --  as the body has not been processed yet. To remedy this, detect
2390            --  a late controlled primitive and create a proper spec for it.
2391            --  This ensures that the primitive will override its inherited
2392            --  counterpart before the freeze takes place.
2393
2394            --  If the declaration we just processed is a body, do not attempt
2395            --  to examine Next_Decl as the late primitive idiom can only apply
2396            --  to the first encountered body.
2397
2398            --  The spec of the late primitive is not generated in ASIS mode to
2399            --  ensure a consistent list of primitives that indicates the true
2400            --  semantic structure of the program (which is not relevant when
2401            --  generating executable code.
2402
2403            --  ??? a cleaner approach may be possible and/or this solution
2404            --  could be extended to general-purpose late primitives, TBD.
2405
2406            if not ASIS_Mode and then not Body_Seen and then not Is_Body (Decl)
2407            then
2408               Body_Seen := True;
2409
2410               if Nkind (Next_Decl) = N_Subprogram_Body then
2411                  Handle_Late_Controlled_Primitive (Next_Decl);
2412               end if;
2413            end if;
2414
2415            Adjust_Decl;
2416            Freeze_All (Freeze_From, Decl);
2417            Freeze_From := Last_Entity (Current_Scope);
2418         end if;
2419
2420         Decl := Next_Decl;
2421      end loop;
2422
2423      --  Analyze the contracts of packages and their bodies
2424
2425      if Present (L) then
2426         Context := Parent (L);
2427
2428         if Nkind (Context) = N_Package_Specification then
2429
2430            --  When a package has private declarations, its contract must be
2431            --  analyzed at the end of the said declarations. This way both the
2432            --  analysis and freeze actions are properly synchronized in case
2433            --  of private type use within the contract.
2434
2435            if L = Private_Declarations (Context) then
2436               Analyze_Package_Contract (Defining_Entity (Context));
2437
2438               --  Build the bodies of the default initial condition procedures
2439               --  for all types subject to pragma Default_Initial_Condition.
2440               --  From a purely Ada stand point, this is a freezing activity,
2441               --  however freezing is not available under GNATprove_Mode. To
2442               --  accomodate both scenarios, the bodies are build at the end
2443               --  of private declaration analysis.
2444
2445               Build_Default_Init_Cond_Procedure_Bodies (L);
2446
2447            --  Otherwise the contract is analyzed at the end of the visible
2448            --  declarations.
2449
2450            elsif L = Visible_Declarations (Context)
2451              and then No (Private_Declarations (Context))
2452            then
2453               Analyze_Package_Contract (Defining_Entity (Context));
2454            end if;
2455
2456         elsif Nkind (Context) = N_Package_Body then
2457            In_Package_Body := True;
2458            Spec_Id := Corresponding_Spec (Context);
2459
2460            Analyze_Package_Body_Contract (Defining_Entity (Context));
2461         end if;
2462      end if;
2463
2464      --  Analyze the contracts of subprogram declarations, subprogram bodies
2465      --  and variables now due to the delayed visibility requirements of their
2466      --  aspects.
2467
2468      Decl := First (L);
2469      while Present (Decl) loop
2470         if Nkind (Decl) = N_Object_Declaration then
2471            Analyze_Object_Contract (Defining_Entity (Decl));
2472
2473         elsif Nkind_In (Decl, N_Abstract_Subprogram_Declaration,
2474                               N_Generic_Subprogram_Declaration,
2475                               N_Subprogram_Declaration)
2476         then
2477            Analyze_Subprogram_Contract (Defining_Entity (Decl));
2478
2479         elsif Nkind (Decl) = N_Subprogram_Body then
2480            Analyze_Subprogram_Body_Contract (Defining_Entity (Decl));
2481
2482         elsif Nkind (Decl) = N_Subprogram_Body_Stub then
2483            Analyze_Subprogram_Body_Stub_Contract (Defining_Entity (Decl));
2484         end if;
2485
2486         Next (Decl);
2487      end loop;
2488
2489      --  State refinements are visible upto the end the of the package body
2490      --  declarations. Hide the refinements from visibility to restore the
2491      --  original state conditions.
2492
2493      if In_Package_Body then
2494         Remove_Visible_Refinements (Spec_Id);
2495      end if;
2496   end Analyze_Declarations;
2497
2498   -----------------------------------
2499   -- Analyze_Full_Type_Declaration --
2500   -----------------------------------
2501
2502   procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2503      Def    : constant Node_Id   := Type_Definition (N);
2504      Def_Id : constant Entity_Id := Defining_Identifier (N);
2505      T      : Entity_Id;
2506      Prev   : Entity_Id;
2507
2508      Is_Remote : constant Boolean :=
2509                    (Is_Remote_Types (Current_Scope)
2510                       or else Is_Remote_Call_Interface (Current_Scope))
2511                      and then not (In_Private_Part (Current_Scope)
2512                                     or else In_Package_Body (Current_Scope));
2513
2514      procedure Check_Ops_From_Incomplete_Type;
2515      --  If there is a tagged incomplete partial view of the type, traverse
2516      --  the primitives of the incomplete view and change the type of any
2517      --  controlling formals and result to indicate the full view. The
2518      --  primitives will be added to the full type's primitive operations
2519      --  list later in Sem_Disp.Check_Operation_From_Incomplete_Type (which
2520      --  is called from Process_Incomplete_Dependents).
2521
2522      ------------------------------------
2523      -- Check_Ops_From_Incomplete_Type --
2524      ------------------------------------
2525
2526      procedure Check_Ops_From_Incomplete_Type is
2527         Elmt   : Elmt_Id;
2528         Formal : Entity_Id;
2529         Op     : Entity_Id;
2530
2531      begin
2532         if Prev /= T
2533           and then Ekind (Prev) = E_Incomplete_Type
2534           and then Is_Tagged_Type (Prev)
2535           and then Is_Tagged_Type (T)
2536         then
2537            Elmt := First_Elmt (Primitive_Operations (Prev));
2538            while Present (Elmt) loop
2539               Op := Node (Elmt);
2540
2541               Formal := First_Formal (Op);
2542               while Present (Formal) loop
2543                  if Etype (Formal) = Prev then
2544                     Set_Etype (Formal, T);
2545                  end if;
2546
2547                  Next_Formal (Formal);
2548               end loop;
2549
2550               if Etype (Op) = Prev then
2551                  Set_Etype (Op, T);
2552               end if;
2553
2554               Next_Elmt (Elmt);
2555            end loop;
2556         end if;
2557      end Check_Ops_From_Incomplete_Type;
2558
2559   --  Start of processing for Analyze_Full_Type_Declaration
2560
2561   begin
2562      Prev := Find_Type_Name (N);
2563
2564      --  The type declaration may be subject to pragma Ghost with policy
2565      --  Ignore. Set the mode now to ensure that any nodes generated during
2566      --  analysis and expansion are properly flagged as ignored Ghost.
2567
2568      Set_Ghost_Mode (N, Prev);
2569
2570      --  The full view, if present, now points to the current type. If there
2571      --  is an incomplete partial view, set a link to it, to simplify the
2572      --  retrieval of primitive operations of the type.
2573
2574      --  Ada 2005 (AI-50217): If the type was previously decorated when
2575      --  imported through a LIMITED WITH clause, it appears as incomplete
2576      --  but has no full view.
2577
2578      if Ekind (Prev) = E_Incomplete_Type
2579        and then Present (Full_View (Prev))
2580      then
2581         T := Full_View (Prev);
2582         Set_Incomplete_View (N, Parent (Prev));
2583      else
2584         T := Prev;
2585      end if;
2586
2587      Set_Is_Pure (T, Is_Pure (Current_Scope));
2588
2589      --  We set the flag Is_First_Subtype here. It is needed to set the
2590      --  corresponding flag for the Implicit class-wide-type created
2591      --  during tagged types processing.
2592
2593      Set_Is_First_Subtype (T, True);
2594
2595      --  Only composite types other than array types are allowed to have
2596      --  discriminants.
2597
2598      case Nkind (Def) is
2599
2600         --  For derived types, the rule will be checked once we've figured
2601         --  out the parent type.
2602
2603         when N_Derived_Type_Definition =>
2604            null;
2605
2606         --  For record types, discriminants are allowed, unless we are in
2607         --  SPARK.
2608
2609         when N_Record_Definition =>
2610            if Present (Discriminant_Specifications (N)) then
2611               Check_SPARK_05_Restriction
2612                 ("discriminant type is not allowed",
2613                  Defining_Identifier
2614                    (First (Discriminant_Specifications (N))));
2615            end if;
2616
2617         when others =>
2618            if Present (Discriminant_Specifications (N)) then
2619               Error_Msg_N
2620                 ("elementary or array type cannot have discriminants",
2621                  Defining_Identifier
2622                    (First (Discriminant_Specifications (N))));
2623            end if;
2624      end case;
2625
2626      --  Elaborate the type definition according to kind, and generate
2627      --  subsidiary (implicit) subtypes where needed. We skip this if it was
2628      --  already done (this happens during the reanalysis that follows a call
2629      --  to the high level optimizer).
2630
2631      if not Analyzed (T) then
2632         Set_Analyzed (T);
2633
2634         case Nkind (Def) is
2635            when N_Access_To_Subprogram_Definition =>
2636               Access_Subprogram_Declaration (T, Def);
2637
2638               --  If this is a remote access to subprogram, we must create the
2639               --  equivalent fat pointer type, and related subprograms.
2640
2641               if Is_Remote then
2642                  Process_Remote_AST_Declaration (N);
2643               end if;
2644
2645               --  Validate categorization rule against access type declaration
2646               --  usually a violation in Pure unit, Shared_Passive unit.
2647
2648               Validate_Access_Type_Declaration (T, N);
2649
2650            when N_Access_To_Object_Definition =>
2651               Access_Type_Declaration (T, Def);
2652
2653               --  Validate categorization rule against access type declaration
2654               --  usually a violation in Pure unit, Shared_Passive unit.
2655
2656               Validate_Access_Type_Declaration (T, N);
2657
2658               --  If we are in a Remote_Call_Interface package and define a
2659               --  RACW, then calling stubs and specific stream attributes
2660               --  must be added.
2661
2662               if Is_Remote
2663                 and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2664               then
2665                  Add_RACW_Features (Def_Id);
2666               end if;
2667
2668            when N_Array_Type_Definition =>
2669               Array_Type_Declaration (T, Def);
2670
2671            when N_Derived_Type_Definition =>
2672               Derived_Type_Declaration (T, N, T /= Def_Id);
2673
2674            when N_Enumeration_Type_Definition =>
2675               Enumeration_Type_Declaration (T, Def);
2676
2677            when N_Floating_Point_Definition =>
2678               Floating_Point_Type_Declaration (T, Def);
2679
2680            when N_Decimal_Fixed_Point_Definition =>
2681               Decimal_Fixed_Point_Type_Declaration (T, Def);
2682
2683            when N_Ordinary_Fixed_Point_Definition =>
2684               Ordinary_Fixed_Point_Type_Declaration (T, Def);
2685
2686            when N_Signed_Integer_Type_Definition =>
2687               Signed_Integer_Type_Declaration (T, Def);
2688
2689            when N_Modular_Type_Definition =>
2690               Modular_Type_Declaration (T, Def);
2691
2692            when N_Record_Definition =>
2693               Record_Type_Declaration (T, N, Prev);
2694
2695            --  If declaration has a parse error, nothing to elaborate.
2696
2697            when N_Error =>
2698               null;
2699
2700            when others =>
2701               raise Program_Error;
2702
2703         end case;
2704      end if;
2705
2706      if Etype (T) = Any_Type then
2707         return;
2708      end if;
2709
2710      --  Controlled type is not allowed in SPARK
2711
2712      if Is_Visibly_Controlled (T) then
2713         Check_SPARK_05_Restriction ("controlled type is not allowed", N);
2714      end if;
2715
2716      --  A type declared within a Ghost region is automatically Ghost
2717      --  (SPARK RM 6.9(2)).
2718
2719      if Comes_From_Source (T) and then Ghost_Mode > None then
2720         Set_Is_Ghost_Entity (T);
2721      end if;
2722
2723      --  Some common processing for all types
2724
2725      Set_Depends_On_Private (T, Has_Private_Component (T));
2726      Check_Ops_From_Incomplete_Type;
2727
2728      --  Both the declared entity, and its anonymous base type if one was
2729      --  created, need freeze nodes allocated.
2730
2731      declare
2732         B : constant Entity_Id := Base_Type (T);
2733
2734      begin
2735         --  In the case where the base type differs from the first subtype, we
2736         --  pre-allocate a freeze node, and set the proper link to the first
2737         --  subtype. Freeze_Entity will use this preallocated freeze node when
2738         --  it freezes the entity.
2739
2740         --  This does not apply if the base type is a generic type, whose
2741         --  declaration is independent of the current derived definition.
2742
2743         if B /= T and then not Is_Generic_Type (B) then
2744            Ensure_Freeze_Node (B);
2745            Set_First_Subtype_Link (Freeze_Node (B), T);
2746         end if;
2747
2748         --  A type that is imported through a limited_with clause cannot
2749         --  generate any code, and thus need not be frozen. However, an access
2750         --  type with an imported designated type needs a finalization list,
2751         --  which may be referenced in some other package that has non-limited
2752         --  visibility on the designated type. Thus we must create the
2753         --  finalization list at the point the access type is frozen, to
2754         --  prevent unsatisfied references at link time.
2755
2756         if not From_Limited_With (T) or else Is_Access_Type (T) then
2757            Set_Has_Delayed_Freeze (T);
2758         end if;
2759      end;
2760
2761      --  Case where T is the full declaration of some private type which has
2762      --  been swapped in Defining_Identifier (N).
2763
2764      if T /= Def_Id and then Is_Private_Type (Def_Id) then
2765         Process_Full_View (N, T, Def_Id);
2766
2767         --  Record the reference. The form of this is a little strange, since
2768         --  the full declaration has been swapped in. So the first parameter
2769         --  here represents the entity to which a reference is made which is
2770         --  the "real" entity, i.e. the one swapped in, and the second
2771         --  parameter provides the reference location.
2772
2773         --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2774         --  since we don't want a complaint about the full type being an
2775         --  unwanted reference to the private type
2776
2777         declare
2778            B : constant Boolean := Has_Pragma_Unreferenced (T);
2779         begin
2780            Set_Has_Pragma_Unreferenced (T, False);
2781            Generate_Reference (T, T, 'c');
2782            Set_Has_Pragma_Unreferenced (T, B);
2783         end;
2784
2785         Set_Completion_Referenced (Def_Id);
2786
2787      --  For completion of incomplete type, process incomplete dependents
2788      --  and always mark the full type as referenced (it is the incomplete
2789      --  type that we get for any real reference).
2790
2791      elsif Ekind (Prev) = E_Incomplete_Type then
2792         Process_Incomplete_Dependents (N, T, Prev);
2793         Generate_Reference (Prev, Def_Id, 'c');
2794         Set_Completion_Referenced (Def_Id);
2795
2796      --  If not private type or incomplete type completion, this is a real
2797      --  definition of a new entity, so record it.
2798
2799      else
2800         Generate_Definition (Def_Id);
2801      end if;
2802
2803      --  Propagate any pending access types whose finalization masters need to
2804      --  be fully initialized from the partial to the full view. Guard against
2805      --  an illegal full view that remains unanalyzed.
2806
2807      if Is_Type (Def_Id) and then Is_Incomplete_Or_Private_Type (Prev) then
2808         Set_Pending_Access_Types (Def_Id, Pending_Access_Types (Prev));
2809      end if;
2810
2811      if Chars (Scope (Def_Id)) = Name_System
2812        and then Chars (Def_Id) = Name_Address
2813        and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2814      then
2815         Set_Is_Descendent_Of_Address (Def_Id);
2816         Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2817         Set_Is_Descendent_Of_Address (Prev);
2818      end if;
2819
2820      Set_Optimize_Alignment_Flags (Def_Id);
2821      Check_Eliminated (Def_Id);
2822
2823      --  If the declaration is a completion and aspects are present, apply
2824      --  them to the entity for the type which is currently the partial
2825      --  view, but which is the one that will be frozen.
2826
2827      if Has_Aspects (N) then
2828
2829         --  In most cases the partial view is a private type, and both views
2830         --  appear in different declarative parts. In the unusual case where
2831         --  the partial view is incomplete, perform the analysis on the
2832         --  full view, to prevent freezing anomalies with the corresponding
2833         --  class-wide type, which otherwise might be frozen before the
2834         --  dispatch table is built.
2835
2836         if Prev /= Def_Id
2837           and then Ekind (Prev) /= E_Incomplete_Type
2838         then
2839            Analyze_Aspect_Specifications (N, Prev);
2840
2841         --  Normal case
2842
2843         else
2844            Analyze_Aspect_Specifications (N, Def_Id);
2845         end if;
2846      end if;
2847   end Analyze_Full_Type_Declaration;
2848
2849   ----------------------------------
2850   -- Analyze_Incomplete_Type_Decl --
2851   ----------------------------------
2852
2853   procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2854      F : constant Boolean := Is_Pure (Current_Scope);
2855      T : Entity_Id;
2856
2857   begin
2858      Check_SPARK_05_Restriction ("incomplete type is not allowed", N);
2859
2860      Generate_Definition (Defining_Identifier (N));
2861
2862      --  Process an incomplete declaration. The identifier must not have been
2863      --  declared already in the scope. However, an incomplete declaration may
2864      --  appear in the private part of a package, for a private type that has
2865      --  already been declared.
2866
2867      --  In this case, the discriminants (if any) must match
2868
2869      T := Find_Type_Name (N);
2870
2871      Set_Ekind (T, E_Incomplete_Type);
2872      Init_Size_Align (T);
2873      Set_Is_First_Subtype (T, True);
2874      Set_Etype (T, T);
2875
2876      --  An incomplete type declared within a Ghost region is automatically
2877      --  Ghost (SPARK RM 6.9(2)).
2878
2879      if Ghost_Mode > None then
2880         Set_Is_Ghost_Entity (T);
2881      end if;
2882
2883      --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2884      --  incomplete types.
2885
2886      if Tagged_Present (N) then
2887         Set_Is_Tagged_Type (T, True);
2888         Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
2889         Make_Class_Wide_Type (T);
2890         Set_Direct_Primitive_Operations (T, New_Elmt_List);
2891      end if;
2892
2893      Push_Scope (T);
2894
2895      Set_Stored_Constraint (T, No_Elist);
2896
2897      if Present (Discriminant_Specifications (N)) then
2898         Process_Discriminants (N);
2899      end if;
2900
2901      End_Scope;
2902
2903      --  If the type has discriminants, non-trivial subtypes may be
2904      --  declared before the full view of the type. The full views of those
2905      --  subtypes will be built after the full view of the type.
2906
2907      Set_Private_Dependents (T, New_Elmt_List);
2908      Set_Is_Pure            (T, F);
2909   end Analyze_Incomplete_Type_Decl;
2910
2911   -----------------------------------
2912   -- Analyze_Interface_Declaration --
2913   -----------------------------------
2914
2915   procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2916      CW : constant Entity_Id := Class_Wide_Type (T);
2917
2918   begin
2919      Set_Is_Tagged_Type (T);
2920      Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
2921
2922      Set_Is_Limited_Record (T, Limited_Present (Def)
2923                                  or else Task_Present (Def)
2924                                  or else Protected_Present (Def)
2925                                  or else Synchronized_Present (Def));
2926
2927      --  Type is abstract if full declaration carries keyword, or if previous
2928      --  partial view did.
2929
2930      Set_Is_Abstract_Type (T);
2931      Set_Is_Interface (T);
2932
2933      --  Type is a limited interface if it includes the keyword limited, task,
2934      --  protected, or synchronized.
2935
2936      Set_Is_Limited_Interface
2937        (T, Limited_Present (Def)
2938              or else Protected_Present (Def)
2939              or else Synchronized_Present (Def)
2940              or else Task_Present (Def));
2941
2942      Set_Interfaces (T, New_Elmt_List);
2943      Set_Direct_Primitive_Operations (T, New_Elmt_List);
2944
2945      --  Complete the decoration of the class-wide entity if it was already
2946      --  built (i.e. during the creation of the limited view)
2947
2948      if Present (CW) then
2949         Set_Is_Interface (CW);
2950         Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2951      end if;
2952
2953      --  Check runtime support for synchronized interfaces
2954
2955      if VM_Target = No_VM
2956        and then (Is_Task_Interface (T)
2957                   or else Is_Protected_Interface (T)
2958                   or else Is_Synchronized_Interface (T))
2959        and then not RTE_Available (RE_Select_Specific_Data)
2960      then
2961         Error_Msg_CRT ("synchronized interfaces", T);
2962      end if;
2963   end Analyze_Interface_Declaration;
2964
2965   -----------------------------
2966   -- Analyze_Itype_Reference --
2967   -----------------------------
2968
2969   --  Nothing to do. This node is placed in the tree only for the benefit of
2970   --  back end processing, and has no effect on the semantic processing.
2971
2972   procedure Analyze_Itype_Reference (N : Node_Id) is
2973   begin
2974      pragma Assert (Is_Itype (Itype (N)));
2975      null;
2976   end Analyze_Itype_Reference;
2977
2978   --------------------------------
2979   -- Analyze_Number_Declaration --
2980   --------------------------------
2981
2982   procedure Analyze_Number_Declaration (N : Node_Id) is
2983      Id    : constant Entity_Id := Defining_Identifier (N);
2984      E     : constant Node_Id   := Expression (N);
2985      T     : Entity_Id;
2986      Index : Interp_Index;
2987      It    : Interp;
2988
2989   begin
2990      --  The number declaration may be subject to pragma Ghost with policy
2991      --  Ignore. Set the mode now to ensure that any nodes generated during
2992      --  analysis and expansion are properly flagged as ignored Ghost.
2993
2994      Set_Ghost_Mode (N);
2995
2996      Generate_Definition (Id);
2997      Enter_Name (Id);
2998
2999      --  A number declared within a Ghost region is automatically Ghost
3000      --  (SPARK RM 6.9(2)).
3001
3002      if Ghost_Mode > None then
3003         Set_Is_Ghost_Entity (Id);
3004      end if;
3005
3006      --  This is an optimization of a common case of an integer literal
3007
3008      if Nkind (E) = N_Integer_Literal then
3009         Set_Is_Static_Expression (E, True);
3010         Set_Etype                (E, Universal_Integer);
3011
3012         Set_Etype     (Id, Universal_Integer);
3013         Set_Ekind     (Id, E_Named_Integer);
3014         Set_Is_Frozen (Id, True);
3015         return;
3016      end if;
3017
3018      Set_Is_Pure (Id, Is_Pure (Current_Scope));
3019
3020      --  Process expression, replacing error by integer zero, to avoid
3021      --  cascaded errors or aborts further along in the processing
3022
3023      --  Replace Error by integer zero, which seems least likely to cause
3024      --  cascaded errors.
3025
3026      if E = Error then
3027         Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
3028         Set_Error_Posted (E);
3029      end if;
3030
3031      Analyze (E);
3032
3033      --  Verify that the expression is static and numeric. If
3034      --  the expression is overloaded, we apply the preference
3035      --  rule that favors root numeric types.
3036
3037      if not Is_Overloaded (E) then
3038         T := Etype (E);
3039         if Has_Dynamic_Predicate_Aspect (T) then
3040            Error_Msg_N
3041              ("subtype has dynamic predicate, "
3042               & "not allowed in number declaration", N);
3043         end if;
3044
3045      else
3046         T := Any_Type;
3047
3048         Get_First_Interp (E, Index, It);
3049         while Present (It.Typ) loop
3050            if (Is_Integer_Type (It.Typ) or else Is_Real_Type (It.Typ))
3051              and then (Scope (Base_Type (It.Typ))) = Standard_Standard
3052            then
3053               if T = Any_Type then
3054                  T := It.Typ;
3055
3056               elsif It.Typ = Universal_Real
3057                       or else
3058                     It.Typ = Universal_Integer
3059               then
3060                  --  Choose universal interpretation over any other
3061
3062                  T := It.Typ;
3063                  exit;
3064               end if;
3065            end if;
3066
3067            Get_Next_Interp (Index, It);
3068         end loop;
3069      end if;
3070
3071      if Is_Integer_Type (T)  then
3072         Resolve (E, T);
3073         Set_Etype (Id, Universal_Integer);
3074         Set_Ekind (Id, E_Named_Integer);
3075
3076      elsif Is_Real_Type (T) then
3077
3078         --  Because the real value is converted to universal_real, this is a
3079         --  legal context for a universal fixed expression.
3080
3081         if T = Universal_Fixed then
3082            declare
3083               Loc  : constant Source_Ptr := Sloc (N);
3084               Conv : constant Node_Id := Make_Type_Conversion (Loc,
3085                        Subtype_Mark =>
3086                          New_Occurrence_Of (Universal_Real, Loc),
3087                        Expression => Relocate_Node (E));
3088
3089            begin
3090               Rewrite (E, Conv);
3091               Analyze (E);
3092            end;
3093
3094         elsif T = Any_Fixed then
3095            Error_Msg_N ("illegal context for mixed mode operation", E);
3096
3097            --  Expression is of the form : universal_fixed * integer. Try to
3098            --  resolve as universal_real.
3099
3100            T := Universal_Real;
3101            Set_Etype (E, T);
3102         end if;
3103
3104         Resolve (E, T);
3105         Set_Etype (Id, Universal_Real);
3106         Set_Ekind (Id, E_Named_Real);
3107
3108      else
3109         Wrong_Type (E, Any_Numeric);
3110         Resolve (E, T);
3111
3112         Set_Etype               (Id, T);
3113         Set_Ekind               (Id, E_Constant);
3114         Set_Never_Set_In_Source (Id, True);
3115         Set_Is_True_Constant    (Id, True);
3116         return;
3117      end if;
3118
3119      if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
3120         Set_Etype (E, Etype (Id));
3121      end if;
3122
3123      if not Is_OK_Static_Expression (E) then
3124         Flag_Non_Static_Expr
3125           ("non-static expression used in number declaration!", E);
3126         Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
3127         Set_Etype (E, Any_Type);
3128      end if;
3129   end Analyze_Number_Declaration;
3130
3131   -----------------------------
3132   -- Analyze_Object_Contract --
3133   -----------------------------
3134
3135   procedure Analyze_Object_Contract (Obj_Id : Entity_Id) is
3136      Obj_Typ : constant Entity_Id := Etype (Obj_Id);
3137      AR_Val  : Boolean := False;
3138      AW_Val  : Boolean := False;
3139      ER_Val  : Boolean := False;
3140      EW_Val  : Boolean := False;
3141      Prag    : Node_Id;
3142      Seen    : Boolean := False;
3143
3144   begin
3145      --  The loop parameter in an element iterator over a formal container
3146      --  is declared with an object declaration but no contracts apply.
3147
3148      if Ekind (Obj_Id) = E_Loop_Parameter then
3149         return;
3150      end if;
3151
3152      if Ekind (Obj_Id) = E_Constant then
3153
3154         --  A constant cannot be effectively volatile. This check is only
3155         --  relevant with SPARK_Mode on as it is not a standard Ada legality
3156         --  rule. Do not flag internally-generated constants that map generic
3157         --  formals to actuals in instantiations (SPARK RM 7.1.3(6)).
3158
3159         if SPARK_Mode = On
3160           and then Is_Effectively_Volatile (Obj_Id)
3161           and then No (Corresponding_Generic_Association (Parent (Obj_Id)))
3162
3163           --  Don't give this for internally generated entities (such as the
3164           --  FIRST and LAST temporaries generated for bounds).
3165
3166           and then Comes_From_Source (Obj_Id)
3167         then
3168            Error_Msg_N ("constant cannot be volatile", Obj_Id);
3169         end if;
3170
3171      else pragma Assert (Ekind (Obj_Id) = E_Variable);
3172
3173         --  The following checks are only relevant when SPARK_Mode is on as
3174         --  they are not standard Ada legality rules. Internally generated
3175         --  temporaries are ignored.
3176
3177         if SPARK_Mode = On and then Comes_From_Source (Obj_Id) then
3178            if Is_Effectively_Volatile (Obj_Id) then
3179
3180               --  The declaration of an effectively volatile object must
3181               --  appear at the library level (SPARK RM 7.1.3(7), C.6(6)).
3182
3183               if not Is_Library_Level_Entity (Obj_Id) then
3184                  Error_Msg_N
3185                    ("volatile variable & must be declared at library level",
3186                     Obj_Id);
3187
3188               --  An object of a discriminated type cannot be effectively
3189               --  volatile (SPARK RM C.6(4)).
3190
3191               elsif Has_Discriminants (Obj_Typ) then
3192                  Error_Msg_N
3193                    ("discriminated object & cannot be volatile", Obj_Id);
3194
3195               --  An object of a tagged type cannot be effectively volatile
3196               --  (SPARK RM C.6(5)).
3197
3198               elsif Is_Tagged_Type (Obj_Typ) then
3199                  Error_Msg_N ("tagged object & cannot be volatile", Obj_Id);
3200               end if;
3201
3202            --  The object is not effectively volatile
3203
3204            else
3205               --  A non-effectively volatile object cannot have effectively
3206               --  volatile components (SPARK RM 7.1.3(7)).
3207
3208               if not Is_Effectively_Volatile (Obj_Id)
3209                 and then Has_Volatile_Component (Obj_Typ)
3210               then
3211                  Error_Msg_N
3212                    ("non-volatile object & cannot have volatile components",
3213                     Obj_Id);
3214               end if;
3215            end if;
3216         end if;
3217
3218         if Is_Ghost_Entity (Obj_Id) then
3219
3220            --  A Ghost object cannot be effectively volatile (SPARK RM 6.9(8))
3221
3222            if Is_Effectively_Volatile (Obj_Id) then
3223               Error_Msg_N ("ghost variable & cannot be volatile", Obj_Id);
3224
3225            --  A Ghost object cannot be imported or exported (SPARK RM 6.9(8))
3226
3227            elsif Is_Imported (Obj_Id) then
3228               Error_Msg_N ("ghost object & cannot be imported", Obj_Id);
3229
3230            elsif Is_Exported (Obj_Id) then
3231               Error_Msg_N ("ghost object & cannot be exported", Obj_Id);
3232            end if;
3233         end if;
3234
3235         --  Analyze all external properties
3236
3237         Prag := Get_Pragma (Obj_Id, Pragma_Async_Readers);
3238
3239         if Present (Prag) then
3240            Analyze_External_Property_In_Decl_Part (Prag, AR_Val);
3241            Seen := True;
3242         end if;
3243
3244         Prag := Get_Pragma (Obj_Id, Pragma_Async_Writers);
3245
3246         if Present (Prag) then
3247            Analyze_External_Property_In_Decl_Part (Prag, AW_Val);
3248            Seen := True;
3249         end if;
3250
3251         Prag := Get_Pragma (Obj_Id, Pragma_Effective_Reads);
3252
3253         if Present (Prag) then
3254            Analyze_External_Property_In_Decl_Part (Prag, ER_Val);
3255            Seen := True;
3256         end if;
3257
3258         Prag := Get_Pragma (Obj_Id, Pragma_Effective_Writes);
3259
3260         if Present (Prag) then
3261            Analyze_External_Property_In_Decl_Part (Prag, EW_Val);
3262            Seen := True;
3263         end if;
3264
3265         --  Verify the mutual interaction of the various external properties
3266
3267         if Seen then
3268            Check_External_Properties (Obj_Id, AR_Val, AW_Val, ER_Val, EW_Val);
3269         end if;
3270
3271         --  Check whether the lack of indicator Part_Of agrees with the
3272         --  placement of the variable with respect to the state space.
3273
3274         Prag := Get_Pragma (Obj_Id, Pragma_Part_Of);
3275
3276         if No (Prag) then
3277            Check_Missing_Part_Of (Obj_Id);
3278         end if;
3279      end if;
3280
3281      --  A ghost object cannot be imported or exported (SPARK RM 6.9(8))
3282
3283      if Is_Ghost_Entity (Obj_Id) then
3284         if Is_Exported (Obj_Id) then
3285            Error_Msg_N ("ghost object & cannot be exported", Obj_Id);
3286
3287         elsif Is_Imported (Obj_Id) then
3288            Error_Msg_N ("ghost object & cannot be imported", Obj_Id);
3289         end if;
3290      end if;
3291   end Analyze_Object_Contract;
3292
3293   --------------------------------
3294   -- Analyze_Object_Declaration --
3295   --------------------------------
3296
3297   procedure Analyze_Object_Declaration (N : Node_Id) is
3298      Loc   : constant Source_Ptr := Sloc (N);
3299      Id    : constant Entity_Id  := Defining_Identifier (N);
3300      T     : Entity_Id;
3301      Act_T : Entity_Id;
3302
3303      E : Node_Id := Expression (N);
3304      --  E is set to Expression (N) throughout this routine. When
3305      --  Expression (N) is modified, E is changed accordingly.
3306
3307      Prev_Entity : Entity_Id := Empty;
3308
3309      function Count_Tasks (T : Entity_Id) return Uint;
3310      --  This function is called when a non-generic library level object of a
3311      --  task type is declared. Its function is to count the static number of
3312      --  tasks declared within the type (it is only called if Has_Tasks is set
3313      --  for T). As a side effect, if an array of tasks with non-static bounds
3314      --  or a variant record type is encountered, Check_Restrictions is called
3315      --  indicating the count is unknown.
3316
3317      -----------------
3318      -- Count_Tasks --
3319      -----------------
3320
3321      function Count_Tasks (T : Entity_Id) return Uint is
3322         C : Entity_Id;
3323         X : Node_Id;
3324         V : Uint;
3325
3326      begin
3327         if Is_Task_Type (T) then
3328            return Uint_1;
3329
3330         elsif Is_Record_Type (T) then
3331            if Has_Discriminants (T) then
3332               Check_Restriction (Max_Tasks, N);
3333               return Uint_0;
3334
3335            else
3336               V := Uint_0;
3337               C := First_Component (T);
3338               while Present (C) loop
3339                  V := V + Count_Tasks (Etype (C));
3340                  Next_Component (C);
3341               end loop;
3342
3343               return V;
3344            end if;
3345
3346         elsif Is_Array_Type (T) then
3347            X := First_Index (T);
3348            V := Count_Tasks (Component_Type (T));
3349            while Present (X) loop
3350               C := Etype (X);
3351
3352               if not Is_OK_Static_Subtype (C) then
3353                  Check_Restriction (Max_Tasks, N);
3354                  return Uint_0;
3355               else
3356                  V := V * (UI_Max (Uint_0,
3357                                    Expr_Value (Type_High_Bound (C)) -
3358                                    Expr_Value (Type_Low_Bound (C)) + Uint_1));
3359               end if;
3360
3361               Next_Index (X);
3362            end loop;
3363
3364            return V;
3365
3366         else
3367            return Uint_0;
3368         end if;
3369      end Count_Tasks;
3370
3371   --  Start of processing for Analyze_Object_Declaration
3372
3373   begin
3374      --  There are three kinds of implicit types generated by an
3375      --  object declaration:
3376
3377      --   1. Those generated by the original Object Definition
3378
3379      --   2. Those generated by the Expression
3380
3381      --   3. Those used to constrain the Object Definition with the
3382      --      expression constraints when the definition is unconstrained.
3383
3384      --  They must be generated in this order to avoid order of elaboration
3385      --  issues. Thus the first step (after entering the name) is to analyze
3386      --  the object definition.
3387
3388      if Constant_Present (N) then
3389         Prev_Entity := Current_Entity_In_Scope (Id);
3390
3391         if Present (Prev_Entity)
3392           and then
3393             --  If the homograph is an implicit subprogram, it is overridden
3394             --  by the current declaration.
3395
3396             ((Is_Overloadable (Prev_Entity)
3397                and then Is_Inherited_Operation (Prev_Entity))
3398
3399               --  The current object is a discriminal generated for an entry
3400               --  family index. Even though the index is a constant, in this
3401               --  particular context there is no true constant redeclaration.
3402               --  Enter_Name will handle the visibility.
3403
3404               or else
3405                 (Is_Discriminal (Id)
3406                   and then Ekind (Discriminal_Link (Id)) =
3407                                              E_Entry_Index_Parameter)
3408
3409               --  The current object is the renaming for a generic declared
3410               --  within the instance.
3411
3412               or else
3413                 (Ekind (Prev_Entity) = E_Package
3414                   and then Nkind (Parent (Prev_Entity)) =
3415                                               N_Package_Renaming_Declaration
3416                   and then not Comes_From_Source (Prev_Entity)
3417                   and then
3418                     Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
3419         then
3420            Prev_Entity := Empty;
3421         end if;
3422      end if;
3423
3424      --  The object declaration may be subject to pragma Ghost with policy
3425      --  Ignore. Set the mode now to ensure that any nodes generated during
3426      --  analysis and expansion are properly flagged as ignored Ghost.
3427
3428      Set_Ghost_Mode (N, Prev_Entity);
3429
3430      if Present (Prev_Entity) then
3431         Constant_Redeclaration (Id, N, T);
3432
3433         Generate_Reference (Prev_Entity, Id, 'c');
3434         Set_Completion_Referenced (Id);
3435
3436         if Error_Posted (N) then
3437
3438            --  Type mismatch or illegal redeclaration, Do not analyze
3439            --  expression to avoid cascaded errors.
3440
3441            T := Find_Type_Of_Object (Object_Definition (N), N);
3442            Set_Etype (Id, T);
3443            Set_Ekind (Id, E_Variable);
3444            goto Leave;
3445         end if;
3446
3447      --  In the normal case, enter identifier at the start to catch premature
3448      --  usage in the initialization expression.
3449
3450      else
3451         Generate_Definition (Id);
3452         Enter_Name (Id);
3453
3454         Mark_Coextensions (N, Object_Definition (N));
3455
3456         T := Find_Type_Of_Object (Object_Definition (N), N);
3457
3458         if Nkind (Object_Definition (N)) = N_Access_Definition
3459           and then Present
3460                      (Access_To_Subprogram_Definition (Object_Definition (N)))
3461           and then Protected_Present
3462                      (Access_To_Subprogram_Definition (Object_Definition (N)))
3463         then
3464            T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
3465         end if;
3466
3467         if Error_Posted (Id) then
3468            Set_Etype (Id, T);
3469            Set_Ekind (Id, E_Variable);
3470            goto Leave;
3471         end if;
3472      end if;
3473
3474      --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
3475      --  out some static checks
3476
3477      if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (T) then
3478
3479         --  In case of aggregates we must also take care of the correct
3480         --  initialization of nested aggregates bug this is done at the
3481         --  point of the analysis of the aggregate (see sem_aggr.adb).
3482
3483         if Present (Expression (N))
3484           and then Nkind (Expression (N)) = N_Aggregate
3485         then
3486            null;
3487
3488         else
3489            declare
3490               Save_Typ : constant Entity_Id := Etype (Id);
3491            begin
3492               Set_Etype (Id, T); --  Temp. decoration for static checks
3493               Null_Exclusion_Static_Checks (N);
3494               Set_Etype (Id, Save_Typ);
3495            end;
3496         end if;
3497      end if;
3498
3499      --  Object is marked pure if it is in a pure scope
3500
3501      Set_Is_Pure (Id, Is_Pure (Current_Scope));
3502
3503      --  If deferred constant, make sure context is appropriate. We detect
3504      --  a deferred constant as a constant declaration with no expression.
3505      --  A deferred constant can appear in a package body if its completion
3506      --  is by means of an interface pragma.
3507
3508      if Constant_Present (N) and then No (E) then
3509
3510         --  A deferred constant may appear in the declarative part of the
3511         --  following constructs:
3512
3513         --     blocks
3514         --     entry bodies
3515         --     extended return statements
3516         --     package specs
3517         --     package bodies
3518         --     subprogram bodies
3519         --     task bodies
3520
3521         --  When declared inside a package spec, a deferred constant must be
3522         --  completed by a full constant declaration or pragma Import. In all
3523         --  other cases, the only proper completion is pragma Import. Extended
3524         --  return statements are flagged as invalid contexts because they do
3525         --  not have a declarative part and so cannot accommodate the pragma.
3526
3527         if Ekind (Current_Scope) = E_Return_Statement then
3528            Error_Msg_N
3529              ("invalid context for deferred constant declaration (RM 7.4)",
3530               N);
3531            Error_Msg_N
3532              ("\declaration requires an initialization expression",
3533                N);
3534            Set_Constant_Present (N, False);
3535
3536         --  In Ada 83, deferred constant must be of private type
3537
3538         elsif not Is_Private_Type (T) then
3539            if Ada_Version = Ada_83 and then Comes_From_Source (N) then
3540               Error_Msg_N
3541                 ("(Ada 83) deferred constant must be private type", N);
3542            end if;
3543         end if;
3544
3545      --  If not a deferred constant, then the object declaration freezes
3546      --  its type, unless the object is of an anonymous type and has delayed
3547      --  aspects. In that case the type is frozen when the object itself is.
3548
3549      else
3550         Check_Fully_Declared (T, N);
3551
3552         if Has_Delayed_Aspects (Id)
3553           and then Is_Array_Type (T)
3554           and then Is_Itype (T)
3555         then
3556            Set_Has_Delayed_Freeze (T);
3557         else
3558            Freeze_Before (N, T);
3559         end if;
3560      end if;
3561
3562      --  If the object was created by a constrained array definition, then
3563      --  set the link in both the anonymous base type and anonymous subtype
3564      --  that are built to represent the array type to point to the object.
3565
3566      if Nkind (Object_Definition (Declaration_Node (Id))) =
3567                        N_Constrained_Array_Definition
3568      then
3569         Set_Related_Array_Object (T, Id);
3570         Set_Related_Array_Object (Base_Type (T), Id);
3571      end if;
3572
3573      --  Special checks for protected objects not at library level
3574
3575      if Is_Protected_Type (T)
3576        and then not Is_Library_Level_Entity (Id)
3577      then
3578         Check_Restriction (No_Local_Protected_Objects, Id);
3579
3580         --  Protected objects with interrupt handlers must be at library level
3581
3582         --  Ada 2005: This test is not needed (and the corresponding clause
3583         --  in the RM is removed) because accessibility checks are sufficient
3584         --  to make handlers not at the library level illegal.
3585
3586         --  AI05-0303: The AI is in fact a binding interpretation, and thus
3587         --  applies to the '95 version of the language as well.
3588
3589         if Has_Interrupt_Handler (T) and then Ada_Version < Ada_95 then
3590            Error_Msg_N
3591              ("interrupt object can only be declared at library level", Id);
3592         end if;
3593      end if;
3594
3595      --  The actual subtype of the object is the nominal subtype, unless
3596      --  the nominal one is unconstrained and obtained from the expression.
3597
3598      Act_T := T;
3599
3600      --  These checks should be performed before the initialization expression
3601      --  is considered, so that the Object_Definition node is still the same
3602      --  as in source code.
3603
3604      --  In SPARK, the nominal subtype is always given by a subtype mark
3605      --  and must not be unconstrained. (The only exception to this is the
3606      --  acceptance of declarations of constants of type String.)
3607
3608      if not Nkind_In (Object_Definition (N), N_Expanded_Name, N_Identifier)
3609      then
3610         Check_SPARK_05_Restriction
3611           ("subtype mark required", Object_Definition (N));
3612
3613      elsif Is_Array_Type (T)
3614        and then not Is_Constrained (T)
3615        and then T /= Standard_String
3616      then
3617         Check_SPARK_05_Restriction
3618           ("subtype mark of constrained type expected",
3619            Object_Definition (N));
3620      end if;
3621
3622      --  There are no aliased objects in SPARK
3623
3624      if Aliased_Present (N) then
3625         Check_SPARK_05_Restriction ("aliased object is not allowed", N);
3626      end if;
3627
3628      --  Process initialization expression if present and not in error
3629
3630      if Present (E) and then E /= Error then
3631
3632         --  Generate an error in case of CPP class-wide object initialization.
3633         --  Required because otherwise the expansion of the class-wide
3634         --  assignment would try to use 'size to initialize the object
3635         --  (primitive that is not available in CPP tagged types).
3636
3637         if Is_Class_Wide_Type (Act_T)
3638           and then
3639             (Is_CPP_Class (Root_Type (Etype (Act_T)))
3640               or else
3641                 (Present (Full_View (Root_Type (Etype (Act_T))))
3642                   and then
3643                     Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
3644         then
3645            Error_Msg_N
3646              ("predefined assignment not available for 'C'P'P tagged types",
3647               E);
3648         end if;
3649
3650         Mark_Coextensions (N, E);
3651         Analyze (E);
3652
3653         --  In case of errors detected in the analysis of the expression,
3654         --  decorate it with the expected type to avoid cascaded errors
3655
3656         if No (Etype (E)) then
3657            Set_Etype (E, T);
3658         end if;
3659
3660         --  If an initialization expression is present, then we set the
3661         --  Is_True_Constant flag. It will be reset if this is a variable
3662         --  and it is indeed modified.
3663
3664         Set_Is_True_Constant (Id, True);
3665
3666         --  If we are analyzing a constant declaration, set its completion
3667         --  flag after analyzing and resolving the expression.
3668
3669         if Constant_Present (N) then
3670            Set_Has_Completion (Id);
3671         end if;
3672
3673         --  Set type and resolve (type may be overridden later on). Note:
3674         --  Ekind (Id) must still be E_Void at this point so that incorrect
3675         --  early usage within E is properly diagnosed.
3676
3677         Set_Etype (Id, T);
3678
3679         --  If the expression is an aggregate we must look ahead to detect
3680         --  the possible presence of an address clause, and defer resolution
3681         --  and expansion of the aggregate to the freeze point of the entity.
3682
3683         if Comes_From_Source (N)
3684           and then Expander_Active
3685           and then Nkind (E) = N_Aggregate
3686           and then Present (Following_Address_Clause (N))
3687         then
3688            Set_Etype (E, T);
3689
3690         else
3691            Resolve (E, T);
3692         end if;
3693
3694         --  No further action needed if E is a call to an inlined function
3695         --  which returns an unconstrained type and it has been expanded into
3696         --  a procedure call. In that case N has been replaced by an object
3697         --  declaration without initializing expression and it has been
3698         --  analyzed (see Expand_Inlined_Call).
3699
3700         if Back_End_Inlining
3701           and then Expander_Active
3702           and then Nkind (E) = N_Function_Call
3703           and then Nkind (Name (E)) in N_Has_Entity
3704           and then Is_Inlined (Entity (Name (E)))
3705           and then not Is_Constrained (Etype (E))
3706           and then Analyzed (N)
3707           and then No (Expression (N))
3708         then
3709            return;
3710         end if;
3711
3712         --  If E is null and has been replaced by an N_Raise_Constraint_Error
3713         --  node (which was marked already-analyzed), we need to set the type
3714         --  to something other than Any_Access in order to keep gigi happy.
3715
3716         if Etype (E) = Any_Access then
3717            Set_Etype (E, T);
3718         end if;
3719
3720         --  If the object is an access to variable, the initialization
3721         --  expression cannot be an access to constant.
3722
3723         if Is_Access_Type (T)
3724           and then not Is_Access_Constant (T)
3725           and then Is_Access_Type (Etype (E))
3726           and then Is_Access_Constant (Etype (E))
3727         then
3728            Error_Msg_N
3729              ("access to variable cannot be initialized with an "
3730               & "access-to-constant expression", E);
3731         end if;
3732
3733         if not Assignment_OK (N) then
3734            Check_Initialization (T, E);
3735         end if;
3736
3737         Check_Unset_Reference (E);
3738
3739         --  If this is a variable, then set current value. If this is a
3740         --  declared constant of a scalar type with a static expression,
3741         --  indicate that it is always valid.
3742
3743         if not Constant_Present (N) then
3744            if Compile_Time_Known_Value (E) then
3745               Set_Current_Value (Id, E);
3746            end if;
3747
3748         elsif Is_Scalar_Type (T) and then Is_OK_Static_Expression (E) then
3749            Set_Is_Known_Valid (Id);
3750         end if;
3751
3752         --  Deal with setting of null flags
3753
3754         if Is_Access_Type (T) then
3755            if Known_Non_Null (E) then
3756               Set_Is_Known_Non_Null (Id, True);
3757            elsif Known_Null (E) and then not Can_Never_Be_Null (Id) then
3758               Set_Is_Known_Null (Id, True);
3759            end if;
3760         end if;
3761
3762         --  Check incorrect use of dynamically tagged expressions
3763
3764         if Is_Tagged_Type (T) then
3765            Check_Dynamically_Tagged_Expression
3766              (Expr        => E,
3767               Typ         => T,
3768               Related_Nod => N);
3769         end if;
3770
3771         Apply_Scalar_Range_Check (E, T);
3772         Apply_Static_Length_Check (E, T);
3773
3774         if Nkind (Original_Node (N)) = N_Object_Declaration
3775           and then Comes_From_Source (Original_Node (N))
3776
3777           --  Only call test if needed
3778
3779           and then Restriction_Check_Required (SPARK_05)
3780           and then not Is_SPARK_05_Initialization_Expr (Original_Node (E))
3781         then
3782            Check_SPARK_05_Restriction
3783              ("initialization expression is not appropriate", E);
3784         end if;
3785
3786         --  A formal parameter of a specific tagged type whose related
3787         --  subprogram is subject to pragma Extensions_Visible with value
3788         --  "False" cannot be implicitly converted to a class-wide type by
3789         --  means of an initialization expression (SPARK RM 6.1.7(3)).
3790
3791         if Is_Class_Wide_Type (T) and then Is_EVF_Expression (E) then
3792            Error_Msg_N
3793              ("formal parameter with Extensions_Visible False cannot be "
3794               & "implicitly converted to class-wide type", E);
3795         end if;
3796      end if;
3797
3798      --  If the No_Streams restriction is set, check that the type of the
3799      --  object is not, and does not contain, any subtype derived from
3800      --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3801      --  Has_Stream just for efficiency reasons. There is no point in
3802      --  spending time on a Has_Stream check if the restriction is not set.
3803
3804      if Restriction_Check_Required (No_Streams) then
3805         if Has_Stream (T) then
3806            Check_Restriction (No_Streams, N);
3807         end if;
3808      end if;
3809
3810      --  Deal with predicate check before we start to do major rewriting. It
3811      --  is OK to initialize and then check the initialized value, since the
3812      --  object goes out of scope if we get a predicate failure. Note that we
3813      --  do this in the analyzer and not the expander because the analyzer
3814      --  does some substantial rewriting in some cases.
3815
3816      --  We need a predicate check if the type has predicates, and if either
3817      --  there is an initializing expression, or for default initialization
3818      --  when we have at least one case of an explicit default initial value
3819      --  and then this is not an internal declaration whose initialization
3820      --  comes later (as for an aggregate expansion).
3821
3822      if not Suppress_Assignment_Checks (N)
3823        and then Present (Predicate_Function (T))
3824        and then not No_Initialization (N)
3825        and then
3826          (Present (E)
3827            or else
3828              Is_Partially_Initialized_Type (T, Include_Implicit => False))
3829      then
3830         --  If the type has a static predicate and the expression is known at
3831         --  compile time, see if the expression satisfies the predicate.
3832
3833         if Present (E) then
3834            Check_Expression_Against_Static_Predicate (E, T);
3835         end if;
3836
3837         Insert_After (N,
3838           Make_Predicate_Check (T, New_Occurrence_Of (Id, Loc)));
3839      end if;
3840
3841      --  Case of unconstrained type
3842
3843      if Is_Indefinite_Subtype (T) then
3844
3845         --  In SPARK, a declaration of unconstrained type is allowed
3846         --  only for constants of type string.
3847
3848         if Is_String_Type (T) and then not Constant_Present (N) then
3849            Check_SPARK_05_Restriction
3850              ("declaration of object of unconstrained type not allowed", N);
3851         end if;
3852
3853         --  Nothing to do in deferred constant case
3854
3855         if Constant_Present (N) and then No (E) then
3856            null;
3857
3858         --  Case of no initialization present
3859
3860         elsif No (E) then
3861            if No_Initialization (N) then
3862               null;
3863
3864            elsif Is_Class_Wide_Type (T) then
3865               Error_Msg_N
3866                 ("initialization required in class-wide declaration ", N);
3867
3868            else
3869               Error_Msg_N
3870                 ("unconstrained subtype not allowed (need initialization)",
3871                  Object_Definition (N));
3872
3873               if Is_Record_Type (T) and then Has_Discriminants (T) then
3874                  Error_Msg_N
3875                    ("\provide initial value or explicit discriminant values",
3876                     Object_Definition (N));
3877
3878                  Error_Msg_NE
3879                    ("\or give default discriminant values for type&",
3880                     Object_Definition (N), T);
3881
3882               elsif Is_Array_Type (T) then
3883                  Error_Msg_N
3884                    ("\provide initial value or explicit array bounds",
3885                     Object_Definition (N));
3886               end if;
3887            end if;
3888
3889         --  Case of initialization present but in error. Set initial
3890         --  expression as absent (but do not make above complaints)
3891
3892         elsif E = Error then
3893            Set_Expression (N, Empty);
3894            E := Empty;
3895
3896         --  Case of initialization present
3897
3898         else
3899            --  Check restrictions in Ada 83
3900
3901            if not Constant_Present (N) then
3902
3903               --  Unconstrained variables not allowed in Ada 83 mode
3904
3905               if Ada_Version = Ada_83
3906                 and then Comes_From_Source (Object_Definition (N))
3907               then
3908                  Error_Msg_N
3909                    ("(Ada 83) unconstrained variable not allowed",
3910                     Object_Definition (N));
3911               end if;
3912            end if;
3913
3914            --  Now we constrain the variable from the initializing expression
3915
3916            --  If the expression is an aggregate, it has been expanded into
3917            --  individual assignments. Retrieve the actual type from the
3918            --  expanded construct.
3919
3920            if Is_Array_Type (T)
3921              and then No_Initialization (N)
3922              and then Nkind (Original_Node (E)) = N_Aggregate
3923            then
3924               Act_T := Etype (E);
3925
3926            --  In case of class-wide interface object declarations we delay
3927            --  the generation of the equivalent record type declarations until
3928            --  its expansion because there are cases in they are not required.
3929
3930            elsif Is_Interface (T) then
3931               null;
3932
3933            --  In GNATprove mode, Expand_Subtype_From_Expr does nothing. Thus,
3934            --  we should prevent the generation of another Itype with the
3935            --  same name as the one already generated, or we end up with
3936            --  two identical types in GNATprove.
3937
3938            elsif GNATprove_Mode then
3939               null;
3940
3941            --  If the type is an unchecked union, no subtype can be built from
3942            --  the expression. Rewrite declaration as a renaming, which the
3943            --  back-end can handle properly. This is a rather unusual case,
3944            --  because most unchecked_union declarations have default values
3945            --  for discriminants and are thus not indefinite.
3946
3947            elsif Is_Unchecked_Union (T) then
3948               if Constant_Present (N) or else Nkind (E) = N_Function_Call then
3949                  Set_Ekind (Id, E_Constant);
3950               else
3951                  Set_Ekind (Id, E_Variable);
3952               end if;
3953
3954               --  An object declared within a Ghost region is automatically
3955               --  Ghost (SPARK RM 6.9(2)).
3956
3957               if Comes_From_Source (Id) and then Ghost_Mode > None then
3958                  Set_Is_Ghost_Entity (Id);
3959
3960                  --  The Ghost policy in effect at the point of declaration
3961                  --  and at the point of completion must match
3962                  --  (SPARK RM 6.9(15)).
3963
3964                  if Present (Prev_Entity)
3965                    and then Is_Ghost_Entity (Prev_Entity)
3966                  then
3967                     Check_Ghost_Completion (Prev_Entity, Id);
3968                  end if;
3969               end if;
3970
3971               Rewrite (N,
3972                 Make_Object_Renaming_Declaration (Loc,
3973                   Defining_Identifier => Id,
3974                   Subtype_Mark        => New_Occurrence_Of (T, Loc),
3975                   Name                => E));
3976
3977               Set_Renamed_Object (Id, E);
3978               Freeze_Before (N, T);
3979               Set_Is_Frozen (Id);
3980               return;
3981
3982            else
3983               Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3984               Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3985            end if;
3986
3987            Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3988
3989            if Aliased_Present (N) then
3990               Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3991            end if;
3992
3993            Freeze_Before (N, Act_T);
3994            Freeze_Before (N, T);
3995         end if;
3996
3997      elsif Is_Array_Type (T)
3998        and then No_Initialization (N)
3999        and then Nkind (Original_Node (E)) = N_Aggregate
4000      then
4001         if not Is_Entity_Name (Object_Definition (N)) then
4002            Act_T := Etype (E);
4003            Check_Compile_Time_Size (Act_T);
4004
4005            if Aliased_Present (N) then
4006               Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
4007            end if;
4008         end if;
4009
4010         --  When the given object definition and the aggregate are specified
4011         --  independently, and their lengths might differ do a length check.
4012         --  This cannot happen if the aggregate is of the form (others =>...)
4013
4014         if not Is_Constrained (T) then
4015            null;
4016
4017         elsif Nkind (E) = N_Raise_Constraint_Error then
4018
4019            --  Aggregate is statically illegal. Place back in declaration
4020
4021            Set_Expression (N, E);
4022            Set_No_Initialization (N, False);
4023
4024         elsif T = Etype (E) then
4025            null;
4026
4027         elsif Nkind (E) = N_Aggregate
4028           and then Present (Component_Associations (E))
4029           and then Present (Choices (First (Component_Associations (E))))
4030           and then Nkind (First
4031            (Choices (First (Component_Associations (E))))) = N_Others_Choice
4032         then
4033            null;
4034
4035         else
4036            Apply_Length_Check (E, T);
4037         end if;
4038
4039      --  If the type is limited unconstrained with defaulted discriminants and
4040      --  there is no expression, then the object is constrained by the
4041      --  defaults, so it is worthwhile building the corresponding subtype.
4042
4043      elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
4044        and then not Is_Constrained (T)
4045        and then Has_Discriminants (T)
4046      then
4047         if No (E) then
4048            Act_T := Build_Default_Subtype (T, N);
4049         else
4050            --  Ada 2005: A limited object may be initialized by means of an
4051            --  aggregate. If the type has default discriminants it has an
4052            --  unconstrained nominal type, Its actual subtype will be obtained
4053            --  from the aggregate, and not from the default discriminants.
4054
4055            Act_T := Etype (E);
4056         end if;
4057
4058         Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
4059
4060      elsif Nkind (E) = N_Function_Call
4061        and then Constant_Present (N)
4062        and then Has_Unconstrained_Elements (Etype (E))
4063      then
4064         --  The back-end has problems with constants of a discriminated type
4065         --  with defaults, if the initial value is a function call. We
4066         --  generate an intermediate temporary that will receive a reference
4067         --  to the result of the call. The initialization expression then
4068         --  becomes a dereference of that temporary.
4069
4070         Remove_Side_Effects (E);
4071
4072      --  If this is a constant declaration of an unconstrained type and
4073      --  the initialization is an aggregate, we can use the subtype of the
4074      --  aggregate for the declared entity because it is immutable.
4075
4076      elsif not Is_Constrained (T)
4077        and then Has_Discriminants (T)
4078        and then Constant_Present (N)
4079        and then not Has_Unchecked_Union (T)
4080        and then Nkind (E) = N_Aggregate
4081      then
4082         Act_T := Etype (E);
4083      end if;
4084
4085      --  Check No_Wide_Characters restriction
4086
4087      Check_Wide_Character_Restriction (T, Object_Definition (N));
4088
4089      --  Indicate this is not set in source. Certainly true for constants, and
4090      --  true for variables so far (will be reset for a variable if and when
4091      --  we encounter a modification in the source).
4092
4093      Set_Never_Set_In_Source (Id);
4094
4095      --  Now establish the proper kind and type of the object
4096
4097      if Constant_Present (N) then
4098         Set_Ekind            (Id, E_Constant);
4099         Set_Is_True_Constant (Id);
4100
4101      else
4102         Set_Ekind (Id, E_Variable);
4103
4104         --  A variable is set as shared passive if it appears in a shared
4105         --  passive package, and is at the outer level. This is not done for
4106         --  entities generated during expansion, because those are always
4107         --  manipulated locally.
4108
4109         if Is_Shared_Passive (Current_Scope)
4110           and then Is_Library_Level_Entity (Id)
4111           and then Comes_From_Source (Id)
4112         then
4113            Set_Is_Shared_Passive (Id);
4114            Check_Shared_Var (Id, T, N);
4115         end if;
4116
4117         --  Set Has_Initial_Value if initializing expression present. Note
4118         --  that if there is no initializing expression, we leave the state
4119         --  of this flag unchanged (usually it will be False, but notably in
4120         --  the case of exception choice variables, it will already be true).
4121
4122         if Present (E) then
4123            Set_Has_Initial_Value (Id);
4124         end if;
4125      end if;
4126
4127      --  Initialize alignment and size and capture alignment setting
4128
4129      Init_Alignment               (Id);
4130      Init_Esize                   (Id);
4131      Set_Optimize_Alignment_Flags (Id);
4132
4133      --  An object declared within a Ghost region is automatically Ghost
4134      --  (SPARK RM 6.9(2)).
4135
4136      if Comes_From_Source (Id)
4137        and then (Ghost_Mode > None
4138                   or else (Present (Prev_Entity)
4139                             and then Is_Ghost_Entity (Prev_Entity)))
4140      then
4141         Set_Is_Ghost_Entity (Id);
4142
4143         --  The Ghost policy in effect at the point of declaration and at the
4144         --  point of completion must match (SPARK RM 6.9(16)).
4145
4146         if Present (Prev_Entity) and then Is_Ghost_Entity (Prev_Entity) then
4147            Check_Ghost_Completion (Prev_Entity, Id);
4148         end if;
4149      end if;
4150
4151      --  Deal with aliased case
4152
4153      if Aliased_Present (N) then
4154         Set_Is_Aliased (Id);
4155
4156         --  If the object is aliased and the type is unconstrained with
4157         --  defaulted discriminants and there is no expression, then the
4158         --  object is constrained by the defaults, so it is worthwhile
4159         --  building the corresponding subtype.
4160
4161         --  Ada 2005 (AI-363): If the aliased object is discriminated and
4162         --  unconstrained, then only establish an actual subtype if the
4163         --  nominal subtype is indefinite. In definite cases the object is
4164         --  unconstrained in Ada 2005.
4165
4166         if No (E)
4167           and then Is_Record_Type (T)
4168           and then not Is_Constrained (T)
4169           and then Has_Discriminants (T)
4170           and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
4171         then
4172            Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
4173         end if;
4174      end if;
4175
4176      --  Now we can set the type of the object
4177
4178      Set_Etype (Id, Act_T);
4179
4180      --  Non-constant object is marked to be treated as volatile if type is
4181      --  volatile and we clear the Current_Value setting that may have been
4182      --  set above. Doing so for constants isn't required and might interfere
4183      --  with possible uses of the object as a static expression in contexts
4184      --  incompatible with volatility (e.g. as a case-statement alternative).
4185
4186      if Ekind (Id) /= E_Constant and then Treat_As_Volatile (Etype (Id)) then
4187         Set_Treat_As_Volatile (Id);
4188         Set_Current_Value (Id, Empty);
4189      end if;
4190
4191      --  Deal with controlled types
4192
4193      if Has_Controlled_Component (Etype (Id))
4194        or else Is_Controlled (Etype (Id))
4195      then
4196         if not Is_Library_Level_Entity (Id) then
4197            Check_Restriction (No_Nested_Finalization, N);
4198         else
4199            Validate_Controlled_Object (Id);
4200         end if;
4201      end if;
4202
4203      if Has_Task (Etype (Id)) then
4204         Check_Restriction (No_Tasking, N);
4205
4206         --  Deal with counting max tasks
4207
4208         --  Nothing to do if inside a generic
4209
4210         if Inside_A_Generic then
4211            null;
4212
4213         --  If library level entity, then count tasks
4214
4215         elsif Is_Library_Level_Entity (Id) then
4216            Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
4217
4218         --  If not library level entity, then indicate we don't know max
4219         --  tasks and also check task hierarchy restriction and blocking
4220         --  operation (since starting a task is definitely blocking).
4221
4222         else
4223            Check_Restriction (Max_Tasks, N);
4224            Check_Restriction (No_Task_Hierarchy, N);
4225            Check_Potentially_Blocking_Operation (N);
4226         end if;
4227
4228         --  A rather specialized test. If we see two tasks being declared
4229         --  of the same type in the same object declaration, and the task
4230         --  has an entry with an address clause, we know that program error
4231         --  will be raised at run time since we can't have two tasks with
4232         --  entries at the same address.
4233
4234         if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
4235            declare
4236               E : Entity_Id;
4237
4238            begin
4239               E := First_Entity (Etype (Id));
4240               while Present (E) loop
4241                  if Ekind (E) = E_Entry
4242                    and then Present (Get_Attribute_Definition_Clause
4243                                        (E, Attribute_Address))
4244                  then
4245                     Error_Msg_Warn := SPARK_Mode /= On;
4246                     Error_Msg_N
4247                       ("more than one task with same entry address<<", N);
4248                     Error_Msg_N ("\Program_Error [<<", N);
4249                     Insert_Action (N,
4250                       Make_Raise_Program_Error (Loc,
4251                         Reason => PE_Duplicated_Entry_Address));
4252                     exit;
4253                  end if;
4254
4255                  Next_Entity (E);
4256               end loop;
4257            end;
4258         end if;
4259      end if;
4260
4261      --  Some simple constant-propagation: if the expression is a constant
4262      --  string initialized with a literal, share the literal. This avoids
4263      --  a run-time copy.
4264
4265      if Present (E)
4266        and then Is_Entity_Name (E)
4267        and then Ekind (Entity (E)) = E_Constant
4268        and then Base_Type (Etype (E)) = Standard_String
4269      then
4270         declare
4271            Val : constant Node_Id := Constant_Value (Entity (E));
4272         begin
4273            if Present (Val) and then Nkind (Val) = N_String_Literal then
4274               Rewrite (E, New_Copy (Val));
4275            end if;
4276         end;
4277      end if;
4278
4279      --  Another optimization: if the nominal subtype is unconstrained and
4280      --  the expression is a function call that returns an unconstrained
4281      --  type, rewrite the declaration as a renaming of the result of the
4282      --  call. The exceptions below are cases where the copy is expected,
4283      --  either by the back end (Aliased case) or by the semantics, as for
4284      --  initializing controlled types or copying tags for classwide types.
4285
4286      if Present (E)
4287        and then Nkind (E) = N_Explicit_Dereference
4288        and then Nkind (Original_Node (E)) = N_Function_Call
4289        and then not Is_Library_Level_Entity (Id)
4290        and then not Is_Constrained (Underlying_Type (T))
4291        and then not Is_Aliased (Id)
4292        and then not Is_Class_Wide_Type (T)
4293        and then not Is_Controlled (T)
4294        and then not Has_Controlled_Component (Base_Type (T))
4295        and then Expander_Active
4296      then
4297         Rewrite (N,
4298           Make_Object_Renaming_Declaration (Loc,
4299             Defining_Identifier => Id,
4300             Access_Definition   => Empty,
4301             Subtype_Mark        => New_Occurrence_Of
4302                                      (Base_Type (Etype (Id)), Loc),
4303             Name                => E));
4304
4305         Set_Renamed_Object (Id, E);
4306
4307         --  Force generation of debugging information for the constant and for
4308         --  the renamed function call.
4309
4310         Set_Debug_Info_Needed (Id);
4311         Set_Debug_Info_Needed (Entity (Prefix (E)));
4312      end if;
4313
4314      if Present (Prev_Entity)
4315        and then Is_Frozen (Prev_Entity)
4316        and then not Error_Posted (Id)
4317      then
4318         Error_Msg_N ("full constant declaration appears too late", N);
4319      end if;
4320
4321      Check_Eliminated (Id);
4322
4323      --  Deal with setting In_Private_Part flag if in private part
4324
4325      if Ekind (Scope (Id)) = E_Package and then In_Private_Part (Scope (Id))
4326      then
4327         Set_In_Private_Part (Id);
4328      end if;
4329
4330      --  Check for violation of No_Local_Timing_Events
4331
4332      if Restriction_Check_Required (No_Local_Timing_Events)
4333        and then not Is_Library_Level_Entity (Id)
4334        and then Is_RTE (Etype (Id), RE_Timing_Event)
4335      then
4336         Check_Restriction (No_Local_Timing_Events, N);
4337      end if;
4338
4339   <<Leave>>
4340      --  Initialize the refined state of a variable here because this is a
4341      --  common destination for legal and illegal object declarations.
4342
4343      if Ekind (Id) = E_Variable then
4344         Set_Encapsulating_State (Id, Empty);
4345      end if;
4346
4347      if Has_Aspects (N) then
4348         Analyze_Aspect_Specifications (N, Id);
4349      end if;
4350
4351      Analyze_Dimension (N);
4352
4353      --  Verify whether the object declaration introduces an illegal hidden
4354      --  state within a package subject to a null abstract state.
4355
4356      if Ekind (Id) = E_Variable then
4357         Check_No_Hidden_State (Id);
4358      end if;
4359   end Analyze_Object_Declaration;
4360
4361   ---------------------------
4362   -- Analyze_Others_Choice --
4363   ---------------------------
4364
4365   --  Nothing to do for the others choice node itself, the semantic analysis
4366   --  of the others choice will occur as part of the processing of the parent
4367
4368   procedure Analyze_Others_Choice (N : Node_Id) is
4369      pragma Warnings (Off, N);
4370   begin
4371      null;
4372   end Analyze_Others_Choice;
4373
4374   -------------------------------------------
4375   -- Analyze_Private_Extension_Declaration --
4376   -------------------------------------------
4377
4378   procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
4379      T           : constant Entity_Id := Defining_Identifier (N);
4380      Indic       : constant Node_Id   := Subtype_Indication (N);
4381      Parent_Type : Entity_Id;
4382      Parent_Base : Entity_Id;
4383
4384   begin
4385      --  The private extension declaration may be subject to pragma Ghost with
4386      --  policy Ignore. Set the mode now to ensure that any nodes generated
4387      --  during analysis and expansion are properly flagged as ignored Ghost.
4388
4389      Set_Ghost_Mode (N);
4390
4391      --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
4392
4393      if Is_Non_Empty_List (Interface_List (N)) then
4394         declare
4395            Intf : Node_Id;
4396            T    : Entity_Id;
4397
4398         begin
4399            Intf := First (Interface_List (N));
4400            while Present (Intf) loop
4401               T := Find_Type_Of_Subtype_Indic (Intf);
4402
4403               Diagnose_Interface (Intf, T);
4404               Next (Intf);
4405            end loop;
4406         end;
4407      end if;
4408
4409      Generate_Definition (T);
4410
4411      --  For other than Ada 2012, just enter the name in the current scope
4412
4413      if Ada_Version < Ada_2012 then
4414         Enter_Name (T);
4415
4416      --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
4417      --  case of private type that completes an incomplete type.
4418
4419      else
4420         declare
4421            Prev : Entity_Id;
4422
4423         begin
4424            Prev := Find_Type_Name (N);
4425
4426            pragma Assert (Prev = T
4427              or else (Ekind (Prev) = E_Incomplete_Type
4428                        and then Present (Full_View (Prev))
4429                        and then Full_View (Prev) = T));
4430         end;
4431      end if;
4432
4433      Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
4434      Parent_Base := Base_Type (Parent_Type);
4435
4436      if Parent_Type = Any_Type or else Etype (Parent_Type) = Any_Type then
4437         Set_Ekind (T, Ekind (Parent_Type));
4438         Set_Etype (T, Any_Type);
4439         goto Leave;
4440
4441      elsif not Is_Tagged_Type (Parent_Type) then
4442         Error_Msg_N
4443           ("parent of type extension must be a tagged type ", Indic);
4444         goto Leave;
4445
4446      elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
4447         Error_Msg_N ("premature derivation of incomplete type", Indic);
4448         goto Leave;
4449
4450      elsif Is_Concurrent_Type (Parent_Type) then
4451         Error_Msg_N
4452           ("parent type of a private extension cannot be "
4453            & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
4454
4455         Set_Etype              (T, Any_Type);
4456         Set_Ekind              (T, E_Limited_Private_Type);
4457         Set_Private_Dependents (T, New_Elmt_List);
4458         Set_Error_Posted       (T);
4459         goto Leave;
4460      end if;
4461
4462      --  Perhaps the parent type should be changed to the class-wide type's
4463      --  specific type in this case to prevent cascading errors ???
4464
4465      if Is_Class_Wide_Type (Parent_Type) then
4466         Error_Msg_N
4467           ("parent of type extension must not be a class-wide type", Indic);
4468         goto Leave;
4469      end if;
4470
4471      if (not Is_Package_Or_Generic_Package (Current_Scope)
4472           and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
4473        or else In_Private_Part (Current_Scope)
4474
4475      then
4476         Error_Msg_N ("invalid context for private extension", N);
4477      end if;
4478
4479      --  Set common attributes
4480
4481      Set_Is_Pure          (T, Is_Pure (Current_Scope));
4482      Set_Scope            (T, Current_Scope);
4483      Set_Ekind            (T, E_Record_Type_With_Private);
4484      Init_Size_Align      (T);
4485      Set_Default_SSO      (T);
4486
4487      Set_Etype            (T,            Parent_Base);
4488      Set_Has_Task         (T, Has_Task  (Parent_Base));
4489      Set_Has_Protected    (T, Has_Task  (Parent_Base));
4490
4491      Set_Convention       (T, Convention     (Parent_Type));
4492      Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
4493      Set_Is_First_Subtype (T);
4494      Make_Class_Wide_Type (T);
4495
4496      if Unknown_Discriminants_Present (N) then
4497         Set_Discriminant_Constraint (T, No_Elist);
4498      end if;
4499
4500      Build_Derived_Record_Type (N, Parent_Type, T);
4501
4502      --  Propagate inherited invariant information. The new type has
4503      --  invariants, if the parent type has inheritable invariants,
4504      --  and these invariants can in turn be inherited.
4505
4506      if Has_Inheritable_Invariants (Parent_Type) then
4507         Set_Has_Inheritable_Invariants (T);
4508         Set_Has_Invariants (T);
4509      end if;
4510
4511      --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
4512      --  synchronized formal derived type.
4513
4514      if Ada_Version >= Ada_2005 and then Synchronized_Present (N) then
4515         Set_Is_Limited_Record (T);
4516
4517         --  Formal derived type case
4518
4519         if Is_Generic_Type (T) then
4520
4521            --  The parent must be a tagged limited type or a synchronized
4522            --  interface.
4523
4524            if (not Is_Tagged_Type (Parent_Type)
4525                 or else not Is_Limited_Type (Parent_Type))
4526              and then
4527                (not Is_Interface (Parent_Type)
4528                  or else not Is_Synchronized_Interface (Parent_Type))
4529            then
4530               Error_Msg_NE ("parent type of & must be tagged limited " &
4531                             "or synchronized", N, T);
4532            end if;
4533
4534            --  The progenitors (if any) must be limited or synchronized
4535            --  interfaces.
4536
4537            if Present (Interfaces (T)) then
4538               declare
4539                  Iface      : Entity_Id;
4540                  Iface_Elmt : Elmt_Id;
4541
4542               begin
4543                  Iface_Elmt := First_Elmt (Interfaces (T));
4544                  while Present (Iface_Elmt) loop
4545                     Iface := Node (Iface_Elmt);
4546
4547                     if not Is_Limited_Interface (Iface)
4548                       and then not Is_Synchronized_Interface (Iface)
4549                     then
4550                        Error_Msg_NE ("progenitor & must be limited " &
4551                                      "or synchronized", N, Iface);
4552                     end if;
4553
4554                     Next_Elmt (Iface_Elmt);
4555                  end loop;
4556               end;
4557            end if;
4558
4559         --  Regular derived extension, the parent must be a limited or
4560         --  synchronized interface.
4561
4562         else
4563            if not Is_Interface (Parent_Type)
4564              or else (not Is_Limited_Interface (Parent_Type)
4565                        and then not Is_Synchronized_Interface (Parent_Type))
4566            then
4567               Error_Msg_NE
4568                 ("parent type of & must be limited interface", N, T);
4569            end if;
4570         end if;
4571
4572      --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
4573      --  extension with a synchronized parent must be explicitly declared
4574      --  synchronized, because the full view will be a synchronized type.
4575      --  This must be checked before the check for limited types below,
4576      --  to ensure that types declared limited are not allowed to extend
4577      --  synchronized interfaces.
4578
4579      elsif Is_Interface (Parent_Type)
4580        and then Is_Synchronized_Interface (Parent_Type)
4581        and then not Synchronized_Present (N)
4582      then
4583         Error_Msg_NE
4584           ("private extension of& must be explicitly synchronized",
4585             N, Parent_Type);
4586
4587      elsif Limited_Present (N) then
4588         Set_Is_Limited_Record (T);
4589
4590         if not Is_Limited_Type (Parent_Type)
4591           and then
4592             (not Is_Interface (Parent_Type)
4593               or else not Is_Limited_Interface (Parent_Type))
4594         then
4595            Error_Msg_NE ("parent type& of limited extension must be limited",
4596              N, Parent_Type);
4597         end if;
4598      end if;
4599
4600   <<Leave>>
4601      if Has_Aspects (N) then
4602         Analyze_Aspect_Specifications (N, T);
4603      end if;
4604   end Analyze_Private_Extension_Declaration;
4605
4606   ---------------------------------
4607   -- Analyze_Subtype_Declaration --
4608   ---------------------------------
4609
4610   procedure Analyze_Subtype_Declaration
4611     (N    : Node_Id;
4612      Skip : Boolean := False)
4613   is
4614      Id       : constant Entity_Id := Defining_Identifier (N);
4615      T        : Entity_Id;
4616      R_Checks : Check_Result;
4617
4618   begin
4619      --  The subtype declaration may be subject to pragma Ghost with policy
4620      --  Ignore. Set the mode now to ensure that any nodes generated during
4621      --  analysis and expansion are properly flagged as ignored Ghost.
4622
4623      Set_Ghost_Mode (N);
4624
4625      Generate_Definition (Id);
4626      Set_Is_Pure (Id, Is_Pure (Current_Scope));
4627      Init_Size_Align (Id);
4628
4629      --  The following guard condition on Enter_Name is to handle cases where
4630      --  the defining identifier has already been entered into the scope but
4631      --  the declaration as a whole needs to be analyzed.
4632
4633      --  This case in particular happens for derived enumeration types. The
4634      --  derived enumeration type is processed as an inserted enumeration type
4635      --  declaration followed by a rewritten subtype declaration. The defining
4636      --  identifier, however, is entered into the name scope very early in the
4637      --  processing of the original type declaration and therefore needs to be
4638      --  avoided here, when the created subtype declaration is analyzed. (See
4639      --  Build_Derived_Types)
4640
4641      --  This also happens when the full view of a private type is derived
4642      --  type with constraints. In this case the entity has been introduced
4643      --  in the private declaration.
4644
4645      --  Finally this happens in some complex cases when validity checks are
4646      --  enabled, where the same subtype declaration may be analyzed twice.
4647      --  This can happen if the subtype is created by the pre-analysis of
4648      --  an attribute tht gives the range of a loop statement, and the loop
4649      --  itself appears within an if_statement that will be rewritten during
4650      --  expansion.
4651
4652      if Skip
4653        or else (Present (Etype (Id))
4654                  and then (Is_Private_Type (Etype (Id))
4655                             or else Is_Task_Type (Etype (Id))
4656                             or else Is_Rewrite_Substitution (N)))
4657      then
4658         null;
4659
4660      elsif Current_Entity (Id) = Id then
4661         null;
4662
4663      else
4664         Enter_Name (Id);
4665      end if;
4666
4667      T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
4668
4669      --  Class-wide equivalent types of records with unknown discriminants
4670      --  involve the generation of an itype which serves as the private view
4671      --  of a constrained record subtype. In such cases the base type of the
4672      --  current subtype we are processing is the private itype. Use the full
4673      --  of the private itype when decorating various attributes.
4674
4675      if Is_Itype (T)
4676        and then Is_Private_Type (T)
4677        and then Present (Full_View (T))
4678      then
4679         T := Full_View (T);
4680      end if;
4681
4682      --  Inherit common attributes
4683
4684      Set_Is_Volatile       (Id, Is_Volatile       (T));
4685      Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
4686      Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
4687      Set_Convention        (Id, Convention        (T));
4688
4689      --  If ancestor has predicates then so does the subtype, and in addition
4690      --  we must delay the freeze to properly arrange predicate inheritance.
4691
4692      --  The Ancestor_Type test is really unpleasant, there seem to be cases
4693      --  in which T = ID, so the above tests and assignments do nothing???
4694
4695      if Has_Predicates (T)
4696        or else (Present (Ancestor_Subtype (T))
4697                  and then Has_Predicates (Ancestor_Subtype (T)))
4698      then
4699         Set_Has_Predicates (Id);
4700         Set_Has_Delayed_Freeze (Id);
4701      end if;
4702
4703      --  Subtype of Boolean cannot have a constraint in SPARK
4704
4705      if Is_Boolean_Type (T)
4706        and then Nkind (Subtype_Indication (N)) = N_Subtype_Indication
4707      then
4708         Check_SPARK_05_Restriction
4709           ("subtype of Boolean cannot have constraint", N);
4710      end if;
4711
4712      if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4713         declare
4714            Cstr     : constant Node_Id := Constraint (Subtype_Indication (N));
4715            One_Cstr : Node_Id;
4716            Low      : Node_Id;
4717            High     : Node_Id;
4718
4719         begin
4720            if Nkind (Cstr) = N_Index_Or_Discriminant_Constraint then
4721               One_Cstr := First (Constraints (Cstr));
4722               while Present (One_Cstr) loop
4723
4724                  --  Index or discriminant constraint in SPARK must be a
4725                  --  subtype mark.
4726
4727                  if not
4728                    Nkind_In (One_Cstr, N_Identifier, N_Expanded_Name)
4729                  then
4730                     Check_SPARK_05_Restriction
4731                       ("subtype mark required", One_Cstr);
4732
4733                  --  String subtype must have a lower bound of 1 in SPARK.
4734                  --  Note that we do not need to test for the non-static case
4735                  --  here, since that was already taken care of in
4736                  --  Process_Range_Expr_In_Decl.
4737
4738                  elsif Base_Type (T) = Standard_String then
4739                     Get_Index_Bounds (One_Cstr, Low, High);
4740
4741                     if Is_OK_Static_Expression (Low)
4742                       and then Expr_Value (Low) /= 1
4743                     then
4744                        Check_SPARK_05_Restriction
4745                          ("String subtype must have lower bound of 1", N);
4746                     end if;
4747                  end if;
4748
4749                  Next (One_Cstr);
4750               end loop;
4751            end if;
4752         end;
4753      end if;
4754
4755      --  In the case where there is no constraint given in the subtype
4756      --  indication, Process_Subtype just returns the Subtype_Mark, so its
4757      --  semantic attributes must be established here.
4758
4759      if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
4760         Set_Etype (Id, Base_Type (T));
4761
4762         --  Subtype of unconstrained array without constraint is not allowed
4763         --  in SPARK.
4764
4765         if Is_Array_Type (T) and then not Is_Constrained (T) then
4766            Check_SPARK_05_Restriction
4767              ("subtype of unconstrained array must have constraint", N);
4768         end if;
4769
4770         case Ekind (T) is
4771            when Array_Kind =>
4772               Set_Ekind                       (Id, E_Array_Subtype);
4773               Copy_Array_Subtype_Attributes   (Id, T);
4774
4775            when Decimal_Fixed_Point_Kind =>
4776               Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
4777               Set_Digits_Value         (Id, Digits_Value       (T));
4778               Set_Delta_Value          (Id, Delta_Value        (T));
4779               Set_Scale_Value          (Id, Scale_Value        (T));
4780               Set_Small_Value          (Id, Small_Value        (T));
4781               Set_Scalar_Range         (Id, Scalar_Range       (T));
4782               Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
4783               Set_Is_Constrained       (Id, Is_Constrained     (T));
4784               Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4785               Set_RM_Size              (Id, RM_Size            (T));
4786
4787            when Enumeration_Kind =>
4788               Set_Ekind                (Id, E_Enumeration_Subtype);
4789               Set_First_Literal        (Id, First_Literal (Base_Type (T)));
4790               Set_Scalar_Range         (Id, Scalar_Range       (T));
4791               Set_Is_Character_Type    (Id, Is_Character_Type  (T));
4792               Set_Is_Constrained       (Id, Is_Constrained     (T));
4793               Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4794               Set_RM_Size              (Id, RM_Size            (T));
4795               Inherit_Predicate_Flags  (Id, T);
4796
4797            when Ordinary_Fixed_Point_Kind =>
4798               Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
4799               Set_Scalar_Range         (Id, Scalar_Range       (T));
4800               Set_Small_Value          (Id, Small_Value        (T));
4801               Set_Delta_Value          (Id, Delta_Value        (T));
4802               Set_Is_Constrained       (Id, Is_Constrained     (T));
4803               Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4804               Set_RM_Size              (Id, RM_Size            (T));
4805
4806            when Float_Kind =>
4807               Set_Ekind                (Id, E_Floating_Point_Subtype);
4808               Set_Scalar_Range         (Id, Scalar_Range       (T));
4809               Set_Digits_Value         (Id, Digits_Value       (T));
4810               Set_Is_Constrained       (Id, Is_Constrained     (T));
4811
4812            when Signed_Integer_Kind =>
4813               Set_Ekind                (Id, E_Signed_Integer_Subtype);
4814               Set_Scalar_Range         (Id, Scalar_Range       (T));
4815               Set_Is_Constrained       (Id, Is_Constrained     (T));
4816               Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4817               Set_RM_Size              (Id, RM_Size            (T));
4818               Inherit_Predicate_Flags  (Id, T);
4819
4820            when Modular_Integer_Kind =>
4821               Set_Ekind                (Id, E_Modular_Integer_Subtype);
4822               Set_Scalar_Range         (Id, Scalar_Range       (T));
4823               Set_Is_Constrained       (Id, Is_Constrained     (T));
4824               Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4825               Set_RM_Size              (Id, RM_Size            (T));
4826               Inherit_Predicate_Flags  (Id, T);
4827
4828            when Class_Wide_Kind =>
4829               Set_Ekind                (Id, E_Class_Wide_Subtype);
4830               Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
4831               Set_Cloned_Subtype       (Id, T);
4832               Set_Is_Tagged_Type       (Id, True);
4833               Set_Has_Unknown_Discriminants
4834                                        (Id, True);
4835               Set_No_Tagged_Streams_Pragma
4836                                        (Id, No_Tagged_Streams_Pragma (T));
4837
4838               if Ekind (T) = E_Class_Wide_Subtype then
4839                  Set_Equivalent_Type   (Id, Equivalent_Type    (T));
4840               end if;
4841
4842            when E_Record_Type | E_Record_Subtype =>
4843               Set_Ekind                (Id, E_Record_Subtype);
4844
4845               if Ekind (T) = E_Record_Subtype
4846                 and then Present (Cloned_Subtype (T))
4847               then
4848                  Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
4849               else
4850                  Set_Cloned_Subtype    (Id, T);
4851               end if;
4852
4853               Set_First_Entity         (Id, First_Entity       (T));
4854               Set_Last_Entity          (Id, Last_Entity        (T));
4855               Set_Has_Discriminants    (Id, Has_Discriminants  (T));
4856               Set_Is_Constrained       (Id, Is_Constrained     (T));
4857               Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
4858               Set_Has_Implicit_Dereference
4859                                        (Id, Has_Implicit_Dereference (T));
4860               Set_Has_Unknown_Discriminants
4861                                        (Id, Has_Unknown_Discriminants (T));
4862
4863               if Has_Discriminants (T) then
4864                  Set_Discriminant_Constraint
4865                                        (Id, Discriminant_Constraint (T));
4866                  Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4867
4868               elsif Has_Unknown_Discriminants (Id) then
4869                  Set_Discriminant_Constraint (Id, No_Elist);
4870               end if;
4871
4872               if Is_Tagged_Type (T) then
4873                  Set_Is_Tagged_Type    (Id, True);
4874                  Set_No_Tagged_Streams_Pragma
4875                                        (Id, No_Tagged_Streams_Pragma (T));
4876                  Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
4877                  Set_Direct_Primitive_Operations
4878                                        (Id, Direct_Primitive_Operations (T));
4879                  Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
4880
4881                  if Is_Interface (T) then
4882                     Set_Is_Interface (Id);
4883                     Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
4884                  end if;
4885               end if;
4886
4887            when Private_Kind =>
4888               Set_Ekind              (Id, Subtype_Kind (Ekind        (T)));
4889               Set_Has_Discriminants  (Id, Has_Discriminants          (T));
4890               Set_Is_Constrained     (Id, Is_Constrained             (T));
4891               Set_First_Entity       (Id, First_Entity               (T));
4892               Set_Last_Entity        (Id, Last_Entity                (T));
4893               Set_Private_Dependents (Id, New_Elmt_List);
4894               Set_Is_Limited_Record  (Id, Is_Limited_Record          (T));
4895               Set_Has_Implicit_Dereference
4896                                      (Id, Has_Implicit_Dereference   (T));
4897               Set_Has_Unknown_Discriminants
4898                                      (Id, Has_Unknown_Discriminants  (T));
4899               Set_Known_To_Have_Preelab_Init
4900                                      (Id, Known_To_Have_Preelab_Init (T));
4901
4902               if Is_Tagged_Type (T) then
4903                  Set_Is_Tagged_Type              (Id);
4904                  Set_No_Tagged_Streams_Pragma    (Id,
4905                    No_Tagged_Streams_Pragma (T));
4906                  Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
4907                  Set_Class_Wide_Type             (Id, Class_Wide_Type  (T));
4908                  Set_Direct_Primitive_Operations (Id,
4909                    Direct_Primitive_Operations (T));
4910               end if;
4911
4912               --  In general the attributes of the subtype of a private type
4913               --  are the attributes of the partial view of parent. However,
4914               --  the full view may be a discriminated type, and the subtype
4915               --  must share the discriminant constraint to generate correct
4916               --  calls to initialization procedures.
4917
4918               if Has_Discriminants (T) then
4919                  Set_Discriminant_Constraint
4920                    (Id, Discriminant_Constraint (T));
4921                  Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4922
4923               elsif Present (Full_View (T))
4924                 and then Has_Discriminants (Full_View (T))
4925               then
4926                  Set_Discriminant_Constraint
4927                    (Id, Discriminant_Constraint (Full_View (T)));
4928                  Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4929
4930                  --  This would seem semantically correct, but apparently
4931                  --  generates spurious errors about missing components ???
4932
4933                  --  Set_Has_Discriminants (Id);
4934               end if;
4935
4936               Prepare_Private_Subtype_Completion (Id, N);
4937
4938               --  If this is the subtype of a constrained private type with
4939               --  discriminants that has got a full view and we also have
4940               --  built a completion just above, show that the completion
4941               --  is a clone of the full view to the back-end.
4942
4943               if Has_Discriminants (T)
4944                  and then not Has_Unknown_Discriminants (T)
4945                  and then not Is_Empty_Elmt_List (Discriminant_Constraint (T))
4946                  and then Present (Full_View (T))
4947                  and then Present (Full_View (Id))
4948               then
4949                  Set_Cloned_Subtype (Full_View (Id), Full_View (T));
4950               end if;
4951
4952            when Access_Kind =>
4953               Set_Ekind             (Id, E_Access_Subtype);
4954               Set_Is_Constrained    (Id, Is_Constrained        (T));
4955               Set_Is_Access_Constant
4956                                     (Id, Is_Access_Constant    (T));
4957               Set_Directly_Designated_Type
4958                                     (Id, Designated_Type       (T));
4959               Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4960
4961               --  A Pure library_item must not contain the declaration of a
4962               --  named access type, except within a subprogram, generic
4963               --  subprogram, task unit, or protected unit, or if it has
4964               --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4965
4966               if Comes_From_Source (Id)
4967                 and then In_Pure_Unit
4968                 and then not In_Subprogram_Task_Protected_Unit
4969                 and then not No_Pool_Assigned (Id)
4970               then
4971                  Error_Msg_N
4972                    ("named access types not allowed in pure unit", N);
4973               end if;
4974
4975            when Concurrent_Kind =>
4976               Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4977               Set_Corresponding_Record_Type (Id,
4978                                         Corresponding_Record_Type (T));
4979               Set_First_Entity         (Id, First_Entity          (T));
4980               Set_First_Private_Entity (Id, First_Private_Entity  (T));
4981               Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4982               Set_Is_Constrained       (Id, Is_Constrained        (T));
4983               Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4984               Set_Last_Entity          (Id, Last_Entity           (T));
4985
4986               if Is_Tagged_Type (T) then
4987                  Set_No_Tagged_Streams_Pragma
4988                    (Id, No_Tagged_Streams_Pragma (T));
4989               end if;
4990
4991               if Has_Discriminants (T) then
4992                  Set_Discriminant_Constraint
4993                    (Id, Discriminant_Constraint (T));
4994                  Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4995               end if;
4996
4997            when Incomplete_Kind  =>
4998               if Ada_Version >= Ada_2005 then
4999
5000                  --  In Ada 2005 an incomplete type can be explicitly tagged:
5001                  --  propagate indication. Note that we also have to include
5002                  --  subtypes for Ada 2012 extended use of incomplete types.
5003
5004                  Set_Ekind              (Id, E_Incomplete_Subtype);
5005                  Set_Is_Tagged_Type     (Id, Is_Tagged_Type (T));
5006                  Set_Private_Dependents (Id, New_Elmt_List);
5007
5008                  if Is_Tagged_Type (Id) then
5009                     Set_No_Tagged_Streams_Pragma
5010                       (Id, No_Tagged_Streams_Pragma (T));
5011                     Set_Direct_Primitive_Operations (Id, New_Elmt_List);
5012                  end if;
5013
5014                  --  Ada 2005 (AI-412): Decorate an incomplete subtype of an
5015                  --  incomplete type visible through a limited with clause.
5016
5017                  if From_Limited_With (T)
5018                    and then Present (Non_Limited_View (T))
5019                  then
5020                     Set_From_Limited_With (Id);
5021                     Set_Non_Limited_View  (Id, Non_Limited_View (T));
5022
5023                  --  Ada 2005 (AI-412): Add the regular incomplete subtype
5024                  --  to the private dependents of the original incomplete
5025                  --  type for future transformation.
5026
5027                  else
5028                     Append_Elmt (Id, Private_Dependents (T));
5029                  end if;
5030
5031               --  If the subtype name denotes an incomplete type an error
5032               --  was already reported by Process_Subtype.
5033
5034               else
5035                  Set_Etype (Id, Any_Type);
5036               end if;
5037
5038            when others =>
5039               raise Program_Error;
5040         end case;
5041      end if;
5042
5043      if Etype (Id) = Any_Type then
5044         goto Leave;
5045      end if;
5046
5047      --  Some common processing on all types
5048
5049      Set_Size_Info      (Id, T);
5050      Set_First_Rep_Item (Id, First_Rep_Item (T));
5051
5052      --  If the parent type is a generic actual, so is the subtype. This may
5053      --  happen in a nested instance. Why Comes_From_Source test???
5054
5055      if not Comes_From_Source (N) then
5056         Set_Is_Generic_Actual_Type (Id, Is_Generic_Actual_Type (T));
5057      end if;
5058
5059      T := Etype (Id);
5060
5061      Set_Is_Immediately_Visible   (Id, True);
5062      Set_Depends_On_Private       (Id, Has_Private_Component (T));
5063      Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
5064
5065      if Is_Interface (T) then
5066         Set_Is_Interface (Id);
5067      end if;
5068
5069      if Present (Generic_Parent_Type (N))
5070        and then
5071          (Nkind (Parent (Generic_Parent_Type (N))) /=
5072                                              N_Formal_Type_Declaration
5073            or else Nkind (Formal_Type_Definition
5074                            (Parent (Generic_Parent_Type (N)))) /=
5075                                              N_Formal_Private_Type_Definition)
5076      then
5077         if Is_Tagged_Type (Id) then
5078
5079            --  If this is a generic actual subtype for a synchronized type,
5080            --  the primitive operations are those of the corresponding record
5081            --  for which there is a separate subtype declaration.
5082
5083            if Is_Concurrent_Type (Id) then
5084               null;
5085            elsif Is_Class_Wide_Type (Id) then
5086               Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
5087            else
5088               Derive_Subprograms (Generic_Parent_Type (N), Id, T);
5089            end if;
5090
5091         elsif Scope (Etype (Id)) /= Standard_Standard then
5092            Derive_Subprograms (Generic_Parent_Type (N), Id);
5093         end if;
5094      end if;
5095
5096      if Is_Private_Type (T) and then Present (Full_View (T)) then
5097         Conditional_Delay (Id, Full_View (T));
5098
5099      --  The subtypes of components or subcomponents of protected types
5100      --  do not need freeze nodes, which would otherwise appear in the
5101      --  wrong scope (before the freeze node for the protected type). The
5102      --  proper subtypes are those of the subcomponents of the corresponding
5103      --  record.
5104
5105      elsif Ekind (Scope (Id)) /= E_Protected_Type
5106        and then Present (Scope (Scope (Id))) -- error defense
5107        and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
5108      then
5109         Conditional_Delay (Id, T);
5110      end if;
5111
5112      --  Check that Constraint_Error is raised for a scalar subtype indication
5113      --  when the lower or upper bound of a non-null range lies outside the
5114      --  range of the type mark.
5115
5116      if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
5117         if Is_Scalar_Type (Etype (Id))
5118            and then Scalar_Range (Id) /=
5119                     Scalar_Range (Etype (Subtype_Mark
5120                                           (Subtype_Indication (N))))
5121         then
5122            Apply_Range_Check
5123              (Scalar_Range (Id),
5124               Etype (Subtype_Mark (Subtype_Indication (N))));
5125
5126         --  In the array case, check compatibility for each index
5127
5128         elsif Is_Array_Type (Etype (Id)) and then Present (First_Index (Id))
5129         then
5130            --  This really should be a subprogram that finds the indications
5131            --  to check???
5132
5133            declare
5134               Subt_Index   : Node_Id := First_Index (Id);
5135               Target_Index : Node_Id :=
5136                                First_Index (Etype
5137                                  (Subtype_Mark (Subtype_Indication (N))));
5138               Has_Dyn_Chk  : Boolean := Has_Dynamic_Range_Check (N);
5139
5140            begin
5141               while Present (Subt_Index) loop
5142                  if ((Nkind (Subt_Index) = N_Identifier
5143                        and then Ekind (Entity (Subt_Index)) in Scalar_Kind)
5144                       or else Nkind (Subt_Index) = N_Subtype_Indication)
5145                    and then
5146                      Nkind (Scalar_Range (Etype (Subt_Index))) = N_Range
5147                  then
5148                     declare
5149                        Target_Typ : constant Entity_Id :=
5150                                       Etype (Target_Index);
5151                     begin
5152                        R_Checks :=
5153                          Get_Range_Checks
5154                            (Scalar_Range (Etype (Subt_Index)),
5155                             Target_Typ,
5156                             Etype (Subt_Index),
5157                             Defining_Identifier (N));
5158
5159                        --  Reset Has_Dynamic_Range_Check on the subtype to
5160                        --  prevent elision of the index check due to a dynamic
5161                        --  check generated for a preceding index (needed since
5162                        --  Insert_Range_Checks tries to avoid generating
5163                        --  redundant checks on a given declaration).
5164
5165                        Set_Has_Dynamic_Range_Check (N, False);
5166
5167                        Insert_Range_Checks
5168                          (R_Checks,
5169                           N,
5170                           Target_Typ,
5171                           Sloc (Defining_Identifier (N)));
5172
5173                        --  Record whether this index involved a dynamic check
5174
5175                        Has_Dyn_Chk :=
5176                          Has_Dyn_Chk or else Has_Dynamic_Range_Check (N);
5177                     end;
5178                  end if;
5179
5180                  Next_Index (Subt_Index);
5181                  Next_Index (Target_Index);
5182               end loop;
5183
5184               --  Finally, mark whether the subtype involves dynamic checks
5185
5186               Set_Has_Dynamic_Range_Check (N, Has_Dyn_Chk);
5187            end;
5188         end if;
5189      end if;
5190
5191      --  A type invariant applies to any subtype in its scope, in particular
5192      --  to a generic actual.
5193
5194      if Has_Invariants (T) and then In_Open_Scopes (Scope (T)) then
5195         Set_Has_Invariants (Id);
5196         Set_Invariant_Procedure (Id, Invariant_Procedure (T));
5197      end if;
5198
5199      --  Make sure that generic actual types are properly frozen. The subtype
5200      --  is marked as a generic actual type when the enclosing instance is
5201      --  analyzed, so here we identify the subtype from the tree structure.
5202
5203      if Expander_Active
5204        and then Is_Generic_Actual_Type (Id)
5205        and then In_Instance
5206        and then not Comes_From_Source (N)
5207        and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
5208        and then Is_Frozen (T)
5209      then
5210         Freeze_Before (N, Id);
5211      end if;
5212
5213      Set_Optimize_Alignment_Flags (Id);
5214      Check_Eliminated (Id);
5215
5216   <<Leave>>
5217      if Has_Aspects (N) then
5218         Analyze_Aspect_Specifications (N, Id);
5219      end if;
5220
5221      Analyze_Dimension (N);
5222   end Analyze_Subtype_Declaration;
5223
5224   --------------------------------
5225   -- Analyze_Subtype_Indication --
5226   --------------------------------
5227
5228   procedure Analyze_Subtype_Indication (N : Node_Id) is
5229      T : constant Entity_Id := Subtype_Mark (N);
5230      R : constant Node_Id   := Range_Expression (Constraint (N));
5231
5232   begin
5233      Analyze (T);
5234
5235      if R /= Error then
5236         Analyze (R);
5237         Set_Etype (N, Etype (R));
5238         Resolve (R, Entity (T));
5239      else
5240         Set_Error_Posted (R);
5241         Set_Error_Posted (T);
5242      end if;
5243   end Analyze_Subtype_Indication;
5244
5245   --------------------------
5246   -- Analyze_Variant_Part --
5247   --------------------------
5248
5249   procedure Analyze_Variant_Part (N : Node_Id) is
5250      Discr_Name : Node_Id;
5251      Discr_Type : Entity_Id;
5252
5253      procedure Process_Variant (A : Node_Id);
5254      --  Analyze declarations for a single variant
5255
5256      package Analyze_Variant_Choices is
5257        new Generic_Analyze_Choices (Process_Variant);
5258      use Analyze_Variant_Choices;
5259
5260      ---------------------
5261      -- Process_Variant --
5262      ---------------------
5263
5264      procedure Process_Variant (A : Node_Id) is
5265         CL : constant Node_Id := Component_List (A);
5266      begin
5267         if not Null_Present (CL) then
5268            Analyze_Declarations (Component_Items (CL));
5269
5270            if Present (Variant_Part (CL)) then
5271               Analyze (Variant_Part (CL));
5272            end if;
5273         end if;
5274      end Process_Variant;
5275
5276   --  Start of processing for Analyze_Variant_Part
5277
5278   begin
5279      Discr_Name := Name (N);
5280      Analyze (Discr_Name);
5281
5282      --  If Discr_Name bad, get out (prevent cascaded errors)
5283
5284      if Etype (Discr_Name) = Any_Type then
5285         return;
5286      end if;
5287
5288      --  Check invalid discriminant in variant part
5289
5290      if Ekind (Entity (Discr_Name)) /= E_Discriminant then
5291         Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
5292      end if;
5293
5294      Discr_Type := Etype (Entity (Discr_Name));
5295
5296      if not Is_Discrete_Type (Discr_Type) then
5297         Error_Msg_N
5298           ("discriminant in a variant part must be of a discrete type",
5299             Name (N));
5300         return;
5301      end if;
5302
5303      --  Now analyze the choices, which also analyzes the declarations that
5304      --  are associated with each choice.
5305
5306      Analyze_Choices (Variants (N), Discr_Type);
5307
5308      --  Note: we used to instantiate and call Check_Choices here to check
5309      --  that the choices covered the discriminant, but it's too early to do
5310      --  that because of statically predicated subtypes, whose analysis may
5311      --  be deferred to their freeze point which may be as late as the freeze
5312      --  point of the containing record. So this call is now to be found in
5313      --  Freeze_Record_Declaration.
5314
5315   end Analyze_Variant_Part;
5316
5317   ----------------------------
5318   -- Array_Type_Declaration --
5319   ----------------------------
5320
5321   procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
5322      Component_Def : constant Node_Id := Component_Definition (Def);
5323      Component_Typ : constant Node_Id := Subtype_Indication (Component_Def);
5324      Element_Type  : Entity_Id;
5325      Implicit_Base : Entity_Id;
5326      Index         : Node_Id;
5327      Related_Id    : Entity_Id := Empty;
5328      Nb_Index      : Nat;
5329      P             : constant Node_Id := Parent (Def);
5330      Priv          : Entity_Id;
5331
5332   begin
5333      if Nkind (Def) = N_Constrained_Array_Definition then
5334         Index := First (Discrete_Subtype_Definitions (Def));
5335      else
5336         Index := First (Subtype_Marks (Def));
5337      end if;
5338
5339      --  Find proper names for the implicit types which may be public. In case
5340      --  of anonymous arrays we use the name of the first object of that type
5341      --  as prefix.
5342
5343      if No (T) then
5344         Related_Id := Defining_Identifier (P);
5345      else
5346         Related_Id := T;
5347      end if;
5348
5349      Nb_Index := 1;
5350      while Present (Index) loop
5351         Analyze (Index);
5352
5353         --  Test for odd case of trying to index a type by the type itself
5354
5355         if Is_Entity_Name (Index) and then Entity (Index) = T then
5356            Error_Msg_N ("type& cannot be indexed by itself", Index);
5357            Set_Entity (Index, Standard_Boolean);
5358            Set_Etype (Index, Standard_Boolean);
5359         end if;
5360
5361         --  Check SPARK restriction requiring a subtype mark
5362
5363         if not Nkind_In (Index, N_Identifier, N_Expanded_Name) then
5364            Check_SPARK_05_Restriction ("subtype mark required", Index);
5365         end if;
5366
5367         --  Add a subtype declaration for each index of private array type
5368         --  declaration whose etype is also private. For example:
5369
5370         --     package Pkg is
5371         --        type Index is private;
5372         --     private
5373         --        type Table is array (Index) of ...
5374         --     end;
5375
5376         --  This is currently required by the expander for the internally
5377         --  generated equality subprogram of records with variant parts in
5378         --  which the etype of some component is such private type.
5379
5380         if Ekind (Current_Scope) = E_Package
5381           and then In_Private_Part (Current_Scope)
5382           and then Has_Private_Declaration (Etype (Index))
5383         then
5384            declare
5385               Loc   : constant Source_Ptr := Sloc (Def);
5386               New_E : Entity_Id;
5387               Decl  : Entity_Id;
5388
5389            begin
5390               New_E := Make_Temporary (Loc, 'T');
5391               Set_Is_Internal (New_E);
5392
5393               Decl :=
5394                 Make_Subtype_Declaration (Loc,
5395                   Defining_Identifier => New_E,
5396                   Subtype_Indication  =>
5397                     New_Occurrence_Of (Etype (Index), Loc));
5398
5399               Insert_Before (Parent (Def), Decl);
5400               Analyze (Decl);
5401               Set_Etype (Index, New_E);
5402
5403               --  If the index is a range the Entity attribute is not
5404               --  available. Example:
5405
5406               --     package Pkg is
5407               --        type T is private;
5408               --     private
5409               --        type T is new Natural;
5410               --        Table : array (T(1) .. T(10)) of Boolean;
5411               --     end Pkg;
5412
5413               if Nkind (Index) /= N_Range then
5414                  Set_Entity (Index, New_E);
5415               end if;
5416            end;
5417         end if;
5418
5419         Make_Index (Index, P, Related_Id, Nb_Index);
5420
5421         --  Check error of subtype with predicate for index type
5422
5423         Bad_Predicated_Subtype_Use
5424           ("subtype& has predicate, not allowed as index subtype",
5425            Index, Etype (Index));
5426
5427         --  Move to next index
5428
5429         Next_Index (Index);
5430         Nb_Index := Nb_Index + 1;
5431      end loop;
5432
5433      --  Process subtype indication if one is present
5434
5435      if Present (Component_Typ) then
5436         Element_Type := Process_Subtype (Component_Typ, P, Related_Id, 'C');
5437
5438         Set_Etype (Component_Typ, Element_Type);
5439
5440         if not Nkind_In (Component_Typ, N_Identifier, N_Expanded_Name) then
5441            Check_SPARK_05_Restriction
5442              ("subtype mark required", Component_Typ);
5443         end if;
5444
5445      --  Ada 2005 (AI-230): Access Definition case
5446
5447      else pragma Assert (Present (Access_Definition (Component_Def)));
5448
5449         --  Indicate that the anonymous access type is created by the
5450         --  array type declaration.
5451
5452         Element_Type := Access_Definition
5453                           (Related_Nod => P,
5454                            N           => Access_Definition (Component_Def));
5455         Set_Is_Local_Anonymous_Access (Element_Type);
5456
5457         --  Propagate the parent. This field is needed if we have to generate
5458         --  the master_id associated with an anonymous access to task type
5459         --  component (see Expand_N_Full_Type_Declaration.Build_Master)
5460
5461         Set_Parent (Element_Type, Parent (T));
5462
5463         --  Ada 2005 (AI-230): In case of components that are anonymous access
5464         --  types the level of accessibility depends on the enclosing type
5465         --  declaration
5466
5467         Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
5468
5469         --  Ada 2005 (AI-254)
5470
5471         declare
5472            CD : constant Node_Id :=
5473                   Access_To_Subprogram_Definition
5474                     (Access_Definition (Component_Def));
5475         begin
5476            if Present (CD) and then Protected_Present (CD) then
5477               Element_Type :=
5478                 Replace_Anonymous_Access_To_Protected_Subprogram (Def);
5479            end if;
5480         end;
5481      end if;
5482
5483      --  Constrained array case
5484
5485      if No (T) then
5486         T := Create_Itype (E_Void, P, Related_Id, 'T');
5487      end if;
5488
5489      if Nkind (Def) = N_Constrained_Array_Definition then
5490
5491         --  Establish Implicit_Base as unconstrained base type
5492
5493         Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
5494
5495         Set_Etype              (Implicit_Base, Implicit_Base);
5496         Set_Scope              (Implicit_Base, Current_Scope);
5497         Set_Has_Delayed_Freeze (Implicit_Base);
5498         Set_Default_SSO        (Implicit_Base);
5499
5500         --  The constrained array type is a subtype of the unconstrained one
5501
5502         Set_Ekind              (T, E_Array_Subtype);
5503         Init_Size_Align        (T);
5504         Set_Etype              (T, Implicit_Base);
5505         Set_Scope              (T, Current_Scope);
5506         Set_Is_Constrained     (T);
5507         Set_First_Index        (T,
5508           First (Discrete_Subtype_Definitions (Def)));
5509         Set_Has_Delayed_Freeze (T);
5510
5511         --  Complete setup of implicit base type
5512
5513         Set_First_Index       (Implicit_Base, First_Index (T));
5514         Set_Component_Type    (Implicit_Base, Element_Type);
5515         Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
5516         Set_Has_Protected     (Implicit_Base, Has_Protected (Element_Type));
5517         Set_Component_Size    (Implicit_Base, Uint_0);
5518         Set_Packed_Array_Impl_Type (Implicit_Base, Empty);
5519         Set_Has_Controlled_Component (Implicit_Base,
5520           Has_Controlled_Component (Element_Type)
5521             or else Is_Controlled  (Element_Type));
5522         Set_Finalize_Storage_Only (Implicit_Base,
5523           Finalize_Storage_Only (Element_Type));
5524
5525         --  Inherit the "ghostness" from the constrained array type
5526
5527         if Is_Ghost_Entity (T) or else Ghost_Mode > None then
5528            Set_Is_Ghost_Entity (Implicit_Base);
5529         end if;
5530
5531      --  Unconstrained array case
5532
5533      else
5534         Set_Ekind                    (T, E_Array_Type);
5535         Init_Size_Align              (T);
5536         Set_Etype                    (T, T);
5537         Set_Scope                    (T, Current_Scope);
5538         Set_Component_Size           (T, Uint_0);
5539         Set_Is_Constrained           (T, False);
5540         Set_First_Index              (T, First (Subtype_Marks (Def)));
5541         Set_Has_Delayed_Freeze       (T, True);
5542         Set_Has_Task                 (T, Has_Task      (Element_Type));
5543         Set_Has_Protected            (T, Has_Protected (Element_Type));
5544         Set_Has_Controlled_Component (T, Has_Controlled_Component
5545                                                        (Element_Type)
5546                                            or else
5547                                          Is_Controlled (Element_Type));
5548         Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
5549                                                        (Element_Type));
5550         Set_Default_SSO              (T);
5551      end if;
5552
5553      --  Common attributes for both cases
5554
5555      Set_Component_Type (Base_Type (T), Element_Type);
5556      Set_Packed_Array_Impl_Type (T, Empty);
5557
5558      if Aliased_Present (Component_Definition (Def)) then
5559         Check_SPARK_05_Restriction
5560           ("aliased is not allowed", Component_Definition (Def));
5561         Set_Has_Aliased_Components (Etype (T));
5562      end if;
5563
5564      --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
5565      --  array type to ensure that objects of this type are initialized.
5566
5567      if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (Element_Type) then
5568         Set_Can_Never_Be_Null (T);
5569
5570         if Null_Exclusion_Present (Component_Definition (Def))
5571
5572            --  No need to check itypes because in their case this check was
5573            --  done at their point of creation
5574
5575           and then not Is_Itype (Element_Type)
5576         then
5577            Error_Msg_N
5578              ("`NOT NULL` not allowed (null already excluded)",
5579               Subtype_Indication (Component_Definition (Def)));
5580         end if;
5581      end if;
5582
5583      Priv := Private_Component (Element_Type);
5584
5585      if Present (Priv) then
5586
5587         --  Check for circular definitions
5588
5589         if Priv = Any_Type then
5590            Set_Component_Type (Etype (T), Any_Type);
5591
5592         --  There is a gap in the visibility of operations on the composite
5593         --  type only if the component type is defined in a different scope.
5594
5595         elsif Scope (Priv) = Current_Scope then
5596            null;
5597
5598         elsif Is_Limited_Type (Priv) then
5599            Set_Is_Limited_Composite (Etype (T));
5600            Set_Is_Limited_Composite (T);
5601         else
5602            Set_Is_Private_Composite (Etype (T));
5603            Set_Is_Private_Composite (T);
5604         end if;
5605      end if;
5606
5607      --  A syntax error in the declaration itself may lead to an empty index
5608      --  list, in which case do a minimal patch.
5609
5610      if No (First_Index (T)) then
5611         Error_Msg_N ("missing index definition in array type declaration", T);
5612
5613         declare
5614            Indexes : constant List_Id :=
5615                        New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
5616         begin
5617            Set_Discrete_Subtype_Definitions (Def, Indexes);
5618            Set_First_Index (T, First (Indexes));
5619            return;
5620         end;
5621      end if;
5622
5623      --  Create a concatenation operator for the new type. Internal array
5624      --  types created for packed entities do not need such, they are
5625      --  compatible with the user-defined type.
5626
5627      if Number_Dimensions (T) = 1
5628        and then not Is_Packed_Array_Impl_Type (T)
5629      then
5630         New_Concatenation_Op (T);
5631      end if;
5632
5633      --  In the case of an unconstrained array the parser has already verified
5634      --  that all the indexes are unconstrained but we still need to make sure
5635      --  that the element type is constrained.
5636
5637      if Is_Indefinite_Subtype (Element_Type) then
5638         Error_Msg_N
5639           ("unconstrained element type in array declaration",
5640            Subtype_Indication (Component_Def));
5641
5642      elsif Is_Abstract_Type (Element_Type) then
5643         Error_Msg_N
5644           ("the type of a component cannot be abstract",
5645            Subtype_Indication (Component_Def));
5646      end if;
5647
5648      --  There may be an invariant declared for the component type, but
5649      --  the construction of the component invariant checking procedure
5650      --  takes place during expansion.
5651   end Array_Type_Declaration;
5652
5653   ------------------------------------------------------
5654   -- Replace_Anonymous_Access_To_Protected_Subprogram --
5655   ------------------------------------------------------
5656
5657   function Replace_Anonymous_Access_To_Protected_Subprogram
5658     (N : Node_Id) return Entity_Id
5659   is
5660      Loc : constant Source_Ptr := Sloc (N);
5661
5662      Curr_Scope : constant Scope_Stack_Entry :=
5663                     Scope_Stack.Table (Scope_Stack.Last);
5664
5665      Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
5666
5667      Acc : Node_Id;
5668      --  Access definition in declaration
5669
5670      Comp : Node_Id;
5671      --  Object definition or formal definition with an access definition
5672
5673      Decl : Node_Id;
5674      --  Declaration of anonymous access to subprogram type
5675
5676      Spec : Node_Id;
5677      --  Original specification in access to subprogram
5678
5679      P : Node_Id;
5680
5681   begin
5682      Set_Is_Internal (Anon);
5683
5684      case Nkind (N) is
5685         when N_Component_Declaration       |
5686           N_Unconstrained_Array_Definition |
5687           N_Constrained_Array_Definition   =>
5688            Comp := Component_Definition (N);
5689            Acc  := Access_Definition (Comp);
5690
5691         when N_Discriminant_Specification =>
5692            Comp := Discriminant_Type (N);
5693            Acc  := Comp;
5694
5695         when N_Parameter_Specification =>
5696            Comp := Parameter_Type (N);
5697            Acc  := Comp;
5698
5699         when N_Access_Function_Definition  =>
5700            Comp := Result_Definition (N);
5701            Acc  := Comp;
5702
5703         when N_Object_Declaration  =>
5704            Comp := Object_Definition (N);
5705            Acc  := Comp;
5706
5707         when N_Function_Specification =>
5708            Comp := Result_Definition (N);
5709            Acc  := Comp;
5710
5711         when others =>
5712            raise Program_Error;
5713      end case;
5714
5715      Spec := Access_To_Subprogram_Definition (Acc);
5716
5717      Decl :=
5718        Make_Full_Type_Declaration (Loc,
5719          Defining_Identifier => Anon,
5720          Type_Definition     => Copy_Separate_Tree (Spec));
5721
5722      Mark_Rewrite_Insertion (Decl);
5723
5724      --  In ASIS mode, analyze the profile on the original node, because
5725      --  the separate copy does not provide enough links to recover the
5726      --  original tree. Analysis is limited to type annotations, within
5727      --  a temporary scope that serves as an anonymous subprogram to collect
5728      --  otherwise useless temporaries and itypes.
5729
5730      if ASIS_Mode then
5731         declare
5732            Typ : constant Entity_Id :=  Make_Temporary (Loc, 'S');
5733
5734         begin
5735            if Nkind (Spec) = N_Access_Function_Definition then
5736               Set_Ekind (Typ, E_Function);
5737            else
5738               Set_Ekind (Typ, E_Procedure);
5739            end if;
5740
5741            Set_Parent (Typ, N);
5742            Set_Scope  (Typ, Current_Scope);
5743            Push_Scope (Typ);
5744
5745            Process_Formals (Parameter_Specifications (Spec), Spec);
5746
5747            if Nkind (Spec) = N_Access_Function_Definition then
5748               declare
5749                  Def : constant Node_Id := Result_Definition (Spec);
5750
5751               begin
5752                  --  The result might itself be an anonymous access type, so
5753                  --  have to recurse.
5754
5755                  if Nkind (Def) = N_Access_Definition then
5756                     if Present (Access_To_Subprogram_Definition (Def)) then
5757                        Set_Etype
5758                          (Def,
5759                           Replace_Anonymous_Access_To_Protected_Subprogram
5760                            (Spec));
5761                     else
5762                        Find_Type (Subtype_Mark (Def));
5763                     end if;
5764
5765                  else
5766                     Find_Type (Def);
5767                  end if;
5768               end;
5769            end if;
5770
5771            End_Scope;
5772         end;
5773      end if;
5774
5775      --  Insert the new declaration in the nearest enclosing scope. If the
5776      --  node is a body and N is its return type, the declaration belongs in
5777      --  the enclosing scope.
5778
5779      P := Parent (N);
5780
5781      if Nkind (P) = N_Subprogram_Body
5782        and then Nkind (N) = N_Function_Specification
5783      then
5784         P := Parent (P);
5785      end if;
5786
5787      while Present (P) and then not Has_Declarations (P) loop
5788         P := Parent (P);
5789      end loop;
5790
5791      pragma Assert (Present (P));
5792
5793      if Nkind (P) = N_Package_Specification then
5794         Prepend (Decl, Visible_Declarations (P));
5795      else
5796         Prepend (Decl, Declarations (P));
5797      end if;
5798
5799      --  Replace the anonymous type with an occurrence of the new declaration.
5800      --  In all cases the rewritten node does not have the null-exclusion
5801      --  attribute because (if present) it was already inherited by the
5802      --  anonymous entity (Anon). Thus, in case of components we do not
5803      --  inherit this attribute.
5804
5805      if Nkind (N) = N_Parameter_Specification then
5806         Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5807         Set_Etype (Defining_Identifier (N), Anon);
5808         Set_Null_Exclusion_Present (N, False);
5809
5810      elsif Nkind (N) = N_Object_Declaration then
5811         Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5812         Set_Etype (Defining_Identifier (N), Anon);
5813
5814      elsif Nkind (N) = N_Access_Function_Definition then
5815         Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5816
5817      elsif Nkind (N) = N_Function_Specification then
5818         Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5819         Set_Etype (Defining_Unit_Name (N), Anon);
5820
5821      else
5822         Rewrite (Comp,
5823           Make_Component_Definition (Loc,
5824             Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
5825      end if;
5826
5827      Mark_Rewrite_Insertion (Comp);
5828
5829      if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
5830         Analyze (Decl);
5831
5832      else
5833         --  Temporarily remove the current scope (record or subprogram) from
5834         --  the stack to add the new declarations to the enclosing scope.
5835
5836         Scope_Stack.Decrement_Last;
5837         Analyze (Decl);
5838         Set_Is_Itype (Anon);
5839         Scope_Stack.Append (Curr_Scope);
5840      end if;
5841
5842      Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
5843      Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
5844      return Anon;
5845   end Replace_Anonymous_Access_To_Protected_Subprogram;
5846
5847   -------------------------------
5848   -- Build_Derived_Access_Type --
5849   -------------------------------
5850
5851   procedure Build_Derived_Access_Type
5852     (N            : Node_Id;
5853      Parent_Type  : Entity_Id;
5854      Derived_Type : Entity_Id)
5855   is
5856      S : constant Node_Id := Subtype_Indication (Type_Definition (N));
5857
5858      Desig_Type      : Entity_Id;
5859      Discr           : Entity_Id;
5860      Discr_Con_Elist : Elist_Id;
5861      Discr_Con_El    : Elmt_Id;
5862      Subt            : Entity_Id;
5863
5864   begin
5865      --  Set the designated type so it is available in case this is an access
5866      --  to a self-referential type, e.g. a standard list type with a next
5867      --  pointer. Will be reset after subtype is built.
5868
5869      Set_Directly_Designated_Type
5870        (Derived_Type, Designated_Type (Parent_Type));
5871
5872      Subt := Process_Subtype (S, N);
5873
5874      if Nkind (S) /= N_Subtype_Indication
5875        and then Subt /= Base_Type (Subt)
5876      then
5877         Set_Ekind (Derived_Type, E_Access_Subtype);
5878      end if;
5879
5880      if Ekind (Derived_Type) = E_Access_Subtype then
5881         declare
5882            Pbase      : constant Entity_Id := Base_Type (Parent_Type);
5883            Ibase      : constant Entity_Id :=
5884                           Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
5885            Svg_Chars  : constant Name_Id   := Chars (Ibase);
5886            Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
5887
5888         begin
5889            Copy_Node (Pbase, Ibase);
5890
5891            Set_Chars             (Ibase, Svg_Chars);
5892            Set_Next_Entity       (Ibase, Svg_Next_E);
5893            Set_Sloc              (Ibase, Sloc (Derived_Type));
5894            Set_Scope             (Ibase, Scope (Derived_Type));
5895            Set_Freeze_Node       (Ibase, Empty);
5896            Set_Is_Frozen         (Ibase, False);
5897            Set_Comes_From_Source (Ibase, False);
5898            Set_Is_First_Subtype  (Ibase, False);
5899
5900            Set_Etype (Ibase, Pbase);
5901            Set_Etype (Derived_Type, Ibase);
5902         end;
5903      end if;
5904
5905      Set_Directly_Designated_Type
5906        (Derived_Type, Designated_Type (Subt));
5907
5908      Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
5909      Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
5910      Set_Size_Info          (Derived_Type,                     Parent_Type);
5911      Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
5912      Set_Depends_On_Private (Derived_Type,
5913                              Has_Private_Component (Derived_Type));
5914      Conditional_Delay      (Derived_Type, Subt);
5915
5916      --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
5917      --  that it is not redundant.
5918
5919      if Null_Exclusion_Present (Type_Definition (N)) then
5920         Set_Can_Never_Be_Null (Derived_Type);
5921
5922         --  What is with the "AND THEN FALSE" here ???
5923
5924         if Can_Never_Be_Null (Parent_Type)
5925           and then False
5926         then
5927            Error_Msg_NE
5928              ("`NOT NULL` not allowed (& already excludes null)",
5929                N, Parent_Type);
5930         end if;
5931
5932      elsif Can_Never_Be_Null (Parent_Type) then
5933         Set_Can_Never_Be_Null (Derived_Type);
5934      end if;
5935
5936      --  Note: we do not copy the Storage_Size_Variable, since we always go to
5937      --  the root type for this information.
5938
5939      --  Apply range checks to discriminants for derived record case
5940      --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
5941
5942      Desig_Type := Designated_Type (Derived_Type);
5943      if Is_Composite_Type (Desig_Type)
5944        and then (not Is_Array_Type (Desig_Type))
5945        and then Has_Discriminants (Desig_Type)
5946        and then Base_Type (Desig_Type) /= Desig_Type
5947      then
5948         Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
5949         Discr_Con_El := First_Elmt (Discr_Con_Elist);
5950
5951         Discr := First_Discriminant (Base_Type (Desig_Type));
5952         while Present (Discr_Con_El) loop
5953            Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
5954            Next_Elmt (Discr_Con_El);
5955            Next_Discriminant (Discr);
5956         end loop;
5957      end if;
5958   end Build_Derived_Access_Type;
5959
5960   ------------------------------
5961   -- Build_Derived_Array_Type --
5962   ------------------------------
5963
5964   procedure Build_Derived_Array_Type
5965     (N            : Node_Id;
5966      Parent_Type  : Entity_Id;
5967      Derived_Type : Entity_Id)
5968   is
5969      Loc           : constant Source_Ptr := Sloc (N);
5970      Tdef          : constant Node_Id    := Type_Definition (N);
5971      Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5972      Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5973      Implicit_Base : Entity_Id;
5974      New_Indic     : Node_Id;
5975
5976      procedure Make_Implicit_Base;
5977      --  If the parent subtype is constrained, the derived type is a subtype
5978      --  of an implicit base type derived from the parent base.
5979
5980      ------------------------
5981      -- Make_Implicit_Base --
5982      ------------------------
5983
5984      procedure Make_Implicit_Base is
5985      begin
5986         Implicit_Base :=
5987           Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5988
5989         Set_Ekind (Implicit_Base, Ekind (Parent_Base));
5990         Set_Etype (Implicit_Base, Parent_Base);
5991
5992         Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
5993         Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
5994
5995         Set_Has_Delayed_Freeze (Implicit_Base, True);
5996
5997         --  Inherit the "ghostness" from the parent base type
5998
5999         if Is_Ghost_Entity (Parent_Base) or else Ghost_Mode > None then
6000            Set_Is_Ghost_Entity (Implicit_Base);
6001         end if;
6002      end Make_Implicit_Base;
6003
6004   --  Start of processing for Build_Derived_Array_Type
6005
6006   begin
6007      if not Is_Constrained (Parent_Type) then
6008         if Nkind (Indic) /= N_Subtype_Indication then
6009            Set_Ekind (Derived_Type, E_Array_Type);
6010
6011            Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
6012            Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
6013
6014            Set_Has_Delayed_Freeze (Derived_Type, True);
6015
6016         else
6017            Make_Implicit_Base;
6018            Set_Etype (Derived_Type, Implicit_Base);
6019
6020            New_Indic :=
6021              Make_Subtype_Declaration (Loc,
6022                Defining_Identifier => Derived_Type,
6023                Subtype_Indication  =>
6024                  Make_Subtype_Indication (Loc,
6025                    Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
6026                    Constraint => Constraint (Indic)));
6027
6028            Rewrite (N, New_Indic);
6029            Analyze (N);
6030         end if;
6031
6032      else
6033         if Nkind (Indic) /= N_Subtype_Indication then
6034            Make_Implicit_Base;
6035
6036            Set_Ekind                     (Derived_Type, Ekind (Parent_Type));
6037            Set_Etype                     (Derived_Type, Implicit_Base);
6038            Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
6039
6040         else
6041            Error_Msg_N ("illegal constraint on constrained type", Indic);
6042         end if;
6043      end if;
6044
6045      --  If parent type is not a derived type itself, and is declared in
6046      --  closed scope (e.g. a subprogram), then we must explicitly introduce
6047      --  the new type's concatenation operator since Derive_Subprograms
6048      --  will not inherit the parent's operator. If the parent type is
6049      --  unconstrained, the operator is of the unconstrained base type.
6050
6051      if Number_Dimensions (Parent_Type) = 1
6052        and then not Is_Limited_Type (Parent_Type)
6053        and then not Is_Derived_Type (Parent_Type)
6054        and then not Is_Package_Or_Generic_Package
6055                       (Scope (Base_Type (Parent_Type)))
6056      then
6057         if not Is_Constrained (Parent_Type)
6058           and then Is_Constrained (Derived_Type)
6059         then
6060            New_Concatenation_Op (Implicit_Base);
6061         else
6062            New_Concatenation_Op (Derived_Type);
6063         end if;
6064      end if;
6065   end Build_Derived_Array_Type;
6066
6067   -----------------------------------
6068   -- Build_Derived_Concurrent_Type --
6069   -----------------------------------
6070
6071   procedure Build_Derived_Concurrent_Type
6072     (N            : Node_Id;
6073      Parent_Type  : Entity_Id;
6074      Derived_Type : Entity_Id)
6075   is
6076      Loc : constant Source_Ptr := Sloc (N);
6077
6078      Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
6079      Corr_Decl        : Node_Id;
6080      Corr_Decl_Needed : Boolean;
6081      --  If the derived type has fewer discriminants than its parent, the
6082      --  corresponding record is also a derived type, in order to account for
6083      --  the bound discriminants. We create a full type declaration for it in
6084      --  this case.
6085
6086      Constraint_Present : constant Boolean :=
6087                             Nkind (Subtype_Indication (Type_Definition (N))) =
6088                                                          N_Subtype_Indication;
6089
6090      D_Constraint   : Node_Id;
6091      New_Constraint : Elist_Id;
6092      Old_Disc       : Entity_Id;
6093      New_Disc       : Entity_Id;
6094      New_N          : Node_Id;
6095
6096   begin
6097      Set_Stored_Constraint (Derived_Type, No_Elist);
6098      Corr_Decl_Needed := False;
6099      Old_Disc := Empty;
6100
6101      if Present (Discriminant_Specifications (N))
6102        and then Constraint_Present
6103      then
6104         Old_Disc := First_Discriminant (Parent_Type);
6105         New_Disc := First (Discriminant_Specifications (N));
6106         while Present (New_Disc) and then Present (Old_Disc) loop
6107            Next_Discriminant (Old_Disc);
6108            Next (New_Disc);
6109         end loop;
6110      end if;
6111
6112      if Present (Old_Disc) and then Expander_Active then
6113
6114         --  The new type has fewer discriminants, so we need to create a new
6115         --  corresponding record, which is derived from the corresponding
6116         --  record of the parent, and has a stored constraint that captures
6117         --  the values of the discriminant constraints. The corresponding
6118         --  record is needed only if expander is active and code generation is
6119         --  enabled.
6120
6121         --  The type declaration for the derived corresponding record has the
6122         --  same discriminant part and constraints as the current declaration.
6123         --  Copy the unanalyzed tree to build declaration.
6124
6125         Corr_Decl_Needed := True;
6126         New_N := Copy_Separate_Tree (N);
6127
6128         Corr_Decl :=
6129           Make_Full_Type_Declaration (Loc,
6130             Defining_Identifier         => Corr_Record,
6131             Discriminant_Specifications =>
6132                Discriminant_Specifications (New_N),
6133             Type_Definition             =>
6134               Make_Derived_Type_Definition (Loc,
6135                 Subtype_Indication =>
6136                   Make_Subtype_Indication (Loc,
6137                     Subtype_Mark =>
6138                        New_Occurrence_Of
6139                          (Corresponding_Record_Type (Parent_Type), Loc),
6140                     Constraint   =>
6141                       Constraint
6142                         (Subtype_Indication (Type_Definition (New_N))))));
6143      end if;
6144
6145      --  Copy Storage_Size and Relative_Deadline variables if task case
6146
6147      if Is_Task_Type (Parent_Type) then
6148         Set_Storage_Size_Variable (Derived_Type,
6149           Storage_Size_Variable (Parent_Type));
6150         Set_Relative_Deadline_Variable (Derived_Type,
6151           Relative_Deadline_Variable (Parent_Type));
6152      end if;
6153
6154      if Present (Discriminant_Specifications (N)) then
6155         Push_Scope (Derived_Type);
6156         Check_Or_Process_Discriminants (N, Derived_Type);
6157
6158         if Constraint_Present then
6159            New_Constraint :=
6160              Expand_To_Stored_Constraint
6161                (Parent_Type,
6162                 Build_Discriminant_Constraints
6163                   (Parent_Type,
6164                    Subtype_Indication (Type_Definition (N)), True));
6165         end if;
6166
6167         End_Scope;
6168
6169      elsif Constraint_Present then
6170
6171         --  Build constrained subtype, copying the constraint, and derive
6172         --  from it to create a derived constrained type.
6173
6174         declare
6175            Loc  : constant Source_Ptr := Sloc (N);
6176            Anon : constant Entity_Id :=
6177                     Make_Defining_Identifier (Loc,
6178                       Chars => New_External_Name (Chars (Derived_Type), 'T'));
6179            Decl : Node_Id;
6180
6181         begin
6182            Decl :=
6183              Make_Subtype_Declaration (Loc,
6184                Defining_Identifier => Anon,
6185                Subtype_Indication =>
6186                  New_Copy_Tree (Subtype_Indication (Type_Definition (N))));
6187            Insert_Before (N, Decl);
6188            Analyze (Decl);
6189
6190            Rewrite (Subtype_Indication (Type_Definition (N)),
6191              New_Occurrence_Of (Anon, Loc));
6192            Set_Analyzed (Derived_Type, False);
6193            Analyze (N);
6194            return;
6195         end;
6196      end if;
6197
6198      --  By default, operations and private data are inherited from parent.
6199      --  However, in the presence of bound discriminants, a new corresponding
6200      --  record will be created, see below.
6201
6202      Set_Has_Discriminants
6203        (Derived_Type, Has_Discriminants         (Parent_Type));
6204      Set_Corresponding_Record_Type
6205        (Derived_Type, Corresponding_Record_Type (Parent_Type));
6206
6207      --  Is_Constrained is set according the parent subtype, but is set to
6208      --  False if the derived type is declared with new discriminants.
6209
6210      Set_Is_Constrained
6211        (Derived_Type,
6212         (Is_Constrained (Parent_Type) or else Constraint_Present)
6213           and then not Present (Discriminant_Specifications (N)));
6214
6215      if Constraint_Present then
6216         if not Has_Discriminants (Parent_Type) then
6217            Error_Msg_N ("untagged parent must have discriminants", N);
6218
6219         elsif Present (Discriminant_Specifications (N)) then
6220
6221            --  Verify that new discriminants are used to constrain old ones
6222
6223            D_Constraint :=
6224              First
6225                (Constraints
6226                  (Constraint (Subtype_Indication (Type_Definition (N)))));
6227
6228            Old_Disc := First_Discriminant (Parent_Type);
6229
6230            while Present (D_Constraint) loop
6231               if Nkind (D_Constraint) /= N_Discriminant_Association then
6232
6233                  --  Positional constraint. If it is a reference to a new
6234                  --  discriminant, it constrains the corresponding old one.
6235
6236                  if Nkind (D_Constraint) = N_Identifier then
6237                     New_Disc := First_Discriminant (Derived_Type);
6238                     while Present (New_Disc) loop
6239                        exit when Chars (New_Disc) = Chars (D_Constraint);
6240                        Next_Discriminant (New_Disc);
6241                     end loop;
6242
6243                     if Present (New_Disc) then
6244                        Set_Corresponding_Discriminant (New_Disc, Old_Disc);
6245                     end if;
6246                  end if;
6247
6248                  Next_Discriminant (Old_Disc);
6249
6250                  --  if this is a named constraint, search by name for the old
6251                  --  discriminants constrained by the new one.
6252
6253               elsif Nkind (Expression (D_Constraint)) = N_Identifier then
6254
6255                  --  Find new discriminant with that name
6256
6257                  New_Disc := First_Discriminant (Derived_Type);
6258                  while Present (New_Disc) loop
6259                     exit when
6260                       Chars (New_Disc) = Chars (Expression (D_Constraint));
6261                     Next_Discriminant (New_Disc);
6262                  end loop;
6263
6264                  if Present (New_Disc) then
6265
6266                     --  Verify that new discriminant renames some discriminant
6267                     --  of the parent type, and associate the new discriminant
6268                     --  with one or more old ones that it renames.
6269
6270                     declare
6271                        Selector : Node_Id;
6272
6273                     begin
6274                        Selector := First (Selector_Names (D_Constraint));
6275                        while Present (Selector) loop
6276                           Old_Disc := First_Discriminant (Parent_Type);
6277                           while Present (Old_Disc) loop
6278                              exit when Chars (Old_Disc) = Chars (Selector);
6279                              Next_Discriminant (Old_Disc);
6280                           end loop;
6281
6282                           if Present (Old_Disc) then
6283                              Set_Corresponding_Discriminant
6284                                (New_Disc, Old_Disc);
6285                           end if;
6286
6287                           Next (Selector);
6288                        end loop;
6289                     end;
6290                  end if;
6291               end if;
6292
6293               Next (D_Constraint);
6294            end loop;
6295
6296            New_Disc := First_Discriminant (Derived_Type);
6297            while Present (New_Disc) loop
6298               if No (Corresponding_Discriminant (New_Disc)) then
6299                  Error_Msg_NE
6300                    ("new discriminant& must constrain old one", N, New_Disc);
6301
6302               elsif not
6303                 Subtypes_Statically_Compatible
6304                   (Etype (New_Disc),
6305                    Etype (Corresponding_Discriminant (New_Disc)))
6306               then
6307                  Error_Msg_NE
6308                    ("& not statically compatible with parent discriminant",
6309                      N, New_Disc);
6310               end if;
6311
6312               Next_Discriminant (New_Disc);
6313            end loop;
6314         end if;
6315
6316      elsif Present (Discriminant_Specifications (N)) then
6317         Error_Msg_N
6318           ("missing discriminant constraint in untagged derivation", N);
6319      end if;
6320
6321      --  The entity chain of the derived type includes the new discriminants
6322      --  but shares operations with the parent.
6323
6324      if Present (Discriminant_Specifications (N)) then
6325         Old_Disc := First_Discriminant (Parent_Type);
6326         while Present (Old_Disc) loop
6327            if No (Next_Entity (Old_Disc))
6328              or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
6329            then
6330               Set_Next_Entity
6331                 (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
6332               exit;
6333            end if;
6334
6335            Next_Discriminant (Old_Disc);
6336         end loop;
6337
6338      else
6339         Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
6340         if Has_Discriminants (Parent_Type) then
6341            Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
6342            Set_Discriminant_Constraint (
6343              Derived_Type, Discriminant_Constraint (Parent_Type));
6344         end if;
6345      end if;
6346
6347      Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
6348
6349      Set_Has_Completion (Derived_Type);
6350
6351      if Corr_Decl_Needed then
6352         Set_Stored_Constraint (Derived_Type, New_Constraint);
6353         Insert_After (N, Corr_Decl);
6354         Analyze (Corr_Decl);
6355         Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
6356      end if;
6357   end Build_Derived_Concurrent_Type;
6358
6359   ------------------------------------
6360   -- Build_Derived_Enumeration_Type --
6361   ------------------------------------
6362
6363   procedure Build_Derived_Enumeration_Type
6364     (N            : Node_Id;
6365      Parent_Type  : Entity_Id;
6366      Derived_Type : Entity_Id)
6367   is
6368      Loc           : constant Source_Ptr := Sloc (N);
6369      Def           : constant Node_Id    := Type_Definition (N);
6370      Indic         : constant Node_Id    := Subtype_Indication (Def);
6371      Implicit_Base : Entity_Id;
6372      Literal       : Entity_Id;
6373      New_Lit       : Entity_Id;
6374      Literals_List : List_Id;
6375      Type_Decl     : Node_Id;
6376      Hi, Lo        : Node_Id;
6377      Rang_Expr     : Node_Id;
6378
6379   begin
6380      --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
6381      --  not have explicit literals lists we need to process types derived
6382      --  from them specially. This is handled by Derived_Standard_Character.
6383      --  If the parent type is a generic type, there are no literals either,
6384      --  and we construct the same skeletal representation as for the generic
6385      --  parent type.
6386
6387      if Is_Standard_Character_Type (Parent_Type) then
6388         Derived_Standard_Character (N, Parent_Type, Derived_Type);
6389
6390      elsif Is_Generic_Type (Root_Type (Parent_Type)) then
6391         declare
6392            Lo : Node_Id;
6393            Hi : Node_Id;
6394
6395         begin
6396            if Nkind (Indic) /= N_Subtype_Indication then
6397               Lo :=
6398                  Make_Attribute_Reference (Loc,
6399                    Attribute_Name => Name_First,
6400                    Prefix         => New_Occurrence_Of (Derived_Type, Loc));
6401               Set_Etype (Lo, Derived_Type);
6402
6403               Hi :=
6404                  Make_Attribute_Reference (Loc,
6405                    Attribute_Name => Name_Last,
6406                    Prefix         => New_Occurrence_Of (Derived_Type, Loc));
6407               Set_Etype (Hi, Derived_Type);
6408
6409               Set_Scalar_Range (Derived_Type,
6410                  Make_Range (Loc,
6411                    Low_Bound  => Lo,
6412                    High_Bound => Hi));
6413            else
6414
6415               --   Analyze subtype indication and verify compatibility
6416               --   with parent type.
6417
6418               if Base_Type (Process_Subtype (Indic, N)) /=
6419                  Base_Type (Parent_Type)
6420               then
6421                  Error_Msg_N
6422                    ("illegal constraint for formal discrete type", N);
6423               end if;
6424            end if;
6425         end;
6426
6427      else
6428         --  If a constraint is present, analyze the bounds to catch
6429         --  premature usage of the derived literals.
6430
6431         if Nkind (Indic) = N_Subtype_Indication
6432           and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
6433         then
6434            Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
6435            Analyze (High_Bound (Range_Expression (Constraint (Indic))));
6436         end if;
6437
6438         --  Introduce an implicit base type for the derived type even if there
6439         --  is no constraint attached to it, since this seems closer to the
6440         --  Ada semantics. Build a full type declaration tree for the derived
6441         --  type using the implicit base type as the defining identifier. The
6442         --  build a subtype declaration tree which applies the constraint (if
6443         --  any) have it replace the derived type declaration.
6444
6445         Literal := First_Literal (Parent_Type);
6446         Literals_List := New_List;
6447         while Present (Literal)
6448           and then Ekind (Literal) = E_Enumeration_Literal
6449         loop
6450            --  Literals of the derived type have the same representation as
6451            --  those of the parent type, but this representation can be
6452            --  overridden by an explicit representation clause. Indicate
6453            --  that there is no explicit representation given yet. These
6454            --  derived literals are implicit operations of the new type,
6455            --  and can be overridden by explicit ones.
6456
6457            if Nkind (Literal) = N_Defining_Character_Literal then
6458               New_Lit :=
6459                 Make_Defining_Character_Literal (Loc, Chars (Literal));
6460            else
6461               New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
6462            end if;
6463
6464            Set_Ekind                (New_Lit, E_Enumeration_Literal);
6465            Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
6466            Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
6467            Set_Enumeration_Rep_Expr (New_Lit, Empty);
6468            Set_Alias                (New_Lit, Literal);
6469            Set_Is_Known_Valid       (New_Lit, True);
6470
6471            Append (New_Lit, Literals_List);
6472            Next_Literal (Literal);
6473         end loop;
6474
6475         Implicit_Base :=
6476           Make_Defining_Identifier (Sloc (Derived_Type),
6477             Chars => New_External_Name (Chars (Derived_Type), 'B'));
6478
6479         --  Indicate the proper nature of the derived type. This must be done
6480         --  before analysis of the literals, to recognize cases when a literal
6481         --  may be hidden by a previous explicit function definition (cf.
6482         --  c83031a).
6483
6484         Set_Ekind (Derived_Type, E_Enumeration_Subtype);
6485         Set_Etype (Derived_Type, Implicit_Base);
6486
6487         Type_Decl :=
6488           Make_Full_Type_Declaration (Loc,
6489             Defining_Identifier => Implicit_Base,
6490             Discriminant_Specifications => No_List,
6491             Type_Definition =>
6492               Make_Enumeration_Type_Definition (Loc, Literals_List));
6493
6494         Mark_Rewrite_Insertion (Type_Decl);
6495         Insert_Before (N, Type_Decl);
6496         Analyze (Type_Decl);
6497
6498         --  After the implicit base is analyzed its Etype needs to be changed
6499         --  to reflect the fact that it is derived from the parent type which
6500         --  was ignored during analysis. We also set the size at this point.
6501
6502         Set_Etype (Implicit_Base, Parent_Type);
6503
6504         Set_Size_Info      (Implicit_Base,                 Parent_Type);
6505         Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
6506         Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
6507
6508         --  Copy other flags from parent type
6509
6510         Set_Has_Non_Standard_Rep
6511                            (Implicit_Base, Has_Non_Standard_Rep
6512                                                           (Parent_Type));
6513         Set_Has_Pragma_Ordered
6514                            (Implicit_Base, Has_Pragma_Ordered
6515                                                           (Parent_Type));
6516         Set_Has_Delayed_Freeze (Implicit_Base);
6517
6518         --  Process the subtype indication including a validation check on the
6519         --  constraint, if any. If a constraint is given, its bounds must be
6520         --  implicitly converted to the new type.
6521
6522         if Nkind (Indic) = N_Subtype_Indication then
6523            declare
6524               R : constant Node_Id :=
6525                     Range_Expression (Constraint (Indic));
6526
6527            begin
6528               if Nkind (R) = N_Range then
6529                  Hi := Build_Scalar_Bound
6530                          (High_Bound (R), Parent_Type, Implicit_Base);
6531                  Lo := Build_Scalar_Bound
6532                          (Low_Bound  (R), Parent_Type, Implicit_Base);
6533
6534               else
6535                  --  Constraint is a Range attribute. Replace with explicit
6536                  --  mention of the bounds of the prefix, which must be a
6537                  --  subtype.
6538
6539                  Analyze (Prefix (R));
6540                  Hi :=
6541                    Convert_To (Implicit_Base,
6542                      Make_Attribute_Reference (Loc,
6543                        Attribute_Name => Name_Last,
6544                        Prefix =>
6545                          New_Occurrence_Of (Entity (Prefix (R)), Loc)));
6546
6547                  Lo :=
6548                    Convert_To (Implicit_Base,
6549                      Make_Attribute_Reference (Loc,
6550                        Attribute_Name => Name_First,
6551                        Prefix =>
6552                          New_Occurrence_Of (Entity (Prefix (R)), Loc)));
6553               end if;
6554            end;
6555
6556         else
6557            Hi :=
6558              Build_Scalar_Bound
6559                (Type_High_Bound (Parent_Type),
6560                 Parent_Type, Implicit_Base);
6561            Lo :=
6562               Build_Scalar_Bound
6563                 (Type_Low_Bound (Parent_Type),
6564                  Parent_Type, Implicit_Base);
6565         end if;
6566
6567         Rang_Expr :=
6568           Make_Range (Loc,
6569             Low_Bound  => Lo,
6570             High_Bound => Hi);
6571
6572         --  If we constructed a default range for the case where no range
6573         --  was given, then the expressions in the range must not freeze
6574         --  since they do not correspond to expressions in the source.
6575
6576         if Nkind (Indic) /= N_Subtype_Indication then
6577            Set_Must_Not_Freeze (Lo);
6578            Set_Must_Not_Freeze (Hi);
6579            Set_Must_Not_Freeze (Rang_Expr);
6580         end if;
6581
6582         Rewrite (N,
6583           Make_Subtype_Declaration (Loc,
6584             Defining_Identifier => Derived_Type,
6585             Subtype_Indication =>
6586               Make_Subtype_Indication (Loc,
6587                 Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
6588                 Constraint =>
6589                   Make_Range_Constraint (Loc,
6590                     Range_Expression => Rang_Expr))));
6591
6592         Analyze (N);
6593
6594         --  Propagate the aspects from the original type declaration to the
6595         --  declaration of the implicit base.
6596
6597         Move_Aspects (From => Original_Node (N), To => Type_Decl);
6598
6599         --  Apply a range check. Since this range expression doesn't have an
6600         --  Etype, we have to specifically pass the Source_Typ parameter. Is
6601         --  this right???
6602
6603         if Nkind (Indic) = N_Subtype_Indication then
6604            Apply_Range_Check
6605              (Range_Expression (Constraint (Indic)), Parent_Type,
6606               Source_Typ => Entity (Subtype_Mark (Indic)));
6607         end if;
6608      end if;
6609   end Build_Derived_Enumeration_Type;
6610
6611   --------------------------------
6612   -- Build_Derived_Numeric_Type --
6613   --------------------------------
6614
6615   procedure Build_Derived_Numeric_Type
6616     (N            : Node_Id;
6617      Parent_Type  : Entity_Id;
6618      Derived_Type : Entity_Id)
6619   is
6620      Loc           : constant Source_Ptr := Sloc (N);
6621      Tdef          : constant Node_Id    := Type_Definition (N);
6622      Indic         : constant Node_Id    := Subtype_Indication (Tdef);
6623      Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
6624      No_Constraint : constant Boolean    := Nkind (Indic) /=
6625                                                  N_Subtype_Indication;
6626      Implicit_Base : Entity_Id;
6627
6628      Lo : Node_Id;
6629      Hi : Node_Id;
6630
6631   begin
6632      --  Process the subtype indication including a validation check on
6633      --  the constraint if any.
6634
6635      Discard_Node (Process_Subtype (Indic, N));
6636
6637      --  Introduce an implicit base type for the derived type even if there
6638      --  is no constraint attached to it, since this seems closer to the Ada
6639      --  semantics.
6640
6641      Implicit_Base :=
6642        Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
6643
6644      Set_Etype          (Implicit_Base, Parent_Base);
6645      Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
6646      Set_Size_Info      (Implicit_Base,                 Parent_Base);
6647      Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
6648      Set_Parent         (Implicit_Base, Parent (Derived_Type));
6649      Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
6650
6651      --  Set RM Size for discrete type or decimal fixed-point type
6652      --  Ordinary fixed-point is excluded, why???
6653
6654      if Is_Discrete_Type (Parent_Base)
6655        or else Is_Decimal_Fixed_Point_Type (Parent_Base)
6656      then
6657         Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
6658      end if;
6659
6660      Set_Has_Delayed_Freeze (Implicit_Base);
6661
6662      Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
6663      Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
6664
6665      Set_Scalar_Range (Implicit_Base,
6666        Make_Range (Loc,
6667          Low_Bound  => Lo,
6668          High_Bound => Hi));
6669
6670      if Has_Infinities (Parent_Base) then
6671         Set_Includes_Infinities (Scalar_Range (Implicit_Base));
6672      end if;
6673
6674      --  The Derived_Type, which is the entity of the declaration, is a
6675      --  subtype of the implicit base. Its Ekind is a subtype, even in the
6676      --  absence of an explicit constraint.
6677
6678      Set_Etype (Derived_Type, Implicit_Base);
6679
6680      --  If we did not have a constraint, then the Ekind is set from the
6681      --  parent type (otherwise Process_Subtype has set the bounds)
6682
6683      if No_Constraint then
6684         Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
6685      end if;
6686
6687      --  If we did not have a range constraint, then set the range from the
6688      --  parent type. Otherwise, the Process_Subtype call has set the bounds.
6689
6690      if No_Constraint or else not Has_Range_Constraint (Indic) then
6691         Set_Scalar_Range (Derived_Type,
6692           Make_Range (Loc,
6693             Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
6694             High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
6695         Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
6696
6697         if Has_Infinities (Parent_Type) then
6698            Set_Includes_Infinities (Scalar_Range (Derived_Type));
6699         end if;
6700
6701         Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
6702      end if;
6703
6704      Set_Is_Descendent_Of_Address (Derived_Type,
6705        Is_Descendent_Of_Address (Parent_Type));
6706      Set_Is_Descendent_Of_Address (Implicit_Base,
6707        Is_Descendent_Of_Address (Parent_Type));
6708
6709      --  Set remaining type-specific fields, depending on numeric type
6710
6711      if Is_Modular_Integer_Type (Parent_Type) then
6712         Set_Modulus (Implicit_Base, Modulus (Parent_Base));
6713
6714         Set_Non_Binary_Modulus
6715           (Implicit_Base, Non_Binary_Modulus (Parent_Base));
6716
6717         Set_Is_Known_Valid
6718           (Implicit_Base, Is_Known_Valid (Parent_Base));
6719
6720      elsif Is_Floating_Point_Type (Parent_Type) then
6721
6722         --  Digits of base type is always copied from the digits value of
6723         --  the parent base type, but the digits of the derived type will
6724         --  already have been set if there was a constraint present.
6725
6726         Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6727         Set_Float_Rep    (Implicit_Base, Float_Rep    (Parent_Base));
6728
6729         if No_Constraint then
6730            Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
6731         end if;
6732
6733      elsif Is_Fixed_Point_Type (Parent_Type) then
6734
6735         --  Small of base type and derived type are always copied from the
6736         --  parent base type, since smalls never change. The delta of the
6737         --  base type is also copied from the parent base type. However the
6738         --  delta of the derived type will have been set already if a
6739         --  constraint was present.
6740
6741         Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
6742         Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
6743         Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
6744
6745         if No_Constraint then
6746            Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
6747         end if;
6748
6749         --  The scale and machine radix in the decimal case are always
6750         --  copied from the parent base type.
6751
6752         if Is_Decimal_Fixed_Point_Type (Parent_Type) then
6753            Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
6754            Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
6755
6756            Set_Machine_Radix_10
6757              (Derived_Type,  Machine_Radix_10 (Parent_Base));
6758            Set_Machine_Radix_10
6759              (Implicit_Base, Machine_Radix_10 (Parent_Base));
6760
6761            Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6762
6763            if No_Constraint then
6764               Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
6765
6766            else
6767               --  the analysis of the subtype_indication sets the
6768               --  digits value of the derived type.
6769
6770               null;
6771            end if;
6772         end if;
6773      end if;
6774
6775      if Is_Integer_Type (Parent_Type) then
6776         Set_Has_Shift_Operator
6777           (Implicit_Base, Has_Shift_Operator (Parent_Type));
6778      end if;
6779
6780      --  The type of the bounds is that of the parent type, and they
6781      --  must be converted to the derived type.
6782
6783      Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
6784
6785      --  The implicit_base should be frozen when the derived type is frozen,
6786      --  but note that it is used in the conversions of the bounds. For fixed
6787      --  types we delay the determination of the bounds until the proper
6788      --  freezing point. For other numeric types this is rejected by GCC, for
6789      --  reasons that are currently unclear (???), so we choose to freeze the
6790      --  implicit base now. In the case of integers and floating point types
6791      --  this is harmless because subsequent representation clauses cannot
6792      --  affect anything, but it is still baffling that we cannot use the
6793      --  same mechanism for all derived numeric types.
6794
6795      --  There is a further complication: actually some representation
6796      --  clauses can affect the implicit base type. For example, attribute
6797      --  definition clauses for stream-oriented attributes need to set the
6798      --  corresponding TSS entries on the base type, and this normally
6799      --  cannot be done after the base type is frozen, so the circuitry in
6800      --  Sem_Ch13.New_Stream_Subprogram must account for this possibility
6801      --  and not use Set_TSS in this case.
6802
6803      --  There are also consequences for the case of delayed representation
6804      --  aspects for some cases. For example, a Size aspect is delayed and
6805      --  should not be evaluated to the freeze point. This early freezing
6806      --  means that the size attribute evaluation happens too early???
6807
6808      if Is_Fixed_Point_Type (Parent_Type) then
6809         Conditional_Delay (Implicit_Base, Parent_Type);
6810      else
6811         Freeze_Before (N, Implicit_Base);
6812      end if;
6813   end Build_Derived_Numeric_Type;
6814
6815   --------------------------------
6816   -- Build_Derived_Private_Type --
6817   --------------------------------
6818
6819   procedure Build_Derived_Private_Type
6820     (N             : Node_Id;
6821      Parent_Type   : Entity_Id;
6822      Derived_Type  : Entity_Id;
6823      Is_Completion : Boolean;
6824      Derive_Subps  : Boolean := True)
6825   is
6826      Loc       : constant Source_Ptr := Sloc (N);
6827      Par_Base  : constant Entity_Id  := Base_Type (Parent_Type);
6828      Par_Scope : constant Entity_Id  := Scope (Par_Base);
6829      Full_N    : constant Node_Id    := New_Copy_Tree (N);
6830      Full_Der  : Entity_Id           := New_Copy (Derived_Type);
6831      Full_P    : Entity_Id;
6832
6833      procedure Build_Full_Derivation;
6834      --  Build full derivation, i.e. derive from the full view
6835
6836      procedure Copy_And_Build;
6837      --  Copy derived type declaration, replace parent with its full view,
6838      --  and build derivation
6839
6840      ---------------------------
6841      -- Build_Full_Derivation --
6842      ---------------------------
6843
6844      procedure Build_Full_Derivation is
6845      begin
6846         --  If parent scope is not open, install the declarations
6847
6848         if not In_Open_Scopes (Par_Scope) then
6849            Install_Private_Declarations (Par_Scope);
6850            Install_Visible_Declarations (Par_Scope);
6851            Copy_And_Build;
6852            Uninstall_Declarations (Par_Scope);
6853
6854         --  If parent scope is open and in another unit, and parent has a
6855         --  completion, then the derivation is taking place in the visible
6856         --  part of a child unit. In that case retrieve the full view of
6857         --  the parent momentarily.
6858
6859         elsif not In_Same_Source_Unit (N, Parent_Type) then
6860            Full_P := Full_View (Parent_Type);
6861            Exchange_Declarations (Parent_Type);
6862            Copy_And_Build;
6863            Exchange_Declarations (Full_P);
6864
6865         --  Otherwise it is a local derivation
6866
6867         else
6868            Copy_And_Build;
6869         end if;
6870      end Build_Full_Derivation;
6871
6872      --------------------
6873      -- Copy_And_Build --
6874      --------------------
6875
6876      procedure Copy_And_Build is
6877         Full_Parent : Entity_Id := Parent_Type;
6878
6879      begin
6880         --  If the parent is itself derived from another private type,
6881         --  installing the private declarations has not affected its
6882         --  privacy status, so use its own full view explicitly.
6883
6884         if Is_Private_Type (Full_Parent)
6885           and then Present (Full_View (Full_Parent))
6886         then
6887            Full_Parent := Full_View (Full_Parent);
6888         end if;
6889
6890         --  And its underlying full view if necessary
6891
6892         if Is_Private_Type (Full_Parent)
6893           and then Present (Underlying_Full_View (Full_Parent))
6894         then
6895            Full_Parent := Underlying_Full_View (Full_Parent);
6896         end if;
6897
6898         --  For record, access and most enumeration types, derivation from
6899         --  the full view requires a fully-fledged declaration. In the other
6900         --  cases, just use an itype.
6901
6902         if Ekind (Full_Parent) in Record_Kind
6903           or else Ekind (Full_Parent) in Access_Kind
6904           or else
6905             (Ekind (Full_Parent) in Enumeration_Kind
6906               and then not Is_Standard_Character_Type (Full_Parent)
6907               and then not Is_Generic_Type (Root_Type (Full_Parent)))
6908         then
6909            --  Copy and adjust declaration to provide a completion for what
6910            --  is originally a private declaration. Indicate that full view
6911            --  is internally generated.
6912
6913            Set_Comes_From_Source (Full_N, False);
6914            Set_Comes_From_Source (Full_Der, False);
6915            Set_Parent (Full_Der, Full_N);
6916            Set_Defining_Identifier (Full_N, Full_Der);
6917
6918            --  If there are no constraints, adjust the subtype mark
6919
6920            if Nkind (Subtype_Indication (Type_Definition (Full_N))) /=
6921                                                       N_Subtype_Indication
6922            then
6923               Set_Subtype_Indication
6924                 (Type_Definition (Full_N),
6925                  New_Occurrence_Of (Full_Parent, Sloc (Full_N)));
6926            end if;
6927
6928            Insert_After (N, Full_N);
6929
6930            --  Build full view of derived type from full view of parent which
6931            --  is now installed. Subprograms have been derived on the partial
6932            --  view, the completion does not derive them anew.
6933
6934            if Ekind (Full_Parent) in Record_Kind then
6935
6936               --  If parent type is tagged, the completion inherits the proper
6937               --  primitive operations.
6938
6939               if Is_Tagged_Type (Parent_Type) then
6940                  Build_Derived_Record_Type
6941                    (Full_N, Full_Parent, Full_Der, Derive_Subps);
6942               else
6943                  Build_Derived_Record_Type
6944                    (Full_N, Full_Parent, Full_Der, Derive_Subps => False);
6945               end if;
6946
6947            else
6948               Build_Derived_Type
6949                 (Full_N, Full_Parent, Full_Der,
6950                  Is_Completion => False, Derive_Subps => False);
6951            end if;
6952
6953            --  The full declaration has been introduced into the tree and
6954            --  processed in the step above. It should not be analyzed again
6955            --  (when encountered later in the current list of declarations)
6956            --  to prevent spurious name conflicts. The full entity remains
6957            --  invisible.
6958
6959            Set_Analyzed (Full_N);
6960
6961         else
6962            Full_Der :=
6963              Make_Defining_Identifier (Sloc (Derived_Type),
6964                Chars => Chars (Derived_Type));
6965            Set_Is_Itype (Full_Der);
6966            Set_Associated_Node_For_Itype (Full_Der, N);
6967            Set_Parent (Full_Der, N);
6968            Build_Derived_Type
6969              (N, Full_Parent, Full_Der,
6970               Is_Completion => False, Derive_Subps => False);
6971         end if;
6972
6973         Set_Has_Private_Declaration (Full_Der);
6974         Set_Has_Private_Declaration (Derived_Type);
6975
6976         Set_Scope                (Full_Der, Scope (Derived_Type));
6977         Set_Is_First_Subtype     (Full_Der, Is_First_Subtype (Derived_Type));
6978         Set_Has_Size_Clause      (Full_Der, False);
6979         Set_Has_Alignment_Clause (Full_Der, False);
6980         Set_Has_Delayed_Freeze   (Full_Der);
6981         Set_Is_Frozen            (Full_Der, False);
6982         Set_Freeze_Node          (Full_Der, Empty);
6983         Set_Depends_On_Private   (Full_Der, Has_Private_Component (Full_Der));
6984         Set_Is_Public            (Full_Der, Is_Public (Derived_Type));
6985
6986         --  The convention on the base type may be set in the private part
6987         --  and not propagated to the subtype until later, so we obtain the
6988         --  convention from the base type of the parent.
6989
6990         Set_Convention (Full_Der, Convention (Base_Type (Full_Parent)));
6991      end Copy_And_Build;
6992
6993   --  Start of processing for Build_Derived_Private_Type
6994
6995   begin
6996      if Is_Tagged_Type (Parent_Type) then
6997         Full_P := Full_View (Parent_Type);
6998
6999         --  A type extension of a type with unknown discriminants is an
7000         --  indefinite type that the back-end cannot handle directly.
7001         --  We treat it as a private type, and build a completion that is
7002         --  derived from the full view of the parent, and hopefully has
7003         --  known discriminants.
7004
7005         --  If the full view of the parent type has an underlying record view,
7006         --  use it to generate the underlying record view of this derived type
7007         --  (required for chains of derivations with unknown discriminants).
7008
7009         --  Minor optimization: we avoid the generation of useless underlying
7010         --  record view entities if the private type declaration has unknown
7011         --  discriminants but its corresponding full view has no
7012         --  discriminants.
7013
7014         if Has_Unknown_Discriminants (Parent_Type)
7015           and then Present (Full_P)
7016           and then (Has_Discriminants (Full_P)
7017                      or else Present (Underlying_Record_View (Full_P)))
7018           and then not In_Open_Scopes (Par_Scope)
7019           and then Expander_Active
7020         then
7021            declare
7022               Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
7023               New_Ext  : constant Node_Id :=
7024                            Copy_Separate_Tree
7025                              (Record_Extension_Part (Type_Definition (N)));
7026               Decl     : Node_Id;
7027
7028            begin
7029               Build_Derived_Record_Type
7030                 (N, Parent_Type, Derived_Type, Derive_Subps);
7031
7032               --  Build anonymous completion, as a derivation from the full
7033               --  view of the parent. This is not a completion in the usual
7034               --  sense, because the current type is not private.
7035
7036               Decl :=
7037                 Make_Full_Type_Declaration (Loc,
7038                   Defining_Identifier => Full_Der,
7039                   Type_Definition     =>
7040                     Make_Derived_Type_Definition (Loc,
7041                       Subtype_Indication =>
7042                         New_Copy_Tree
7043                           (Subtype_Indication (Type_Definition (N))),
7044                       Record_Extension_Part => New_Ext));
7045
7046               --  If the parent type has an underlying record view, use it
7047               --  here to build the new underlying record view.
7048
7049               if Present (Underlying_Record_View (Full_P)) then
7050                  pragma Assert
7051                    (Nkind (Subtype_Indication (Type_Definition (Decl)))
7052                       = N_Identifier);
7053                  Set_Entity (Subtype_Indication (Type_Definition (Decl)),
7054                    Underlying_Record_View (Full_P));
7055               end if;
7056
7057               Install_Private_Declarations (Par_Scope);
7058               Install_Visible_Declarations (Par_Scope);
7059               Insert_Before (N, Decl);
7060
7061               --  Mark entity as an underlying record view before analysis,
7062               --  to avoid generating the list of its primitive operations
7063               --  (which is not really required for this entity) and thus
7064               --  prevent spurious errors associated with missing overriding
7065               --  of abstract primitives (overridden only for Derived_Type).
7066
7067               Set_Ekind (Full_Der, E_Record_Type);
7068               Set_Is_Underlying_Record_View (Full_Der);
7069               Set_Default_SSO (Full_Der);
7070
7071               Analyze (Decl);
7072
7073               pragma Assert (Has_Discriminants (Full_Der)
7074                 and then not Has_Unknown_Discriminants (Full_Der));
7075
7076               Uninstall_Declarations (Par_Scope);
7077
7078               --  Freeze the underlying record view, to prevent generation of
7079               --  useless dispatching information, which is simply shared with
7080               --  the real derived type.
7081
7082               Set_Is_Frozen (Full_Der);
7083
7084               --  If the derived type has access discriminants, create
7085               --  references to their anonymous types now, to prevent
7086               --  back-end problems when their first use is in generated
7087               --  bodies of primitives.
7088
7089               declare
7090                  E : Entity_Id;
7091
7092               begin
7093                  E := First_Entity (Full_Der);
7094
7095                  while Present (E) loop
7096                     if Ekind (E) = E_Discriminant
7097                       and then Ekind (Etype (E)) = E_Anonymous_Access_Type
7098                     then
7099                        Build_Itype_Reference (Etype (E), Decl);
7100                     end if;
7101
7102                     Next_Entity (E);
7103                  end loop;
7104               end;
7105
7106               --  Set up links between real entity and underlying record view
7107
7108               Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
7109               Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
7110            end;
7111
7112         --  If discriminants are known, build derived record
7113
7114         else
7115            Build_Derived_Record_Type
7116              (N, Parent_Type, Derived_Type, Derive_Subps);
7117         end if;
7118
7119         return;
7120
7121      elsif Has_Discriminants (Parent_Type) then
7122
7123         --  Build partial view of derived type from partial view of parent.
7124         --  This must be done before building the full derivation because the
7125         --  second derivation will modify the discriminants of the first and
7126         --  the discriminants are chained with the rest of the components in
7127         --  the full derivation.
7128
7129         Build_Derived_Record_Type
7130           (N, Parent_Type, Derived_Type, Derive_Subps);
7131
7132         --  Build the full derivation if this is not the anonymous derived
7133         --  base type created by Build_Derived_Record_Type in the constrained
7134         --  case (see point 5. of its head comment) since we build it for the
7135         --  derived subtype. And skip it for protected types altogether, as
7136         --  gigi does not use these types directly.
7137
7138         if Present (Full_View (Parent_Type))
7139           and then not Is_Itype (Derived_Type)
7140           and then not (Ekind (Full_View (Parent_Type)) in Protected_Kind)
7141         then
7142            declare
7143               Der_Base   : constant Entity_Id := Base_Type (Derived_Type);
7144               Discr      : Entity_Id;
7145               Last_Discr : Entity_Id;
7146
7147            begin
7148               --  If this is not a completion, construct the implicit full
7149               --  view by deriving from the full view of the parent type.
7150               --  But if this is a completion, the derived private type
7151               --  being built is a full view and the full derivation can
7152               --  only be its underlying full view.
7153
7154               Build_Full_Derivation;
7155
7156               if not Is_Completion then
7157                  Set_Full_View (Derived_Type, Full_Der);
7158               else
7159                  Set_Underlying_Full_View (Derived_Type, Full_Der);
7160               end if;
7161
7162               if not Is_Base_Type (Derived_Type) then
7163                  Set_Full_View (Der_Base, Base_Type (Full_Der));
7164               end if;
7165
7166               --  Copy the discriminant list from full view to the partial
7167               --  view (base type and its subtype). Gigi requires that the
7168               --  partial and full views have the same discriminants.
7169
7170               --  Note that since the partial view points to discriminants
7171               --  in the full view, their scope will be that of the full
7172               --  view. This might cause some front end problems and need
7173               --  adjustment???
7174
7175               Discr := First_Discriminant (Base_Type (Full_Der));
7176               Set_First_Entity (Der_Base, Discr);
7177
7178               loop
7179                  Last_Discr := Discr;
7180                  Next_Discriminant (Discr);
7181                  exit when No (Discr);
7182               end loop;
7183
7184               Set_Last_Entity (Der_Base, Last_Discr);
7185               Set_First_Entity (Derived_Type, First_Entity (Der_Base));
7186               Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
7187
7188               Set_Stored_Constraint
7189                 (Full_Der, Stored_Constraint (Derived_Type));
7190            end;
7191         end if;
7192
7193      elsif Present (Full_View (Parent_Type))
7194        and then Has_Discriminants (Full_View (Parent_Type))
7195      then
7196         if Has_Unknown_Discriminants (Parent_Type)
7197           and then Nkind (Subtype_Indication (Type_Definition (N))) =
7198                                                         N_Subtype_Indication
7199         then
7200            Error_Msg_N
7201              ("cannot constrain type with unknown discriminants",
7202               Subtype_Indication (Type_Definition (N)));
7203            return;
7204         end if;
7205
7206         --  If this is not a completion, construct the implicit full view by
7207         --  deriving from the full view of the parent type. But if this is a
7208         --  completion, the derived private type being built is a full view
7209         --  and the full derivation can only be its underlying full view.
7210
7211         Build_Full_Derivation;
7212
7213         if not Is_Completion then
7214            Set_Full_View (Derived_Type, Full_Der);
7215         else
7216            Set_Underlying_Full_View (Derived_Type, Full_Der);
7217         end if;
7218
7219         --  In any case, the primitive operations are inherited from the
7220         --  parent type, not from the internal full view.
7221
7222         Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
7223
7224         if Derive_Subps then
7225            Derive_Subprograms (Parent_Type, Derived_Type);
7226         end if;
7227
7228         Set_Stored_Constraint (Derived_Type, No_Elist);
7229         Set_Is_Constrained
7230           (Derived_Type, Is_Constrained (Full_View (Parent_Type)));
7231
7232      else
7233         --  Untagged type, No discriminants on either view
7234
7235         if Nkind (Subtype_Indication (Type_Definition (N))) =
7236                                                   N_Subtype_Indication
7237         then
7238            Error_Msg_N
7239              ("illegal constraint on type without discriminants", N);
7240         end if;
7241
7242         if Present (Discriminant_Specifications (N))
7243           and then Present (Full_View (Parent_Type))
7244           and then not Is_Tagged_Type (Full_View (Parent_Type))
7245         then
7246            Error_Msg_N ("cannot add discriminants to untagged type", N);
7247         end if;
7248
7249         Set_Stored_Constraint (Derived_Type, No_Elist);
7250         Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
7251         Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
7252         Set_Has_Controlled_Component
7253                               (Derived_Type, Has_Controlled_Component
7254                                                             (Parent_Type));
7255
7256         --  Direct controlled types do not inherit Finalize_Storage_Only flag
7257
7258         if not Is_Controlled  (Parent_Type) then
7259            Set_Finalize_Storage_Only
7260              (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
7261         end if;
7262
7263         --  If this is not a completion, construct the implicit full view by
7264         --  deriving from the full view of the parent type.
7265
7266         --  ??? If the parent is untagged private and its completion is
7267         --  tagged, this mechanism will not work because we cannot derive from
7268         --  the tagged full view unless we have an extension.
7269
7270         if Present (Full_View (Parent_Type))
7271           and then not Is_Tagged_Type (Full_View (Parent_Type))
7272           and then not Is_Completion
7273         then
7274            Build_Full_Derivation;
7275            Set_Full_View (Derived_Type, Full_Der);
7276         end if;
7277      end if;
7278
7279      Set_Has_Unknown_Discriminants (Derived_Type,
7280        Has_Unknown_Discriminants (Parent_Type));
7281
7282      if Is_Private_Type (Derived_Type) then
7283         Set_Private_Dependents (Derived_Type, New_Elmt_List);
7284      end if;
7285
7286      --  If the parent base type is in scope, add the derived type to its
7287      --  list of private dependents, because its full view may become
7288      --  visible subsequently (in a nested private part, a body, or in a
7289      --  further child unit).
7290
7291      if Is_Private_Type (Par_Base) and then In_Open_Scopes (Par_Scope) then
7292         Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
7293
7294         --  Check for unusual case where a type completed by a private
7295         --  derivation occurs within a package nested in a child unit, and
7296         --  the parent is declared in an ancestor.
7297
7298         if Is_Child_Unit (Scope (Current_Scope))
7299           and then Is_Completion
7300           and then In_Private_Part (Current_Scope)
7301           and then Scope (Parent_Type) /= Current_Scope
7302
7303           --  Note that if the parent has a completion in the private part,
7304           --  (which is itself a derivation from some other private type)
7305           --  it is that completion that is visible, there is no full view
7306           --  available, and no special processing is needed.
7307
7308           and then Present (Full_View (Parent_Type))
7309         then
7310            --  In this case, the full view of the parent type will become
7311            --  visible in the body of the enclosing child, and only then will
7312            --  the current type be possibly non-private. Build an underlying
7313            --  full view that will be installed when the enclosing child body
7314            --  is compiled.
7315
7316            if Present (Underlying_Full_View (Derived_Type)) then
7317               Full_Der := Underlying_Full_View (Derived_Type);
7318            else
7319               Build_Full_Derivation;
7320               Set_Underlying_Full_View (Derived_Type, Full_Der);
7321            end if;
7322
7323            --  The full view will be used to swap entities on entry/exit to
7324            --  the body, and must appear in the entity list for the package.
7325
7326            Append_Entity (Full_Der, Scope (Derived_Type));
7327         end if;
7328      end if;
7329   end Build_Derived_Private_Type;
7330
7331   -------------------------------
7332   -- Build_Derived_Record_Type --
7333   -------------------------------
7334
7335   --  1. INTRODUCTION
7336
7337   --  Ideally we would like to use the same model of type derivation for
7338   --  tagged and untagged record types. Unfortunately this is not quite
7339   --  possible because the semantics of representation clauses is different
7340   --  for tagged and untagged records under inheritance. Consider the
7341   --  following:
7342
7343   --     type R (...) is [tagged] record ... end record;
7344   --     type T (...) is new R (...) [with ...];
7345
7346   --  The representation clauses for T can specify a completely different
7347   --  record layout from R's. Hence the same component can be placed in two
7348   --  very different positions in objects of type T and R. If R and T are
7349   --  tagged types, representation clauses for T can only specify the layout
7350   --  of non inherited components, thus components that are common in R and T
7351   --  have the same position in objects of type R and T.
7352
7353   --  This has two implications. The first is that the entire tree for R's
7354   --  declaration needs to be copied for T in the untagged case, so that T
7355   --  can be viewed as a record type of its own with its own representation
7356   --  clauses. The second implication is the way we handle discriminants.
7357   --  Specifically, in the untagged case we need a way to communicate to Gigi
7358   --  what are the real discriminants in the record, while for the semantics
7359   --  we need to consider those introduced by the user to rename the
7360   --  discriminants in the parent type. This is handled by introducing the
7361   --  notion of stored discriminants. See below for more.
7362
7363   --  Fortunately the way regular components are inherited can be handled in
7364   --  the same way in tagged and untagged types.
7365
7366   --  To complicate things a bit more the private view of a private extension
7367   --  cannot be handled in the same way as the full view (for one thing the
7368   --  semantic rules are somewhat different). We will explain what differs
7369   --  below.
7370
7371   --  2. DISCRIMINANTS UNDER INHERITANCE
7372
7373   --  The semantic rules governing the discriminants of derived types are
7374   --  quite subtle.
7375
7376   --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
7377   --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
7378
7379   --  If parent type has discriminants, then the discriminants that are
7380   --  declared in the derived type are [3.4 (11)]:
7381
7382   --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
7383   --    there is one;
7384
7385   --  o Otherwise, each discriminant of the parent type (implicitly declared
7386   --    in the same order with the same specifications). In this case, the
7387   --    discriminants are said to be "inherited", or if unknown in the parent
7388   --    are also unknown in the derived type.
7389
7390   --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
7391
7392   --  o The parent subtype must be constrained;
7393
7394   --  o If the parent type is not a tagged type, then each discriminant of
7395   --    the derived type must be used in the constraint defining a parent
7396   --    subtype. [Implementation note: This ensures that the new discriminant
7397   --    can share storage with an existing discriminant.]
7398
7399   --  For the derived type each discriminant of the parent type is either
7400   --  inherited, constrained to equal some new discriminant of the derived
7401   --  type, or constrained to the value of an expression.
7402
7403   --  When inherited or constrained to equal some new discriminant, the
7404   --  parent discriminant and the discriminant of the derived type are said
7405   --  to "correspond".
7406
7407   --  If a discriminant of the parent type is constrained to a specific value
7408   --  in the derived type definition, then the discriminant is said to be
7409   --  "specified" by that derived type definition.
7410
7411   --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
7412
7413   --  We have spoken about stored discriminants in point 1 (introduction)
7414   --  above. There are two sort of stored discriminants: implicit and
7415   --  explicit. As long as the derived type inherits the same discriminants as
7416   --  the root record type, stored discriminants are the same as regular
7417   --  discriminants, and are said to be implicit. However, if any discriminant
7418   --  in the root type was renamed in the derived type, then the derived
7419   --  type will contain explicit stored discriminants. Explicit stored
7420   --  discriminants are discriminants in addition to the semantically visible
7421   --  discriminants defined for the derived type. Stored discriminants are
7422   --  used by Gigi to figure out what are the physical discriminants in
7423   --  objects of the derived type (see precise definition in einfo.ads).
7424   --  As an example, consider the following:
7425
7426   --           type R  (D1, D2, D3 : Int) is record ... end record;
7427   --           type T1 is new R;
7428   --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
7429   --           type T3 is new T2;
7430   --           type T4 (Y : Int) is new T3 (Y, 99);
7431
7432   --  The following table summarizes the discriminants and stored
7433   --  discriminants in R and T1 through T4.
7434
7435   --   Type      Discrim     Stored Discrim  Comment
7436   --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
7437   --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
7438   --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
7439   --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
7440   --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
7441
7442   --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
7443   --  find the corresponding discriminant in the parent type, while
7444   --  Original_Record_Component (abbreviated ORC below), the actual physical
7445   --  component that is renamed. Finally the field Is_Completely_Hidden
7446   --  (abbreviated ICH below) is set for all explicit stored discriminants
7447   --  (see einfo.ads for more info). For the above example this gives:
7448
7449   --                 Discrim     CD        ORC     ICH
7450   --                 ^^^^^^^     ^^        ^^^     ^^^
7451   --                 D1 in R    empty     itself    no
7452   --                 D2 in R    empty     itself    no
7453   --                 D3 in R    empty     itself    no
7454
7455   --                 D1 in T1  D1 in R    itself    no
7456   --                 D2 in T1  D2 in R    itself    no
7457   --                 D3 in T1  D3 in R    itself    no
7458
7459   --                 X1 in T2  D3 in T1  D3 in T2   no
7460   --                 X2 in T2  D1 in T1  D1 in T2   no
7461   --                 D1 in T2   empty    itself    yes
7462   --                 D2 in T2   empty    itself    yes
7463   --                 D3 in T2   empty    itself    yes
7464
7465   --                 X1 in T3  X1 in T2  D3 in T3   no
7466   --                 X2 in T3  X2 in T2  D1 in T3   no
7467   --                 D1 in T3   empty    itself    yes
7468   --                 D2 in T3   empty    itself    yes
7469   --                 D3 in T3   empty    itself    yes
7470
7471   --                 Y  in T4  X1 in T3  D3 in T3   no
7472   --                 D1 in T3   empty    itself    yes
7473   --                 D2 in T3   empty    itself    yes
7474   --                 D3 in T3   empty    itself    yes
7475
7476   --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
7477
7478   --  Type derivation for tagged types is fairly straightforward. If no
7479   --  discriminants are specified by the derived type, these are inherited
7480   --  from the parent. No explicit stored discriminants are ever necessary.
7481   --  The only manipulation that is done to the tree is that of adding a
7482   --  _parent field with parent type and constrained to the same constraint
7483   --  specified for the parent in the derived type definition. For instance:
7484
7485   --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
7486   --           type T1 is new R with null record;
7487   --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
7488
7489   --  are changed into:
7490
7491   --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
7492   --              _parent : R (D1, D2, D3);
7493   --           end record;
7494
7495   --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
7496   --              _parent : T1 (X2, 88, X1);
7497   --           end record;
7498
7499   --  The discriminants actually present in R, T1 and T2 as well as their CD,
7500   --  ORC and ICH fields are:
7501
7502   --                 Discrim     CD        ORC     ICH
7503   --                 ^^^^^^^     ^^        ^^^     ^^^
7504   --                 D1 in R    empty     itself    no
7505   --                 D2 in R    empty     itself    no
7506   --                 D3 in R    empty     itself    no
7507
7508   --                 D1 in T1  D1 in R    D1 in R   no
7509   --                 D2 in T1  D2 in R    D2 in R   no
7510   --                 D3 in T1  D3 in R    D3 in R   no
7511
7512   --                 X1 in T2  D3 in T1   D3 in R   no
7513   --                 X2 in T2  D1 in T1   D1 in R   no
7514
7515   --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
7516   --
7517   --  Regardless of whether we dealing with a tagged or untagged type
7518   --  we will transform all derived type declarations of the form
7519   --
7520   --               type T is new R (...) [with ...];
7521   --  or
7522   --               subtype S is R (...);
7523   --               type T is new S [with ...];
7524   --  into
7525   --               type BT is new R [with ...];
7526   --               subtype T is BT (...);
7527   --
7528   --  That is, the base derived type is constrained only if it has no
7529   --  discriminants. The reason for doing this is that GNAT's semantic model
7530   --  assumes that a base type with discriminants is unconstrained.
7531   --
7532   --  Note that, strictly speaking, the above transformation is not always
7533   --  correct. Consider for instance the following excerpt from ACVC b34011a:
7534   --
7535   --       procedure B34011A is
7536   --          type REC (D : integer := 0) is record
7537   --             I : Integer;
7538   --          end record;
7539
7540   --          package P is
7541   --             type T6 is new Rec;
7542   --             function F return T6;
7543   --          end P;
7544
7545   --          use P;
7546   --          package Q6 is
7547   --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
7548   --          end Q6;
7549   --
7550   --  The definition of Q6.U is illegal. However transforming Q6.U into
7551
7552   --             type BaseU is new T6;
7553   --             subtype U is BaseU (Q6.F.I)
7554
7555   --  turns U into a legal subtype, which is incorrect. To avoid this problem
7556   --  we always analyze the constraint (in this case (Q6.F.I)) before applying
7557   --  the transformation described above.
7558
7559   --  There is another instance where the above transformation is incorrect.
7560   --  Consider:
7561
7562   --          package Pack is
7563   --             type Base (D : Integer) is tagged null record;
7564   --             procedure P (X : Base);
7565
7566   --             type Der is new Base (2) with null record;
7567   --             procedure P (X : Der);
7568   --          end Pack;
7569
7570   --  Then the above transformation turns this into
7571
7572   --             type Der_Base is new Base with null record;
7573   --             --  procedure P (X : Base) is implicitly inherited here
7574   --             --  as procedure P (X : Der_Base).
7575
7576   --             subtype Der is Der_Base (2);
7577   --             procedure P (X : Der);
7578   --             --  The overriding of P (X : Der_Base) is illegal since we
7579   --             --  have a parameter conformance problem.
7580
7581   --  To get around this problem, after having semantically processed Der_Base
7582   --  and the rewritten subtype declaration for Der, we copy Der_Base field
7583   --  Discriminant_Constraint from Der so that when parameter conformance is
7584   --  checked when P is overridden, no semantic errors are flagged.
7585
7586   --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
7587
7588   --  Regardless of whether we are dealing with a tagged or untagged type
7589   --  we will transform all derived type declarations of the form
7590
7591   --               type R (D1, .., Dn : ...) is [tagged] record ...;
7592   --               type T is new R [with ...];
7593   --  into
7594   --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
7595
7596   --  The reason for such transformation is that it allows us to implement a
7597   --  very clean form of component inheritance as explained below.
7598
7599   --  Note that this transformation is not achieved by direct tree rewriting
7600   --  and manipulation, but rather by redoing the semantic actions that the
7601   --  above transformation will entail. This is done directly in routine
7602   --  Inherit_Components.
7603
7604   --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
7605
7606   --  In both tagged and untagged derived types, regular non discriminant
7607   --  components are inherited in the derived type from the parent type. In
7608   --  the absence of discriminants component, inheritance is straightforward
7609   --  as components can simply be copied from the parent.
7610
7611   --  If the parent has discriminants, inheriting components constrained with
7612   --  these discriminants requires caution. Consider the following example:
7613
7614   --      type R  (D1, D2 : Positive) is [tagged] record
7615   --         S : String (D1 .. D2);
7616   --      end record;
7617
7618   --      type T1                is new R        [with null record];
7619   --      type T2 (X : positive) is new R (1, X) [with null record];
7620
7621   --  As explained in 6. above, T1 is rewritten as
7622   --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
7623   --  which makes the treatment for T1 and T2 identical.
7624
7625   --  What we want when inheriting S, is that references to D1 and D2 in R are
7626   --  replaced with references to their correct constraints, i.e. D1 and D2 in
7627   --  T1 and 1 and X in T2. So all R's discriminant references are replaced
7628   --  with either discriminant references in the derived type or expressions.
7629   --  This replacement is achieved as follows: before inheriting R's
7630   --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
7631   --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
7632   --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
7633   --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
7634   --  by String (1 .. X).
7635
7636   --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
7637
7638   --  We explain here the rules governing private type extensions relevant to
7639   --  type derivation. These rules are explained on the following example:
7640
7641   --      type D [(...)] is new A [(...)] with private;      <-- partial view
7642   --      type D [(...)] is new P [(...)] with null record;  <-- full view
7643
7644   --  Type A is called the ancestor subtype of the private extension.
7645   --  Type P is the parent type of the full view of the private extension. It
7646   --  must be A or a type derived from A.
7647
7648   --  The rules concerning the discriminants of private type extensions are
7649   --  [7.3(10-13)]:
7650
7651   --  o If a private extension inherits known discriminants from the ancestor
7652   --    subtype, then the full view must also inherit its discriminants from
7653   --    the ancestor subtype and the parent subtype of the full view must be
7654   --    constrained if and only if the ancestor subtype is constrained.
7655
7656   --  o If a partial view has unknown discriminants, then the full view may
7657   --    define a definite or an indefinite subtype, with or without
7658   --    discriminants.
7659
7660   --  o If a partial view has neither known nor unknown discriminants, then
7661   --    the full view must define a definite subtype.
7662
7663   --  o If the ancestor subtype of a private extension has constrained
7664   --    discriminants, then the parent subtype of the full view must impose a
7665   --    statically matching constraint on those discriminants.
7666
7667   --  This means that only the following forms of private extensions are
7668   --  allowed:
7669
7670   --      type D is new A with private;      <-- partial view
7671   --      type D is new P with null record;  <-- full view
7672
7673   --  If A has no discriminants than P has no discriminants, otherwise P must
7674   --  inherit A's discriminants.
7675
7676   --      type D is new A (...) with private;      <-- partial view
7677   --      type D is new P (:::) with null record;  <-- full view
7678
7679   --  P must inherit A's discriminants and (...) and (:::) must statically
7680   --  match.
7681
7682   --      subtype A is R (...);
7683   --      type D is new A with private;      <-- partial view
7684   --      type D is new P with null record;  <-- full view
7685
7686   --  P must have inherited R's discriminants and must be derived from A or
7687   --  any of its subtypes.
7688
7689   --      type D (..) is new A with private;              <-- partial view
7690   --      type D (..) is new P [(:::)] with null record;  <-- full view
7691
7692   --  No specific constraints on P's discriminants or constraint (:::).
7693   --  Note that A can be unconstrained, but the parent subtype P must either
7694   --  be constrained or (:::) must be present.
7695
7696   --      type D (..) is new A [(...)] with private;      <-- partial view
7697   --      type D (..) is new P [(:::)] with null record;  <-- full view
7698
7699   --  P's constraints on A's discriminants must statically match those
7700   --  imposed by (...).
7701
7702   --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
7703
7704   --  The full view of a private extension is handled exactly as described
7705   --  above. The model chose for the private view of a private extension is
7706   --  the same for what concerns discriminants (i.e. they receive the same
7707   --  treatment as in the tagged case). However, the private view of the
7708   --  private extension always inherits the components of the parent base,
7709   --  without replacing any discriminant reference. Strictly speaking this is
7710   --  incorrect. However, Gigi never uses this view to generate code so this
7711   --  is a purely semantic issue. In theory, a set of transformations similar
7712   --  to those given in 5. and 6. above could be applied to private views of
7713   --  private extensions to have the same model of component inheritance as
7714   --  for non private extensions. However, this is not done because it would
7715   --  further complicate private type processing. Semantically speaking, this
7716   --  leaves us in an uncomfortable situation. As an example consider:
7717
7718   --          package Pack is
7719   --             type R (D : integer) is tagged record
7720   --                S : String (1 .. D);
7721   --             end record;
7722   --             procedure P (X : R);
7723   --             type T is new R (1) with private;
7724   --          private
7725   --             type T is new R (1) with null record;
7726   --          end;
7727
7728   --  This is transformed into:
7729
7730   --          package Pack is
7731   --             type R (D : integer) is tagged record
7732   --                S : String (1 .. D);
7733   --             end record;
7734   --             procedure P (X : R);
7735   --             type T is new R (1) with private;
7736   --          private
7737   --             type BaseT is new R with null record;
7738   --             subtype  T is BaseT (1);
7739   --          end;
7740
7741   --  (strictly speaking the above is incorrect Ada)
7742
7743   --  From the semantic standpoint the private view of private extension T
7744   --  should be flagged as constrained since one can clearly have
7745   --
7746   --             Obj : T;
7747   --
7748   --  in a unit withing Pack. However, when deriving subprograms for the
7749   --  private view of private extension T, T must be seen as unconstrained
7750   --  since T has discriminants (this is a constraint of the current
7751   --  subprogram derivation model). Thus, when processing the private view of
7752   --  a private extension such as T, we first mark T as unconstrained, we
7753   --  process it, we perform program derivation and just before returning from
7754   --  Build_Derived_Record_Type we mark T as constrained.
7755
7756   --  ??? Are there are other uncomfortable cases that we will have to
7757   --      deal with.
7758
7759   --  10. RECORD_TYPE_WITH_PRIVATE complications
7760
7761   --  Types that are derived from a visible record type and have a private
7762   --  extension present other peculiarities. They behave mostly like private
7763   --  types, but if they have primitive operations defined, these will not
7764   --  have the proper signatures for further inheritance, because other
7765   --  primitive operations will use the implicit base that we define for
7766   --  private derivations below. This affect subprogram inheritance (see
7767   --  Derive_Subprograms for details). We also derive the implicit base from
7768   --  the base type of the full view, so that the implicit base is a record
7769   --  type and not another private type, This avoids infinite loops.
7770
7771   procedure Build_Derived_Record_Type
7772     (N            : Node_Id;
7773      Parent_Type  : Entity_Id;
7774      Derived_Type : Entity_Id;
7775      Derive_Subps : Boolean := True)
7776   is
7777      Discriminant_Specs : constant Boolean :=
7778                             Present (Discriminant_Specifications (N));
7779      Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
7780      Loc                : constant Source_Ptr := Sloc (N);
7781      Private_Extension  : constant Boolean :=
7782                             Nkind (N) = N_Private_Extension_Declaration;
7783      Assoc_List         : Elist_Id;
7784      Constraint_Present : Boolean;
7785      Constrs            : Elist_Id;
7786      Discrim            : Entity_Id;
7787      Indic              : Node_Id;
7788      Inherit_Discrims   : Boolean := False;
7789      Last_Discrim       : Entity_Id;
7790      New_Base           : Entity_Id;
7791      New_Decl           : Node_Id;
7792      New_Discrs         : Elist_Id;
7793      New_Indic          : Node_Id;
7794      Parent_Base        : Entity_Id;
7795      Save_Etype         : Entity_Id;
7796      Save_Discr_Constr  : Elist_Id;
7797      Save_Next_Entity   : Entity_Id;
7798      Type_Def           : Node_Id;
7799
7800      Discs : Elist_Id := New_Elmt_List;
7801      --  An empty Discs list means that there were no constraints in the
7802      --  subtype indication or that there was an error processing it.
7803
7804   begin
7805      if Ekind (Parent_Type) = E_Record_Type_With_Private
7806        and then Present (Full_View (Parent_Type))
7807        and then Has_Discriminants (Parent_Type)
7808      then
7809         Parent_Base := Base_Type (Full_View (Parent_Type));
7810      else
7811         Parent_Base := Base_Type (Parent_Type);
7812      end if;
7813
7814      --  AI05-0115 : if this is a derivation from a private type in some
7815      --  other scope that may lead to invisible components for the derived
7816      --  type, mark it accordingly.
7817
7818      if Is_Private_Type (Parent_Type) then
7819         if Scope (Parent_Type) = Scope (Derived_Type) then
7820            null;
7821
7822         elsif In_Open_Scopes (Scope (Parent_Type))
7823           and then In_Private_Part (Scope (Parent_Type))
7824         then
7825            null;
7826
7827         else
7828            Set_Has_Private_Ancestor (Derived_Type);
7829         end if;
7830
7831      else
7832         Set_Has_Private_Ancestor
7833           (Derived_Type, Has_Private_Ancestor (Parent_Type));
7834      end if;
7835
7836      --  Before we start the previously documented transformations, here is
7837      --  little fix for size and alignment of tagged types. Normally when we
7838      --  derive type D from type P, we copy the size and alignment of P as the
7839      --  default for D, and in the absence of explicit representation clauses
7840      --  for D, the size and alignment are indeed the same as the parent.
7841
7842      --  But this is wrong for tagged types, since fields may be added, and
7843      --  the default size may need to be larger, and the default alignment may
7844      --  need to be larger.
7845
7846      --  We therefore reset the size and alignment fields in the tagged case.
7847      --  Note that the size and alignment will in any case be at least as
7848      --  large as the parent type (since the derived type has a copy of the
7849      --  parent type in the _parent field)
7850
7851      --  The type is also marked as being tagged here, which is needed when
7852      --  processing components with a self-referential anonymous access type
7853      --  in the call to Check_Anonymous_Access_Components below. Note that
7854      --  this flag is also set later on for completeness.
7855
7856      if Is_Tagged then
7857         Set_Is_Tagged_Type (Derived_Type);
7858         Init_Size_Align    (Derived_Type);
7859      end if;
7860
7861      --  STEP 0a: figure out what kind of derived type declaration we have
7862
7863      if Private_Extension then
7864         Type_Def := N;
7865         Set_Ekind (Derived_Type, E_Record_Type_With_Private);
7866         Set_Default_SSO (Derived_Type);
7867
7868      else
7869         Type_Def := Type_Definition (N);
7870
7871         --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7872         --  Parent_Base can be a private type or private extension. However,
7873         --  for tagged types with an extension the newly added fields are
7874         --  visible and hence the Derived_Type is always an E_Record_Type.
7875         --  (except that the parent may have its own private fields).
7876         --  For untagged types we preserve the Ekind of the Parent_Base.
7877
7878         if Present (Record_Extension_Part (Type_Def)) then
7879            Set_Ekind (Derived_Type, E_Record_Type);
7880            Set_Default_SSO (Derived_Type);
7881
7882            --  Create internal access types for components with anonymous
7883            --  access types.
7884
7885            if Ada_Version >= Ada_2005 then
7886               Check_Anonymous_Access_Components
7887                 (N, Derived_Type, Derived_Type,
7888                   Component_List (Record_Extension_Part (Type_Def)));
7889            end if;
7890
7891         else
7892            Set_Ekind (Derived_Type, Ekind (Parent_Base));
7893         end if;
7894      end if;
7895
7896      --  Indic can either be an N_Identifier if the subtype indication
7897      --  contains no constraint or an N_Subtype_Indication if the subtype
7898      --  indication has a constraint.
7899
7900      Indic := Subtype_Indication (Type_Def);
7901      Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
7902
7903      --  Check that the type has visible discriminants. The type may be
7904      --  a private type with unknown discriminants whose full view has
7905      --  discriminants which are invisible.
7906
7907      if Constraint_Present then
7908         if not Has_Discriminants (Parent_Base)
7909           or else
7910             (Has_Unknown_Discriminants (Parent_Base)
7911               and then Is_Private_Type (Parent_Base))
7912         then
7913            Error_Msg_N
7914              ("invalid constraint: type has no discriminant",
7915                 Constraint (Indic));
7916
7917            Constraint_Present := False;
7918            Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7919
7920         elsif Is_Constrained (Parent_Type) then
7921            Error_Msg_N
7922               ("invalid constraint: parent type is already constrained",
7923                  Constraint (Indic));
7924
7925            Constraint_Present := False;
7926            Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7927         end if;
7928      end if;
7929
7930      --  STEP 0b: If needed, apply transformation given in point 5. above
7931
7932      if not Private_Extension
7933        and then Has_Discriminants (Parent_Type)
7934        and then not Discriminant_Specs
7935        and then (Is_Constrained (Parent_Type) or else Constraint_Present)
7936      then
7937         --  First, we must analyze the constraint (see comment in point 5.)
7938         --  The constraint may come from the subtype indication of the full
7939         --  declaration.
7940
7941         if Constraint_Present then
7942            New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
7943
7944         --  If there is no explicit constraint, there might be one that is
7945         --  inherited from a constrained parent type. In that case verify that
7946         --  it conforms to the constraint in the partial view. In perverse
7947         --  cases the parent subtypes of the partial and full view can have
7948         --  different constraints.
7949
7950         elsif Present (Stored_Constraint (Parent_Type)) then
7951            New_Discrs := Stored_Constraint (Parent_Type);
7952
7953         else
7954            New_Discrs := No_Elist;
7955         end if;
7956
7957         if Has_Discriminants (Derived_Type)
7958           and then Has_Private_Declaration (Derived_Type)
7959           and then Present (Discriminant_Constraint (Derived_Type))
7960           and then Present (New_Discrs)
7961         then
7962            --  Verify that constraints of the full view statically match
7963            --  those given in the partial view.
7964
7965            declare
7966               C1, C2 : Elmt_Id;
7967
7968            begin
7969               C1 := First_Elmt (New_Discrs);
7970               C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
7971               while Present (C1) and then Present (C2) loop
7972                  if Fully_Conformant_Expressions (Node (C1), Node (C2))
7973                    or else
7974                      (Is_OK_Static_Expression (Node (C1))
7975                        and then Is_OK_Static_Expression (Node (C2))
7976                        and then
7977                          Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
7978                  then
7979                     null;
7980
7981                  else
7982                     if Constraint_Present then
7983                        Error_Msg_N
7984                          ("constraint not conformant to previous declaration",
7985                           Node (C1));
7986                     else
7987                        Error_Msg_N
7988                          ("constraint of full view is incompatible "
7989                           & "with partial view", N);
7990                     end if;
7991                  end if;
7992
7993                  Next_Elmt (C1);
7994                  Next_Elmt (C2);
7995               end loop;
7996            end;
7997         end if;
7998
7999         --  Insert and analyze the declaration for the unconstrained base type
8000
8001         New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
8002
8003         New_Decl :=
8004           Make_Full_Type_Declaration (Loc,
8005              Defining_Identifier => New_Base,
8006              Type_Definition     =>
8007                Make_Derived_Type_Definition (Loc,
8008                  Abstract_Present      => Abstract_Present (Type_Def),
8009                  Limited_Present       => Limited_Present (Type_Def),
8010                  Subtype_Indication    =>
8011                    New_Occurrence_Of (Parent_Base, Loc),
8012                  Record_Extension_Part =>
8013                    Relocate_Node (Record_Extension_Part (Type_Def)),
8014                  Interface_List        => Interface_List (Type_Def)));
8015
8016         Set_Parent (New_Decl, Parent (N));
8017         Mark_Rewrite_Insertion (New_Decl);
8018         Insert_Before (N, New_Decl);
8019
8020         --  In the extension case, make sure ancestor is frozen appropriately
8021         --  (see also non-discriminated case below).
8022
8023         if Present (Record_Extension_Part (Type_Def))
8024           or else Is_Interface (Parent_Base)
8025         then
8026            Freeze_Before (New_Decl, Parent_Type);
8027         end if;
8028
8029         --  Note that this call passes False for the Derive_Subps parameter
8030         --  because subprogram derivation is deferred until after creating
8031         --  the subtype (see below).
8032
8033         Build_Derived_Type
8034           (New_Decl, Parent_Base, New_Base,
8035            Is_Completion => False, Derive_Subps => False);
8036
8037         --  ??? This needs re-examination to determine whether the
8038         --  above call can simply be replaced by a call to Analyze.
8039
8040         Set_Analyzed (New_Decl);
8041
8042         --  Insert and analyze the declaration for the constrained subtype
8043
8044         if Constraint_Present then
8045            New_Indic :=
8046              Make_Subtype_Indication (Loc,
8047                Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
8048                Constraint   => Relocate_Node (Constraint (Indic)));
8049
8050         else
8051            declare
8052               Constr_List : constant List_Id := New_List;
8053               C           : Elmt_Id;
8054               Expr        : Node_Id;
8055
8056            begin
8057               C := First_Elmt (Discriminant_Constraint (Parent_Type));
8058               while Present (C) loop
8059                  Expr := Node (C);
8060
8061                  --  It is safe here to call New_Copy_Tree since we called
8062                  --  Force_Evaluation on each constraint previously
8063                  --  in Build_Discriminant_Constraints.
8064
8065                  Append (New_Copy_Tree (Expr), To => Constr_List);
8066
8067                  Next_Elmt (C);
8068               end loop;
8069
8070               New_Indic :=
8071                 Make_Subtype_Indication (Loc,
8072                   Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
8073                   Constraint   =>
8074                     Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
8075            end;
8076         end if;
8077
8078         Rewrite (N,
8079           Make_Subtype_Declaration (Loc,
8080             Defining_Identifier => Derived_Type,
8081             Subtype_Indication  => New_Indic));
8082
8083         Analyze (N);
8084
8085         --  Derivation of subprograms must be delayed until the full subtype
8086         --  has been established, to ensure proper overriding of subprograms
8087         --  inherited by full types. If the derivations occurred as part of
8088         --  the call to Build_Derived_Type above, then the check for type
8089         --  conformance would fail because earlier primitive subprograms
8090         --  could still refer to the full type prior the change to the new
8091         --  subtype and hence would not match the new base type created here.
8092         --  Subprograms are not derived, however, when Derive_Subps is False
8093         --  (since otherwise there could be redundant derivations).
8094
8095         if Derive_Subps then
8096            Derive_Subprograms (Parent_Type, Derived_Type);
8097         end if;
8098
8099         --  For tagged types the Discriminant_Constraint of the new base itype
8100         --  is inherited from the first subtype so that no subtype conformance
8101         --  problem arise when the first subtype overrides primitive
8102         --  operations inherited by the implicit base type.
8103
8104         if Is_Tagged then
8105            Set_Discriminant_Constraint
8106              (New_Base, Discriminant_Constraint (Derived_Type));
8107         end if;
8108
8109         return;
8110      end if;
8111
8112      --  If we get here Derived_Type will have no discriminants or it will be
8113      --  a discriminated unconstrained base type.
8114
8115      --  STEP 1a: perform preliminary actions/checks for derived tagged types
8116
8117      if Is_Tagged then
8118
8119         --  The parent type is frozen for non-private extensions (RM 13.14(7))
8120         --  The declaration of a specific descendant of an interface type
8121         --  freezes the interface type (RM 13.14).
8122
8123         if not Private_Extension or else Is_Interface (Parent_Base) then
8124            Freeze_Before (N, Parent_Type);
8125         end if;
8126
8127         --  In Ada 2005 (AI-344), the restriction that a derived tagged type
8128         --  cannot be declared at a deeper level than its parent type is
8129         --  removed. The check on derivation within a generic body is also
8130         --  relaxed, but there's a restriction that a derived tagged type
8131         --  cannot be declared in a generic body if it's derived directly
8132         --  or indirectly from a formal type of that generic.
8133
8134         if Ada_Version >= Ada_2005 then
8135            if Present (Enclosing_Generic_Body (Derived_Type)) then
8136               declare
8137                  Ancestor_Type : Entity_Id;
8138
8139               begin
8140                  --  Check to see if any ancestor of the derived type is a
8141                  --  formal type.
8142
8143                  Ancestor_Type := Parent_Type;
8144                  while not Is_Generic_Type (Ancestor_Type)
8145                    and then Etype (Ancestor_Type) /= Ancestor_Type
8146                  loop
8147                     Ancestor_Type := Etype (Ancestor_Type);
8148                  end loop;
8149
8150                  --  If the derived type does have a formal type as an
8151                  --  ancestor, then it's an error if the derived type is
8152                  --  declared within the body of the generic unit that
8153                  --  declares the formal type in its generic formal part. It's
8154                  --  sufficient to check whether the ancestor type is declared
8155                  --  inside the same generic body as the derived type (such as
8156                  --  within a nested generic spec), in which case the
8157                  --  derivation is legal. If the formal type is declared
8158                  --  outside of that generic body, then it's guaranteed that
8159                  --  the derived type is declared within the generic body of
8160                  --  the generic unit declaring the formal type.
8161
8162                  if Is_Generic_Type (Ancestor_Type)
8163                    and then Enclosing_Generic_Body (Ancestor_Type) /=
8164                               Enclosing_Generic_Body (Derived_Type)
8165                  then
8166                     Error_Msg_NE
8167                       ("parent type of& must not be descendant of formal type"
8168                          & " of an enclosing generic body",
8169                            Indic, Derived_Type);
8170                  end if;
8171               end;
8172            end if;
8173
8174         elsif Type_Access_Level (Derived_Type) /=
8175                 Type_Access_Level (Parent_Type)
8176           and then not Is_Generic_Type (Derived_Type)
8177         then
8178            if Is_Controlled (Parent_Type) then
8179               Error_Msg_N
8180                 ("controlled type must be declared at the library level",
8181                  Indic);
8182            else
8183               Error_Msg_N
8184                 ("type extension at deeper accessibility level than parent",
8185                  Indic);
8186            end if;
8187
8188         else
8189            declare
8190               GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
8191            begin
8192               if Present (GB)
8193                 and then GB /= Enclosing_Generic_Body (Parent_Base)
8194               then
8195                  Error_Msg_NE
8196                    ("parent type of& must not be outside generic body"
8197                       & " (RM 3.9.1(4))",
8198                         Indic, Derived_Type);
8199               end if;
8200            end;
8201         end if;
8202      end if;
8203
8204      --  Ada 2005 (AI-251)
8205
8206      if Ada_Version >= Ada_2005 and then Is_Tagged then
8207
8208         --  "The declaration of a specific descendant of an interface type
8209         --  freezes the interface type" (RM 13.14).
8210
8211         declare
8212            Iface : Node_Id;
8213         begin
8214            if Is_Non_Empty_List (Interface_List (Type_Def)) then
8215               Iface := First (Interface_List (Type_Def));
8216               while Present (Iface) loop
8217                  Freeze_Before (N, Etype (Iface));
8218                  Next (Iface);
8219               end loop;
8220            end if;
8221         end;
8222      end if;
8223
8224      --  STEP 1b : preliminary cleanup of the full view of private types
8225
8226      --  If the type is already marked as having discriminants, then it's the
8227      --  completion of a private type or private extension and we need to
8228      --  retain the discriminants from the partial view if the current
8229      --  declaration has Discriminant_Specifications so that we can verify
8230      --  conformance. However, we must remove any existing components that
8231      --  were inherited from the parent (and attached in Copy_And_Swap)
8232      --  because the full type inherits all appropriate components anyway, and
8233      --  we do not want the partial view's components interfering.
8234
8235      if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
8236         Discrim := First_Discriminant (Derived_Type);
8237         loop
8238            Last_Discrim := Discrim;
8239            Next_Discriminant (Discrim);
8240            exit when No (Discrim);
8241         end loop;
8242
8243         Set_Last_Entity (Derived_Type, Last_Discrim);
8244
8245      --  In all other cases wipe out the list of inherited components (even
8246      --  inherited discriminants), it will be properly rebuilt here.
8247
8248      else
8249         Set_First_Entity (Derived_Type, Empty);
8250         Set_Last_Entity  (Derived_Type, Empty);
8251      end if;
8252
8253      --  STEP 1c: Initialize some flags for the Derived_Type
8254
8255      --  The following flags must be initialized here so that
8256      --  Process_Discriminants can check that discriminants of tagged types do
8257      --  not have a default initial value and that access discriminants are
8258      --  only specified for limited records. For completeness, these flags are
8259      --  also initialized along with all the other flags below.
8260
8261      --  AI-419: Limitedness is not inherited from an interface parent, so to
8262      --  be limited in that case the type must be explicitly declared as
8263      --  limited. However, task and protected interfaces are always limited.
8264
8265      if Limited_Present (Type_Def) then
8266         Set_Is_Limited_Record (Derived_Type);
8267
8268      elsif Is_Limited_Record (Parent_Type)
8269        or else (Present (Full_View (Parent_Type))
8270                  and then Is_Limited_Record (Full_View (Parent_Type)))
8271      then
8272         if not Is_Interface (Parent_Type)
8273           or else Is_Synchronized_Interface (Parent_Type)
8274           or else Is_Protected_Interface (Parent_Type)
8275           or else Is_Task_Interface (Parent_Type)
8276         then
8277            Set_Is_Limited_Record (Derived_Type);
8278         end if;
8279      end if;
8280
8281      --  STEP 2a: process discriminants of derived type if any
8282
8283      Push_Scope (Derived_Type);
8284
8285      if Discriminant_Specs then
8286         Set_Has_Unknown_Discriminants (Derived_Type, False);
8287
8288         --  The following call initializes fields Has_Discriminants and
8289         --  Discriminant_Constraint, unless we are processing the completion
8290         --  of a private type declaration.
8291
8292         Check_Or_Process_Discriminants (N, Derived_Type);
8293
8294         --  For untagged types, the constraint on the Parent_Type must be
8295         --  present and is used to rename the discriminants.
8296
8297         if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
8298            Error_Msg_N ("untagged parent must have discriminants", Indic);
8299
8300         elsif not Is_Tagged and then not Constraint_Present then
8301            Error_Msg_N
8302              ("discriminant constraint needed for derived untagged records",
8303               Indic);
8304
8305         --  Otherwise the parent subtype must be constrained unless we have a
8306         --  private extension.
8307
8308         elsif not Constraint_Present
8309           and then not Private_Extension
8310           and then not Is_Constrained (Parent_Type)
8311         then
8312            Error_Msg_N
8313              ("unconstrained type not allowed in this context", Indic);
8314
8315         elsif Constraint_Present then
8316            --  The following call sets the field Corresponding_Discriminant
8317            --  for the discriminants in the Derived_Type.
8318
8319            Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
8320
8321            --  For untagged types all new discriminants must rename
8322            --  discriminants in the parent. For private extensions new
8323            --  discriminants cannot rename old ones (implied by [7.3(13)]).
8324
8325            Discrim := First_Discriminant (Derived_Type);
8326            while Present (Discrim) loop
8327               if not Is_Tagged
8328                 and then No (Corresponding_Discriminant (Discrim))
8329               then
8330                  Error_Msg_N
8331                    ("new discriminants must constrain old ones", Discrim);
8332
8333               elsif Private_Extension
8334                 and then Present (Corresponding_Discriminant (Discrim))
8335               then
8336                  Error_Msg_N
8337                    ("only static constraints allowed for parent"
8338                     & " discriminants in the partial view", Indic);
8339                  exit;
8340               end if;
8341
8342               --  If a new discriminant is used in the constraint, then its
8343               --  subtype must be statically compatible with the parent
8344               --  discriminant's subtype (3.7(15)).
8345
8346               --  However, if the record contains an array constrained by
8347               --  the discriminant but with some different bound, the compiler
8348               --  attemps to create a smaller range for the discriminant type.
8349               --  (See exp_ch3.Adjust_Discriminants). In this case, where
8350               --  the discriminant type is a scalar type, the check must use
8351               --  the original discriminant type in the parent declaration.
8352
8353               declare
8354                  Corr_Disc : constant Entity_Id :=
8355                                Corresponding_Discriminant (Discrim);
8356                  Disc_Type : constant Entity_Id := Etype (Discrim);
8357                  Corr_Type : Entity_Id;
8358
8359               begin
8360                  if Present (Corr_Disc) then
8361                     if Is_Scalar_Type (Disc_Type) then
8362                        Corr_Type :=
8363                           Entity (Discriminant_Type (Parent (Corr_Disc)));
8364                     else
8365                        Corr_Type := Etype (Corr_Disc);
8366                     end if;
8367
8368                     if not
8369                        Subtypes_Statically_Compatible (Disc_Type, Corr_Type)
8370                     then
8371                        Error_Msg_N
8372                          ("subtype must be compatible "
8373                           & "with parent discriminant",
8374                           Discrim);
8375                     end if;
8376                  end if;
8377               end;
8378
8379               Next_Discriminant (Discrim);
8380            end loop;
8381
8382            --  Check whether the constraints of the full view statically
8383            --  match those imposed by the parent subtype [7.3(13)].
8384
8385            if Present (Stored_Constraint (Derived_Type)) then
8386               declare
8387                  C1, C2 : Elmt_Id;
8388
8389               begin
8390                  C1 := First_Elmt (Discs);
8391                  C2 := First_Elmt (Stored_Constraint (Derived_Type));
8392                  while Present (C1) and then Present (C2) loop
8393                     if not
8394                       Fully_Conformant_Expressions (Node (C1), Node (C2))
8395                     then
8396                        Error_Msg_N
8397                          ("not conformant with previous declaration",
8398                           Node (C1));
8399                     end if;
8400
8401                     Next_Elmt (C1);
8402                     Next_Elmt (C2);
8403                  end loop;
8404               end;
8405            end if;
8406         end if;
8407
8408      --  STEP 2b: No new discriminants, inherit discriminants if any
8409
8410      else
8411         if Private_Extension then
8412            Set_Has_Unknown_Discriminants
8413              (Derived_Type,
8414               Has_Unknown_Discriminants (Parent_Type)
8415                 or else Unknown_Discriminants_Present (N));
8416
8417         --  The partial view of the parent may have unknown discriminants,
8418         --  but if the full view has discriminants and the parent type is
8419         --  in scope they must be inherited.
8420
8421         elsif Has_Unknown_Discriminants (Parent_Type)
8422           and then
8423            (not Has_Discriminants (Parent_Type)
8424              or else not In_Open_Scopes (Scope (Parent_Type)))
8425         then
8426            Set_Has_Unknown_Discriminants (Derived_Type);
8427         end if;
8428
8429         if not Has_Unknown_Discriminants (Derived_Type)
8430           and then not Has_Unknown_Discriminants (Parent_Base)
8431           and then Has_Discriminants (Parent_Type)
8432         then
8433            Inherit_Discrims := True;
8434            Set_Has_Discriminants
8435              (Derived_Type, True);
8436            Set_Discriminant_Constraint
8437              (Derived_Type, Discriminant_Constraint (Parent_Base));
8438         end if;
8439
8440         --  The following test is true for private types (remember
8441         --  transformation 5. is not applied to those) and in an error
8442         --  situation.
8443
8444         if Constraint_Present then
8445            Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
8446         end if;
8447
8448         --  For now mark a new derived type as constrained only if it has no
8449         --  discriminants. At the end of Build_Derived_Record_Type we properly
8450         --  set this flag in the case of private extensions. See comments in
8451         --  point 9. just before body of Build_Derived_Record_Type.
8452
8453         Set_Is_Constrained
8454           (Derived_Type,
8455            not (Inherit_Discrims
8456                  or else Has_Unknown_Discriminants (Derived_Type)));
8457      end if;
8458
8459      --  STEP 3: initialize fields of derived type
8460
8461      Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
8462      Set_Stored_Constraint (Derived_Type, No_Elist);
8463
8464      --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
8465      --  but cannot be interfaces
8466
8467      if not Private_Extension
8468         and then Ekind (Derived_Type) /= E_Private_Type
8469         and then Ekind (Derived_Type) /= E_Limited_Private_Type
8470      then
8471         if Interface_Present (Type_Def) then
8472            Analyze_Interface_Declaration (Derived_Type, Type_Def);
8473         end if;
8474
8475         Set_Interfaces (Derived_Type, No_Elist);
8476      end if;
8477
8478      --  Fields inherited from the Parent_Type
8479
8480      Set_Has_Specified_Layout
8481        (Derived_Type, Has_Specified_Layout     (Parent_Type));
8482      Set_Is_Limited_Composite
8483        (Derived_Type, Is_Limited_Composite     (Parent_Type));
8484      Set_Is_Private_Composite
8485        (Derived_Type, Is_Private_Composite     (Parent_Type));
8486
8487      if Is_Tagged_Type (Parent_Type) then
8488         Set_No_Tagged_Streams_Pragma
8489           (Derived_Type, No_Tagged_Streams_Pragma (Parent_Type));
8490      end if;
8491
8492      --  Fields inherited from the Parent_Base
8493
8494      Set_Has_Controlled_Component
8495        (Derived_Type, Has_Controlled_Component (Parent_Base));
8496      Set_Has_Non_Standard_Rep
8497        (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
8498      Set_Has_Primitive_Operations
8499        (Derived_Type, Has_Primitive_Operations (Parent_Base));
8500
8501      --  Fields inherited from the Parent_Base in the non-private case
8502
8503      if Ekind (Derived_Type) = E_Record_Type then
8504         Set_Has_Complex_Representation
8505           (Derived_Type, Has_Complex_Representation (Parent_Base));
8506      end if;
8507
8508      --  Fields inherited from the Parent_Base for record types
8509
8510      if Is_Record_Type (Derived_Type) then
8511         declare
8512            Parent_Full : Entity_Id;
8513
8514         begin
8515            --  Ekind (Parent_Base) is not necessarily E_Record_Type since
8516            --  Parent_Base can be a private type or private extension. Go
8517            --  to the full view here to get the E_Record_Type specific flags.
8518
8519            if Present (Full_View (Parent_Base)) then
8520               Parent_Full := Full_View (Parent_Base);
8521            else
8522               Parent_Full := Parent_Base;
8523            end if;
8524
8525            Set_OK_To_Reorder_Components
8526              (Derived_Type, OK_To_Reorder_Components (Parent_Full));
8527         end;
8528      end if;
8529
8530      --  Set fields for private derived types
8531
8532      if Is_Private_Type (Derived_Type) then
8533         Set_Depends_On_Private (Derived_Type, True);
8534         Set_Private_Dependents (Derived_Type, New_Elmt_List);
8535
8536      --  Inherit fields from non private record types. If this is the
8537      --  completion of a derivation from a private type, the parent itself
8538      --  is private, and the attributes come from its full view, which must
8539      --  be present.
8540
8541      else
8542         if Is_Private_Type (Parent_Base)
8543           and then not Is_Record_Type (Parent_Base)
8544         then
8545            Set_Component_Alignment
8546              (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
8547            Set_C_Pass_By_Copy
8548              (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
8549         else
8550            Set_Component_Alignment
8551              (Derived_Type, Component_Alignment (Parent_Base));
8552            Set_C_Pass_By_Copy
8553              (Derived_Type, C_Pass_By_Copy      (Parent_Base));
8554         end if;
8555      end if;
8556
8557      --  Set fields for tagged types
8558
8559      if Is_Tagged then
8560         Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
8561
8562         --  All tagged types defined in Ada.Finalization are controlled
8563
8564         if Chars (Scope (Derived_Type)) = Name_Finalization
8565           and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
8566           and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
8567         then
8568            Set_Is_Controlled (Derived_Type);
8569         else
8570            Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
8571         end if;
8572
8573         --  Minor optimization: there is no need to generate the class-wide
8574         --  entity associated with an underlying record view.
8575
8576         if not Is_Underlying_Record_View (Derived_Type) then
8577            Make_Class_Wide_Type (Derived_Type);
8578         end if;
8579
8580         Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
8581
8582         if Has_Discriminants (Derived_Type)
8583           and then Constraint_Present
8584         then
8585            Set_Stored_Constraint
8586              (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
8587         end if;
8588
8589         if Ada_Version >= Ada_2005 then
8590            declare
8591               Ifaces_List : Elist_Id;
8592
8593            begin
8594               --  Checks rules 3.9.4 (13/2 and 14/2)
8595
8596               if Comes_From_Source (Derived_Type)
8597                 and then not Is_Private_Type (Derived_Type)
8598                 and then Is_Interface (Parent_Type)
8599                 and then not Is_Interface (Derived_Type)
8600               then
8601                  if Is_Task_Interface (Parent_Type) then
8602                     Error_Msg_N
8603                       ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
8604                        Derived_Type);
8605
8606                  elsif Is_Protected_Interface (Parent_Type) then
8607                     Error_Msg_N
8608                       ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
8609                        Derived_Type);
8610                  end if;
8611               end if;
8612
8613               --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
8614
8615               Check_Interfaces (N, Type_Def);
8616
8617               --  Ada 2005 (AI-251): Collect the list of progenitors that are
8618               --  not already in the parents.
8619
8620               Collect_Interfaces
8621                 (T               => Derived_Type,
8622                  Ifaces_List     => Ifaces_List,
8623                  Exclude_Parents => True);
8624
8625               Set_Interfaces (Derived_Type, Ifaces_List);
8626
8627               --  If the derived type is the anonymous type created for
8628               --  a declaration whose parent has a constraint, propagate
8629               --  the interface list to the source type. This must be done
8630               --  prior to the completion of the analysis of the source type
8631               --  because the components in the extension may contain current
8632               --  instances whose legality depends on some ancestor.
8633
8634               if Is_Itype (Derived_Type) then
8635                  declare
8636                     Def : constant Node_Id :=
8637                             Associated_Node_For_Itype (Derived_Type);
8638                  begin
8639                     if Present (Def)
8640                       and then Nkind (Def) = N_Full_Type_Declaration
8641                     then
8642                        Set_Interfaces
8643                          (Defining_Identifier (Def), Ifaces_List);
8644                     end if;
8645                  end;
8646               end if;
8647
8648               --  Propagate inherited invariant information of parents
8649               --  and progenitors
8650
8651               if Ada_Version >= Ada_2012
8652                 and then not Is_Interface (Derived_Type)
8653               then
8654                  if Has_Inheritable_Invariants (Parent_Type) then
8655                     Set_Has_Invariants (Derived_Type);
8656                     Set_Has_Inheritable_Invariants (Derived_Type);
8657
8658                  elsif not Is_Empty_Elmt_List (Ifaces_List) then
8659                     declare
8660                        AI : Elmt_Id;
8661
8662                     begin
8663                        AI := First_Elmt (Ifaces_List);
8664                        while Present (AI) loop
8665                           if Has_Inheritable_Invariants (Node (AI)) then
8666                              Set_Has_Invariants (Derived_Type);
8667                              Set_Has_Inheritable_Invariants (Derived_Type);
8668
8669                              exit;
8670                           end if;
8671
8672                           Next_Elmt (AI);
8673                        end loop;
8674                     end;
8675                  end if;
8676               end if;
8677
8678               --  A type extension is automatically Ghost when one of its
8679               --  progenitors is Ghost (SPARK RM 6.9(9)). This property is
8680               --  also inherited when the parent type is Ghost, but this is
8681               --  done in Build_Derived_Type as the mechanism also handles
8682               --  untagged derivations.
8683
8684               if Implements_Ghost_Interface (Derived_Type) then
8685                  Set_Is_Ghost_Entity (Derived_Type);
8686               end if;
8687            end;
8688         end if;
8689
8690      else
8691         Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
8692         Set_Has_Non_Standard_Rep
8693                       (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
8694      end if;
8695
8696      --  STEP 4: Inherit components from the parent base and constrain them.
8697      --          Apply the second transformation described in point 6. above.
8698
8699      if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
8700        or else not Has_Discriminants (Parent_Type)
8701        or else not Is_Constrained (Parent_Type)
8702      then
8703         Constrs := Discs;
8704      else
8705         Constrs := Discriminant_Constraint (Parent_Type);
8706      end if;
8707
8708      Assoc_List :=
8709        Inherit_Components
8710          (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
8711
8712      --  STEP 5a: Copy the parent record declaration for untagged types
8713
8714      if not Is_Tagged then
8715
8716         --  Discriminant_Constraint (Derived_Type) has been properly
8717         --  constructed. Save it and temporarily set it to Empty because we
8718         --  do not want the call to New_Copy_Tree below to mess this list.
8719
8720         if Has_Discriminants (Derived_Type) then
8721            Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
8722            Set_Discriminant_Constraint (Derived_Type, No_Elist);
8723         else
8724            Save_Discr_Constr := No_Elist;
8725         end if;
8726
8727         --  Save the Etype field of Derived_Type. It is correctly set now,
8728         --  but the call to New_Copy tree may remap it to point to itself,
8729         --  which is not what we want. Ditto for the Next_Entity field.
8730
8731         Save_Etype       := Etype (Derived_Type);
8732         Save_Next_Entity := Next_Entity (Derived_Type);
8733
8734         --  Assoc_List maps all stored discriminants in the Parent_Base to
8735         --  stored discriminants in the Derived_Type. It is fundamental that
8736         --  no types or itypes with discriminants other than the stored
8737         --  discriminants appear in the entities declared inside
8738         --  Derived_Type, since the back end cannot deal with it.
8739
8740         New_Decl :=
8741           New_Copy_Tree
8742             (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
8743
8744         --  Restore the fields saved prior to the New_Copy_Tree call
8745         --  and compute the stored constraint.
8746
8747         Set_Etype       (Derived_Type, Save_Etype);
8748         Set_Next_Entity (Derived_Type, Save_Next_Entity);
8749
8750         if Has_Discriminants (Derived_Type) then
8751            Set_Discriminant_Constraint
8752              (Derived_Type, Save_Discr_Constr);
8753            Set_Stored_Constraint
8754              (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
8755            Replace_Components (Derived_Type, New_Decl);
8756            Set_Has_Implicit_Dereference
8757              (Derived_Type, Has_Implicit_Dereference (Parent_Type));
8758         end if;
8759
8760         --  Insert the new derived type declaration
8761
8762         Rewrite (N, New_Decl);
8763
8764      --  STEP 5b: Complete the processing for record extensions in generics
8765
8766      --  There is no completion for record extensions declared in the
8767      --  parameter part of a generic, so we need to complete processing for
8768      --  these generic record extensions here. The Record_Type_Definition call
8769      --  will change the Ekind of the components from E_Void to E_Component.
8770
8771      elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
8772         Record_Type_Definition (Empty, Derived_Type);
8773
8774      --  STEP 5c: Process the record extension for non private tagged types
8775
8776      elsif not Private_Extension then
8777         Expand_Record_Extension (Derived_Type, Type_Def);
8778
8779         --  Note : previously in ASIS mode we set the Parent_Subtype of the
8780         --  derived type to propagate some semantic information. This led
8781         --  to other ASIS failures and has been removed.
8782
8783         --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
8784         --  implemented interfaces if we are in expansion mode
8785
8786         if Expander_Active
8787           and then Has_Interfaces (Derived_Type)
8788         then
8789            Add_Interface_Tag_Components (N, Derived_Type);
8790         end if;
8791
8792         --  Analyze the record extension
8793
8794         Record_Type_Definition
8795           (Record_Extension_Part (Type_Def), Derived_Type);
8796      end if;
8797
8798      End_Scope;
8799
8800      --  Nothing else to do if there is an error in the derivation.
8801      --  An unusual case: the full view may be derived from a type in an
8802      --  instance, when the partial view was used illegally as an actual
8803      --  in that instance, leading to a circular definition.
8804
8805      if Etype (Derived_Type) = Any_Type
8806        or else Etype (Parent_Type) = Derived_Type
8807      then
8808         return;
8809      end if;
8810
8811      --  Set delayed freeze and then derive subprograms, we need to do
8812      --  this in this order so that derived subprograms inherit the
8813      --  derived freeze if necessary.
8814
8815      Set_Has_Delayed_Freeze (Derived_Type);
8816
8817      if Derive_Subps then
8818         Derive_Subprograms (Parent_Type, Derived_Type);
8819      end if;
8820
8821      --  If we have a private extension which defines a constrained derived
8822      --  type mark as constrained here after we have derived subprograms. See
8823      --  comment on point 9. just above the body of Build_Derived_Record_Type.
8824
8825      if Private_Extension and then Inherit_Discrims then
8826         if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
8827            Set_Is_Constrained          (Derived_Type, True);
8828            Set_Discriminant_Constraint (Derived_Type, Discs);
8829
8830         elsif Is_Constrained (Parent_Type) then
8831            Set_Is_Constrained
8832              (Derived_Type, True);
8833            Set_Discriminant_Constraint
8834              (Derived_Type, Discriminant_Constraint (Parent_Type));
8835         end if;
8836      end if;
8837
8838      --  Update the class-wide type, which shares the now-completed entity
8839      --  list with its specific type. In case of underlying record views,
8840      --  we do not generate the corresponding class wide entity.
8841
8842      if Is_Tagged
8843        and then not Is_Underlying_Record_View (Derived_Type)
8844      then
8845         Set_First_Entity
8846           (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
8847         Set_Last_Entity
8848           (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
8849      end if;
8850
8851      Check_Function_Writable_Actuals (N);
8852   end Build_Derived_Record_Type;
8853
8854   ------------------------
8855   -- Build_Derived_Type --
8856   ------------------------
8857
8858   procedure Build_Derived_Type
8859     (N             : Node_Id;
8860      Parent_Type   : Entity_Id;
8861      Derived_Type  : Entity_Id;
8862      Is_Completion : Boolean;
8863      Derive_Subps  : Boolean := True)
8864   is
8865      Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
8866
8867   begin
8868      --  Set common attributes
8869
8870      Set_Scope          (Derived_Type, Current_Scope);
8871
8872      Set_Etype          (Derived_Type,                Parent_Base);
8873      Set_Ekind          (Derived_Type, Ekind         (Parent_Base));
8874      Set_Has_Task       (Derived_Type, Has_Task      (Parent_Base));
8875      Set_Has_Protected  (Derived_Type, Has_Protected (Parent_Base));
8876
8877      Set_Size_Info      (Derived_Type,                 Parent_Type);
8878      Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
8879      Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
8880      Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
8881      Set_Is_Volatile    (Derived_Type, Is_Volatile    (Parent_Type));
8882
8883      if Is_Tagged_Type (Derived_Type) then
8884         Set_No_Tagged_Streams_Pragma
8885           (Derived_Type, No_Tagged_Streams_Pragma (Parent_Type));
8886      end if;
8887
8888      --  If the parent has primitive routines, set the derived type link
8889
8890      if Has_Primitive_Operations (Parent_Type) then
8891         Set_Derived_Type_Link (Parent_Base, Derived_Type);
8892      end if;
8893
8894      --  If the parent type is a private subtype, the convention on the base
8895      --  type may be set in the private part, and not propagated to the
8896      --  subtype until later, so we obtain the convention from the base type.
8897
8898      Set_Convention (Derived_Type, Convention (Parent_Base));
8899
8900      --  Set SSO default for record or array type
8901
8902      if (Is_Array_Type (Derived_Type) or else Is_Record_Type (Derived_Type))
8903        and then Is_Base_Type (Derived_Type)
8904      then
8905         Set_Default_SSO (Derived_Type);
8906      end if;
8907
8908      --  Propagate invariant information. The new type has invariants if
8909      --  they are inherited from the parent type, and these invariants can
8910      --  be further inherited, so both flags are set.
8911
8912      --  We similarly inherit predicates
8913
8914      if Has_Predicates (Parent_Type) then
8915         Set_Has_Predicates (Derived_Type);
8916      end if;
8917
8918      --  The derived type inherits the representation clauses of the parent
8919
8920      Inherit_Rep_Item_Chain (Derived_Type, Parent_Type);
8921
8922      --  Propagate the attributes related to pragma Default_Initial_Condition
8923      --  from the parent type to the private extension. A derived type always
8924      --  inherits the default initial condition flag from the parent type. If
8925      --  the derived type carries its own Default_Initial_Condition pragma,
8926      --  the flag is later reset in Analyze_Pragma. Note that both flags are
8927      --  mutually exclusive.
8928
8929      Propagate_Default_Init_Cond_Attributes
8930        (From_Typ             => Parent_Type,
8931         To_Typ               => Derived_Type,
8932         Parent_To_Derivation => True);
8933
8934      --  If the parent type has delayed rep aspects, then mark the derived
8935      --  type as possibly inheriting a delayed rep aspect.
8936
8937      if Has_Delayed_Rep_Aspects (Parent_Type) then
8938         Set_May_Inherit_Delayed_Rep_Aspects (Derived_Type);
8939      end if;
8940
8941      --  Propagate the attributes related to pragma Ghost from the parent type
8942      --  to the derived type or type extension (SPARK RM 6.9(9)).
8943
8944      if Is_Ghost_Entity (Parent_Type) then
8945         Set_Is_Ghost_Entity (Derived_Type);
8946      end if;
8947
8948      --  Type dependent processing
8949
8950      case Ekind (Parent_Type) is
8951         when Numeric_Kind =>
8952            Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
8953
8954         when Array_Kind =>
8955            Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
8956
8957         when E_Record_Type
8958            | E_Record_Subtype
8959            | Class_Wide_Kind  =>
8960            Build_Derived_Record_Type
8961              (N, Parent_Type, Derived_Type, Derive_Subps);
8962            return;
8963
8964         when Enumeration_Kind =>
8965            Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
8966
8967         when Access_Kind =>
8968            Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
8969
8970         when Incomplete_Or_Private_Kind =>
8971            Build_Derived_Private_Type
8972              (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
8973
8974            --  For discriminated types, the derivation includes deriving
8975            --  primitive operations. For others it is done below.
8976
8977            if Is_Tagged_Type (Parent_Type)
8978              or else Has_Discriminants (Parent_Type)
8979              or else (Present (Full_View (Parent_Type))
8980                        and then Has_Discriminants (Full_View (Parent_Type)))
8981            then
8982               return;
8983            end if;
8984
8985         when Concurrent_Kind =>
8986            Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
8987
8988         when others =>
8989            raise Program_Error;
8990      end case;
8991
8992      --  Nothing more to do if some error occurred
8993
8994      if Etype (Derived_Type) = Any_Type then
8995         return;
8996      end if;
8997
8998      --  Set delayed freeze and then derive subprograms, we need to do this
8999      --  in this order so that derived subprograms inherit the derived freeze
9000      --  if necessary.
9001
9002      Set_Has_Delayed_Freeze (Derived_Type);
9003
9004      if Derive_Subps then
9005         Derive_Subprograms (Parent_Type, Derived_Type);
9006      end if;
9007
9008      Set_Has_Primitive_Operations
9009        (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
9010   end Build_Derived_Type;
9011
9012   -----------------------
9013   -- Build_Discriminal --
9014   -----------------------
9015
9016   procedure Build_Discriminal (Discrim : Entity_Id) is
9017      D_Minal : Entity_Id;
9018      CR_Disc : Entity_Id;
9019
9020   begin
9021      --  A discriminal has the same name as the discriminant
9022
9023      D_Minal := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
9024
9025      Set_Ekind     (D_Minal, E_In_Parameter);
9026      Set_Mechanism (D_Minal, Default_Mechanism);
9027      Set_Etype     (D_Minal, Etype (Discrim));
9028      Set_Scope     (D_Minal, Current_Scope);
9029
9030      Set_Discriminal (Discrim, D_Minal);
9031      Set_Discriminal_Link (D_Minal, Discrim);
9032
9033      --  For task types, build at once the discriminants of the corresponding
9034      --  record, which are needed if discriminants are used in entry defaults
9035      --  and in family bounds.
9036
9037      if Is_Concurrent_Type (Current_Scope)
9038           or else
9039         Is_Limited_Type    (Current_Scope)
9040      then
9041         CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
9042
9043         Set_Ekind            (CR_Disc, E_In_Parameter);
9044         Set_Mechanism        (CR_Disc, Default_Mechanism);
9045         Set_Etype            (CR_Disc, Etype (Discrim));
9046         Set_Scope            (CR_Disc, Current_Scope);
9047         Set_Discriminal_Link (CR_Disc, Discrim);
9048         Set_CR_Discriminant  (Discrim, CR_Disc);
9049      end if;
9050   end Build_Discriminal;
9051
9052   ------------------------------------
9053   -- Build_Discriminant_Constraints --
9054   ------------------------------------
9055
9056   function Build_Discriminant_Constraints
9057     (T           : Entity_Id;
9058      Def         : Node_Id;
9059      Derived_Def : Boolean := False) return Elist_Id
9060   is
9061      C        : constant Node_Id := Constraint (Def);
9062      Nb_Discr : constant Nat     := Number_Discriminants (T);
9063
9064      Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
9065      --  Saves the expression corresponding to a given discriminant in T
9066
9067      function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
9068      --  Return the Position number within array Discr_Expr of a discriminant
9069      --  D within the discriminant list of the discriminated type T.
9070
9071      procedure Process_Discriminant_Expression
9072         (Expr : Node_Id;
9073          D    : Entity_Id);
9074      --  If this is a discriminant constraint on a partial view, do not
9075      --  generate an overflow check on the discriminant expression. The check
9076      --  will be generated when constraining the full view. Otherwise the
9077      --  backend creates duplicate symbols for the temporaries corresponding
9078      --  to the expressions to be checked, causing spurious assembler errors.
9079
9080      ------------------
9081      -- Pos_Of_Discr --
9082      ------------------
9083
9084      function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
9085         Disc : Entity_Id;
9086
9087      begin
9088         Disc := First_Discriminant (T);
9089         for J in Discr_Expr'Range loop
9090            if Disc = D then
9091               return J;
9092            end if;
9093
9094            Next_Discriminant (Disc);
9095         end loop;
9096
9097         --  Note: Since this function is called on discriminants that are
9098         --  known to belong to the discriminated type, falling through the
9099         --  loop with no match signals an internal compiler error.
9100
9101         raise Program_Error;
9102      end Pos_Of_Discr;
9103
9104      -------------------------------------
9105      -- Process_Discriminant_Expression --
9106      -------------------------------------
9107
9108      procedure Process_Discriminant_Expression
9109         (Expr : Node_Id;
9110          D    : Entity_Id)
9111      is
9112         BDT : constant Entity_Id := Base_Type (Etype (D));
9113
9114      begin
9115         --  If this is a discriminant constraint on a partial view, do
9116         --  not generate an overflow on the discriminant expression. The
9117         --  check will be generated when constraining the full view.
9118
9119         if Is_Private_Type (T)
9120           and then Present (Full_View (T))
9121         then
9122            Analyze_And_Resolve (Expr, BDT, Suppress => Overflow_Check);
9123         else
9124            Analyze_And_Resolve (Expr, BDT);
9125         end if;
9126      end Process_Discriminant_Expression;
9127
9128      --  Declarations local to Build_Discriminant_Constraints
9129
9130      Discr : Entity_Id;
9131      E     : Entity_Id;
9132      Elist : constant Elist_Id := New_Elmt_List;
9133
9134      Constr   : Node_Id;
9135      Expr     : Node_Id;
9136      Id       : Node_Id;
9137      Position : Nat;
9138      Found    : Boolean;
9139
9140      Discrim_Present : Boolean := False;
9141
9142   --  Start of processing for Build_Discriminant_Constraints
9143
9144   begin
9145      --  The following loop will process positional associations only.
9146      --  For a positional association, the (single) discriminant is
9147      --  implicitly specified by position, in textual order (RM 3.7.2).
9148
9149      Discr  := First_Discriminant (T);
9150      Constr := First (Constraints (C));
9151      for D in Discr_Expr'Range loop
9152         exit when Nkind (Constr) = N_Discriminant_Association;
9153
9154         if No (Constr) then
9155            Error_Msg_N ("too few discriminants given in constraint", C);
9156            return New_Elmt_List;
9157
9158         elsif Nkind (Constr) = N_Range
9159           or else (Nkind (Constr) = N_Attribute_Reference
9160                     and then Attribute_Name (Constr) = Name_Range)
9161         then
9162            Error_Msg_N
9163              ("a range is not a valid discriminant constraint", Constr);
9164            Discr_Expr (D) := Error;
9165
9166         else
9167            Process_Discriminant_Expression (Constr, Discr);
9168            Discr_Expr (D) := Constr;
9169         end if;
9170
9171         Next_Discriminant (Discr);
9172         Next (Constr);
9173      end loop;
9174
9175      if No (Discr) and then Present (Constr) then
9176         Error_Msg_N ("too many discriminants given in constraint", Constr);
9177         return New_Elmt_List;
9178      end if;
9179
9180      --  Named associations can be given in any order, but if both positional
9181      --  and named associations are used in the same discriminant constraint,
9182      --  then positional associations must occur first, at their normal
9183      --  position. Hence once a named association is used, the rest of the
9184      --  discriminant constraint must use only named associations.
9185
9186      while Present (Constr) loop
9187
9188         --  Positional association forbidden after a named association
9189
9190         if Nkind (Constr) /= N_Discriminant_Association then
9191            Error_Msg_N ("positional association follows named one", Constr);
9192            return New_Elmt_List;
9193
9194         --  Otherwise it is a named association
9195
9196         else
9197            --  E records the type of the discriminants in the named
9198            --  association. All the discriminants specified in the same name
9199            --  association must have the same type.
9200
9201            E := Empty;
9202
9203            --  Search the list of discriminants in T to see if the simple name
9204            --  given in the constraint matches any of them.
9205
9206            Id := First (Selector_Names (Constr));
9207            while Present (Id) loop
9208               Found := False;
9209
9210               --  If Original_Discriminant is present, we are processing a
9211               --  generic instantiation and this is an instance node. We need
9212               --  to find the name of the corresponding discriminant in the
9213               --  actual record type T and not the name of the discriminant in
9214               --  the generic formal. Example:
9215
9216               --    generic
9217               --       type G (D : int) is private;
9218               --    package P is
9219               --       subtype W is G (D => 1);
9220               --    end package;
9221               --    type Rec (X : int) is record ... end record;
9222               --    package Q is new P (G => Rec);
9223
9224               --  At the point of the instantiation, formal type G is Rec
9225               --  and therefore when reanalyzing "subtype W is G (D => 1);"
9226               --  which really looks like "subtype W is Rec (D => 1);" at
9227               --  the point of instantiation, we want to find the discriminant
9228               --  that corresponds to D in Rec, i.e. X.
9229
9230               if Present (Original_Discriminant (Id))
9231                 and then In_Instance
9232               then
9233                  Discr := Find_Corresponding_Discriminant (Id, T);
9234                  Found := True;
9235
9236               else
9237                  Discr := First_Discriminant (T);
9238                  while Present (Discr) loop
9239                     if Chars (Discr) = Chars (Id) then
9240                        Found := True;
9241                        exit;
9242                     end if;
9243
9244                     Next_Discriminant (Discr);
9245                  end loop;
9246
9247                  if not Found then
9248                     Error_Msg_N ("& does not match any discriminant", Id);
9249                     return New_Elmt_List;
9250
9251                  --  If the parent type is a generic formal, preserve the
9252                  --  name of the discriminant for subsequent instances.
9253                  --  see comment at the beginning of this if statement.
9254
9255                  elsif Is_Generic_Type (Root_Type (T)) then
9256                     Set_Original_Discriminant (Id, Discr);
9257                  end if;
9258               end if;
9259
9260               Position := Pos_Of_Discr (T, Discr);
9261
9262               if Present (Discr_Expr (Position)) then
9263                  Error_Msg_N ("duplicate constraint for discriminant&", Id);
9264
9265               else
9266                  --  Each discriminant specified in the same named association
9267                  --  must be associated with a separate copy of the
9268                  --  corresponding expression.
9269
9270                  if Present (Next (Id)) then
9271                     Expr := New_Copy_Tree (Expression (Constr));
9272                     Set_Parent (Expr, Parent (Expression (Constr)));
9273                  else
9274                     Expr := Expression (Constr);
9275                  end if;
9276
9277                  Discr_Expr (Position) := Expr;
9278                  Process_Discriminant_Expression (Expr, Discr);
9279               end if;
9280
9281               --  A discriminant association with more than one discriminant
9282               --  name is only allowed if the named discriminants are all of
9283               --  the same type (RM 3.7.1(8)).
9284
9285               if E = Empty then
9286                  E := Base_Type (Etype (Discr));
9287
9288               elsif Base_Type (Etype (Discr)) /= E then
9289                  Error_Msg_N
9290                    ("all discriminants in an association " &
9291                     "must have the same type", Id);
9292               end if;
9293
9294               Next (Id);
9295            end loop;
9296         end if;
9297
9298         Next (Constr);
9299      end loop;
9300
9301      --  A discriminant constraint must provide exactly one value for each
9302      --  discriminant of the type (RM 3.7.1(8)).
9303
9304      for J in Discr_Expr'Range loop
9305         if No (Discr_Expr (J)) then
9306            Error_Msg_N ("too few discriminants given in constraint", C);
9307            return New_Elmt_List;
9308         end if;
9309      end loop;
9310
9311      --  Determine if there are discriminant expressions in the constraint
9312
9313      for J in Discr_Expr'Range loop
9314         if Denotes_Discriminant
9315              (Discr_Expr (J), Check_Concurrent => True)
9316         then
9317            Discrim_Present := True;
9318         end if;
9319      end loop;
9320
9321      --  Build an element list consisting of the expressions given in the
9322      --  discriminant constraint and apply the appropriate checks. The list
9323      --  is constructed after resolving any named discriminant associations
9324      --  and therefore the expressions appear in the textual order of the
9325      --  discriminants.
9326
9327      Discr := First_Discriminant (T);
9328      for J in Discr_Expr'Range loop
9329         if Discr_Expr (J) /= Error then
9330            Append_Elmt (Discr_Expr (J), Elist);
9331
9332            --  If any of the discriminant constraints is given by a
9333            --  discriminant and we are in a derived type declaration we
9334            --  have a discriminant renaming. Establish link between new
9335            --  and old discriminant.
9336
9337            if Denotes_Discriminant (Discr_Expr (J)) then
9338               if Derived_Def then
9339                  Set_Corresponding_Discriminant
9340                    (Entity (Discr_Expr (J)), Discr);
9341               end if;
9342
9343            --  Force the evaluation of non-discriminant expressions.
9344            --  If we have found a discriminant in the constraint 3.4(26)
9345            --  and 3.8(18) demand that no range checks are performed are
9346            --  after evaluation. If the constraint is for a component
9347            --  definition that has a per-object constraint, expressions are
9348            --  evaluated but not checked either. In all other cases perform
9349            --  a range check.
9350
9351            else
9352               if Discrim_Present then
9353                  null;
9354
9355               elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
9356                 and then
9357                   Has_Per_Object_Constraint
9358                     (Defining_Identifier (Parent (Parent (Def))))
9359               then
9360                  null;
9361
9362               elsif Is_Access_Type (Etype (Discr)) then
9363                  Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
9364
9365               else
9366                  Apply_Range_Check (Discr_Expr (J), Etype (Discr));
9367               end if;
9368
9369               Force_Evaluation (Discr_Expr (J));
9370            end if;
9371
9372            --  Check that the designated type of an access discriminant's
9373            --  expression is not a class-wide type unless the discriminant's
9374            --  designated type is also class-wide.
9375
9376            if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
9377              and then not Is_Class_Wide_Type
9378                         (Designated_Type (Etype (Discr)))
9379              and then Etype (Discr_Expr (J)) /= Any_Type
9380              and then Is_Class_Wide_Type
9381                         (Designated_Type (Etype (Discr_Expr (J))))
9382            then
9383               Wrong_Type (Discr_Expr (J), Etype (Discr));
9384
9385            elsif Is_Access_Type (Etype (Discr))
9386              and then not Is_Access_Constant (Etype (Discr))
9387              and then Is_Access_Type (Etype (Discr_Expr (J)))
9388              and then Is_Access_Constant (Etype (Discr_Expr (J)))
9389            then
9390               Error_Msg_NE
9391                 ("constraint for discriminant& must be access to variable",
9392                    Def, Discr);
9393            end if;
9394         end if;
9395
9396         Next_Discriminant (Discr);
9397      end loop;
9398
9399      return Elist;
9400   end Build_Discriminant_Constraints;
9401
9402   ---------------------------------
9403   -- Build_Discriminated_Subtype --
9404   ---------------------------------
9405
9406   procedure Build_Discriminated_Subtype
9407     (T           : Entity_Id;
9408      Def_Id      : Entity_Id;
9409      Elist       : Elist_Id;
9410      Related_Nod : Node_Id;
9411      For_Access  : Boolean := False)
9412   is
9413      Has_Discrs  : constant Boolean := Has_Discriminants (T);
9414      Constrained : constant Boolean :=
9415                      (Has_Discrs
9416                         and then not Is_Empty_Elmt_List (Elist)
9417                         and then not Is_Class_Wide_Type (T))
9418                        or else Is_Constrained (T);
9419
9420   begin
9421      if Ekind (T) = E_Record_Type then
9422         if For_Access then
9423            Set_Ekind (Def_Id, E_Private_Subtype);
9424            Set_Is_For_Access_Subtype (Def_Id, True);
9425         else
9426            Set_Ekind (Def_Id, E_Record_Subtype);
9427         end if;
9428
9429         --  Inherit preelaboration flag from base, for types for which it
9430         --  may have been set: records, private types, protected types.
9431
9432         Set_Known_To_Have_Preelab_Init
9433           (Def_Id, Known_To_Have_Preelab_Init (T));
9434
9435      elsif Ekind (T) = E_Task_Type then
9436         Set_Ekind (Def_Id, E_Task_Subtype);
9437
9438      elsif Ekind (T) = E_Protected_Type then
9439         Set_Ekind (Def_Id, E_Protected_Subtype);
9440         Set_Known_To_Have_Preelab_Init
9441           (Def_Id, Known_To_Have_Preelab_Init (T));
9442
9443      elsif Is_Private_Type (T) then
9444         Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
9445         Set_Known_To_Have_Preelab_Init
9446           (Def_Id, Known_To_Have_Preelab_Init (T));
9447
9448         --  Private subtypes may have private dependents
9449
9450         Set_Private_Dependents (Def_Id, New_Elmt_List);
9451
9452      elsif Is_Class_Wide_Type (T) then
9453         Set_Ekind (Def_Id, E_Class_Wide_Subtype);
9454
9455      else
9456         --  Incomplete type. Attach subtype to list of dependents, to be
9457         --  completed with full view of parent type,  unless is it the
9458         --  designated subtype of a record component within an init_proc.
9459         --  This last case arises for a component of an access type whose
9460         --  designated type is incomplete (e.g. a Taft Amendment type).
9461         --  The designated subtype is within an inner scope, and needs no
9462         --  elaboration, because only the access type is needed in the
9463         --  initialization procedure.
9464
9465         Set_Ekind (Def_Id, Ekind (T));
9466
9467         if For_Access and then Within_Init_Proc then
9468            null;
9469         else
9470            Append_Elmt (Def_Id, Private_Dependents (T));
9471         end if;
9472      end if;
9473
9474      Set_Etype             (Def_Id, T);
9475      Init_Size_Align       (Def_Id);
9476      Set_Has_Discriminants (Def_Id, Has_Discrs);
9477      Set_Is_Constrained    (Def_Id, Constrained);
9478
9479      Set_First_Entity      (Def_Id, First_Entity   (T));
9480      Set_Last_Entity       (Def_Id, Last_Entity    (T));
9481      Set_Has_Implicit_Dereference
9482                            (Def_Id, Has_Implicit_Dereference (T));
9483
9484      --  If the subtype is the completion of a private declaration, there may
9485      --  have been representation clauses for the partial view, and they must
9486      --  be preserved. Build_Derived_Type chains the inherited clauses with
9487      --  the ones appearing on the extension. If this comes from a subtype
9488      --  declaration, all clauses are inherited.
9489
9490      if No (First_Rep_Item (Def_Id)) then
9491         Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
9492      end if;
9493
9494      if Is_Tagged_Type (T) then
9495         Set_Is_Tagged_Type (Def_Id);
9496         Set_No_Tagged_Streams_Pragma (Def_Id, No_Tagged_Streams_Pragma (T));
9497         Make_Class_Wide_Type (Def_Id);
9498      end if;
9499
9500      Set_Stored_Constraint (Def_Id, No_Elist);
9501
9502      if Has_Discrs then
9503         Set_Discriminant_Constraint (Def_Id, Elist);
9504         Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
9505      end if;
9506
9507      if Is_Tagged_Type (T) then
9508
9509         --  Ada 2005 (AI-251): In case of concurrent types we inherit the
9510         --  concurrent record type (which has the list of primitive
9511         --  operations).
9512
9513         if Ada_Version >= Ada_2005
9514           and then Is_Concurrent_Type (T)
9515         then
9516            Set_Corresponding_Record_Type (Def_Id,
9517               Corresponding_Record_Type (T));
9518         else
9519            Set_Direct_Primitive_Operations (Def_Id,
9520              Direct_Primitive_Operations (T));
9521         end if;
9522
9523         Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
9524      end if;
9525
9526      --  Subtypes introduced by component declarations do not need to be
9527      --  marked as delayed, and do not get freeze nodes, because the semantics
9528      --  verifies that the parents of the subtypes are frozen before the
9529      --  enclosing record is frozen.
9530
9531      if not Is_Type (Scope (Def_Id)) then
9532         Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
9533
9534         if Is_Private_Type (T)
9535           and then Present (Full_View (T))
9536         then
9537            Conditional_Delay (Def_Id, Full_View (T));
9538         else
9539            Conditional_Delay (Def_Id, T);
9540         end if;
9541      end if;
9542
9543      if Is_Record_Type (T) then
9544         Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
9545
9546         if Has_Discrs
9547            and then not Is_Empty_Elmt_List (Elist)
9548            and then not For_Access
9549         then
9550            Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
9551         elsif not For_Access then
9552            Set_Cloned_Subtype (Def_Id, T);
9553         end if;
9554      end if;
9555   end Build_Discriminated_Subtype;
9556
9557   ---------------------------
9558   -- Build_Itype_Reference --
9559   ---------------------------
9560
9561   procedure Build_Itype_Reference
9562     (Ityp : Entity_Id;
9563      Nod  : Node_Id)
9564   is
9565      IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
9566   begin
9567
9568      --  Itype references are only created for use by the back-end
9569
9570      if Inside_A_Generic then
9571         return;
9572      else
9573         Set_Itype (IR, Ityp);
9574         Insert_After (Nod, IR);
9575      end if;
9576   end Build_Itype_Reference;
9577
9578   ------------------------
9579   -- Build_Scalar_Bound --
9580   ------------------------
9581
9582   function Build_Scalar_Bound
9583     (Bound : Node_Id;
9584      Par_T : Entity_Id;
9585      Der_T : Entity_Id) return Node_Id
9586   is
9587      New_Bound : Entity_Id;
9588
9589   begin
9590      --  Note: not clear why this is needed, how can the original bound
9591      --  be unanalyzed at this point? and if it is, what business do we
9592      --  have messing around with it? and why is the base type of the
9593      --  parent type the right type for the resolution. It probably is
9594      --  not. It is OK for the new bound we are creating, but not for
9595      --  the old one??? Still if it never happens, no problem.
9596
9597      Analyze_And_Resolve (Bound, Base_Type (Par_T));
9598
9599      if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
9600         New_Bound := New_Copy (Bound);
9601         Set_Etype (New_Bound, Der_T);
9602         Set_Analyzed (New_Bound);
9603
9604      elsif Is_Entity_Name (Bound) then
9605         New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
9606
9607      --  The following is almost certainly wrong. What business do we have
9608      --  relocating a node (Bound) that is presumably still attached to
9609      --  the tree elsewhere???
9610
9611      else
9612         New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
9613      end if;
9614
9615      Set_Etype (New_Bound, Der_T);
9616      return New_Bound;
9617   end Build_Scalar_Bound;
9618
9619   --------------------------------
9620   -- Build_Underlying_Full_View --
9621   --------------------------------
9622
9623   procedure Build_Underlying_Full_View
9624     (N   : Node_Id;
9625      Typ : Entity_Id;
9626      Par : Entity_Id)
9627   is
9628      Loc  : constant Source_Ptr := Sloc (N);
9629      Subt : constant Entity_Id :=
9630               Make_Defining_Identifier
9631                 (Loc, New_External_Name (Chars (Typ), 'S'));
9632
9633      Constr : Node_Id;
9634      Indic  : Node_Id;
9635      C      : Node_Id;
9636      Id     : Node_Id;
9637
9638      procedure Set_Discriminant_Name (Id : Node_Id);
9639      --  If the derived type has discriminants, they may rename discriminants
9640      --  of the parent. When building the full view of the parent, we need to
9641      --  recover the names of the original discriminants if the constraint is
9642      --  given by named associations.
9643
9644      ---------------------------
9645      -- Set_Discriminant_Name --
9646      ---------------------------
9647
9648      procedure Set_Discriminant_Name (Id : Node_Id) is
9649         Disc : Entity_Id;
9650
9651      begin
9652         Set_Original_Discriminant (Id, Empty);
9653
9654         if Has_Discriminants (Typ) then
9655            Disc := First_Discriminant (Typ);
9656            while Present (Disc) loop
9657               if Chars (Disc) = Chars (Id)
9658                 and then Present (Corresponding_Discriminant (Disc))
9659               then
9660                  Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
9661               end if;
9662               Next_Discriminant (Disc);
9663            end loop;
9664         end if;
9665      end Set_Discriminant_Name;
9666
9667   --  Start of processing for Build_Underlying_Full_View
9668
9669   begin
9670      if Nkind (N) = N_Full_Type_Declaration then
9671         Constr := Constraint (Subtype_Indication (Type_Definition (N)));
9672
9673      elsif Nkind (N) = N_Subtype_Declaration then
9674         Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
9675
9676      elsif Nkind (N) = N_Component_Declaration then
9677         Constr :=
9678           New_Copy_Tree
9679             (Constraint (Subtype_Indication (Component_Definition (N))));
9680
9681      else
9682         raise Program_Error;
9683      end if;
9684
9685      C := First (Constraints (Constr));
9686      while Present (C) loop
9687         if Nkind (C) = N_Discriminant_Association then
9688            Id := First (Selector_Names (C));
9689            while Present (Id) loop
9690               Set_Discriminant_Name (Id);
9691               Next (Id);
9692            end loop;
9693         end if;
9694
9695         Next (C);
9696      end loop;
9697
9698      Indic :=
9699        Make_Subtype_Declaration (Loc,
9700          Defining_Identifier => Subt,
9701          Subtype_Indication  =>
9702            Make_Subtype_Indication (Loc,
9703              Subtype_Mark => New_Occurrence_Of (Par, Loc),
9704              Constraint   => New_Copy_Tree (Constr)));
9705
9706      --  If this is a component subtype for an outer itype, it is not
9707      --  a list member, so simply set the parent link for analysis: if
9708      --  the enclosing type does not need to be in a declarative list,
9709      --  neither do the components.
9710
9711      if Is_List_Member (N)
9712        and then Nkind (N) /= N_Component_Declaration
9713      then
9714         Insert_Before (N, Indic);
9715      else
9716         Set_Parent (Indic, Parent (N));
9717      end if;
9718
9719      Analyze (Indic);
9720      Set_Underlying_Full_View (Typ, Full_View (Subt));
9721   end Build_Underlying_Full_View;
9722
9723   -------------------------------
9724   -- Check_Abstract_Overriding --
9725   -------------------------------
9726
9727   procedure Check_Abstract_Overriding (T : Entity_Id) is
9728      Alias_Subp : Entity_Id;
9729      Elmt       : Elmt_Id;
9730      Op_List    : Elist_Id;
9731      Subp       : Entity_Id;
9732      Type_Def   : Node_Id;
9733
9734      procedure Check_Pragma_Implemented (Subp : Entity_Id);
9735      --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
9736      --  which has pragma Implemented already set. Check whether Subp's entity
9737      --  kind conforms to the implementation kind of the overridden routine.
9738
9739      procedure Check_Pragma_Implemented
9740        (Subp       : Entity_Id;
9741         Iface_Subp : Entity_Id);
9742      --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
9743      --  Iface_Subp and both entities have pragma Implemented already set on
9744      --  them. Check whether the two implementation kinds are conforming.
9745
9746      procedure Inherit_Pragma_Implemented
9747        (Subp       : Entity_Id;
9748         Iface_Subp : Entity_Id);
9749      --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
9750      --  subprogram Iface_Subp which has been marked by pragma Implemented.
9751      --  Propagate the implementation kind of Iface_Subp to Subp.
9752
9753      ------------------------------
9754      -- Check_Pragma_Implemented --
9755      ------------------------------
9756
9757      procedure Check_Pragma_Implemented (Subp : Entity_Id) is
9758         Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
9759         Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
9760         Subp_Alias  : constant Entity_Id := Alias (Subp);
9761         Contr_Typ   : Entity_Id;
9762         Impl_Subp   : Entity_Id;
9763
9764      begin
9765         --  Subp must have an alias since it is a hidden entity used to link
9766         --  an interface subprogram to its overriding counterpart.
9767
9768         pragma Assert (Present (Subp_Alias));
9769
9770         --  Handle aliases to synchronized wrappers
9771
9772         Impl_Subp := Subp_Alias;
9773
9774         if Is_Primitive_Wrapper (Impl_Subp) then
9775            Impl_Subp := Wrapped_Entity (Impl_Subp);
9776         end if;
9777
9778         --  Extract the type of the controlling formal
9779
9780         Contr_Typ := Etype (First_Formal (Subp_Alias));
9781
9782         if Is_Concurrent_Record_Type (Contr_Typ) then
9783            Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
9784         end if;
9785
9786         --  An interface subprogram whose implementation kind is By_Entry must
9787         --  be implemented by an entry.
9788
9789         if Impl_Kind = Name_By_Entry
9790           and then Ekind (Impl_Subp) /= E_Entry
9791         then
9792            Error_Msg_Node_2 := Iface_Alias;
9793            Error_Msg_NE
9794              ("type & must implement abstract subprogram & with an entry",
9795               Subp_Alias, Contr_Typ);
9796
9797         elsif Impl_Kind = Name_By_Protected_Procedure then
9798
9799            --  An interface subprogram whose implementation kind is By_
9800            --  Protected_Procedure cannot be implemented by a primitive
9801            --  procedure of a task type.
9802
9803            if Ekind (Contr_Typ) /= E_Protected_Type then
9804               Error_Msg_Node_2 := Contr_Typ;
9805               Error_Msg_NE
9806                 ("interface subprogram & cannot be implemented by a " &
9807                  "primitive procedure of task type &", Subp_Alias,
9808                  Iface_Alias);
9809
9810            --  An interface subprogram whose implementation kind is By_
9811            --  Protected_Procedure must be implemented by a procedure.
9812
9813            elsif Ekind (Impl_Subp) /= E_Procedure then
9814               Error_Msg_Node_2 := Iface_Alias;
9815               Error_Msg_NE
9816                 ("type & must implement abstract subprogram & with a " &
9817                  "procedure", Subp_Alias, Contr_Typ);
9818
9819            elsif Present (Get_Rep_Pragma (Impl_Subp, Name_Implemented))
9820              and then Implementation_Kind (Impl_Subp) /= Impl_Kind
9821            then
9822               Error_Msg_Name_1 := Impl_Kind;
9823               Error_Msg_N
9824                ("overriding operation& must have synchronization%",
9825                 Subp_Alias);
9826            end if;
9827
9828         --  If primitive has Optional synchronization, overriding operation
9829         --  must match if it has an explicit synchronization..
9830
9831         elsif Present (Get_Rep_Pragma (Impl_Subp, Name_Implemented))
9832           and then Implementation_Kind (Impl_Subp) /= Impl_Kind
9833         then
9834               Error_Msg_Name_1 := Impl_Kind;
9835               Error_Msg_N
9836                ("overriding operation& must have syncrhonization%",
9837                 Subp_Alias);
9838         end if;
9839      end Check_Pragma_Implemented;
9840
9841      ------------------------------
9842      -- Check_Pragma_Implemented --
9843      ------------------------------
9844
9845      procedure Check_Pragma_Implemented
9846        (Subp       : Entity_Id;
9847         Iface_Subp : Entity_Id)
9848      is
9849         Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
9850         Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
9851
9852      begin
9853         --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
9854         --  and overriding subprogram are different. In general this is an
9855         --  error except when the implementation kind of the overridden
9856         --  subprograms is By_Any or Optional.
9857
9858         if Iface_Kind /= Subp_Kind
9859           and then Iface_Kind /= Name_By_Any
9860           and then Iface_Kind /= Name_Optional
9861         then
9862            if Iface_Kind = Name_By_Entry then
9863               Error_Msg_N
9864                 ("incompatible implementation kind, overridden subprogram " &
9865                  "is marked By_Entry", Subp);
9866            else
9867               Error_Msg_N
9868                 ("incompatible implementation kind, overridden subprogram " &
9869                  "is marked By_Protected_Procedure", Subp);
9870            end if;
9871         end if;
9872      end Check_Pragma_Implemented;
9873
9874      --------------------------------
9875      -- Inherit_Pragma_Implemented --
9876      --------------------------------
9877
9878      procedure Inherit_Pragma_Implemented
9879        (Subp       : Entity_Id;
9880         Iface_Subp : Entity_Id)
9881      is
9882         Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
9883         Loc        : constant Source_Ptr := Sloc (Subp);
9884         Impl_Prag  : Node_Id;
9885
9886      begin
9887         --  Since the implementation kind is stored as a representation item
9888         --  rather than a flag, create a pragma node.
9889
9890         Impl_Prag :=
9891           Make_Pragma (Loc,
9892             Chars                        => Name_Implemented,
9893             Pragma_Argument_Associations => New_List (
9894               Make_Pragma_Argument_Association (Loc,
9895                 Expression => New_Occurrence_Of (Subp, Loc)),
9896
9897               Make_Pragma_Argument_Association (Loc,
9898                 Expression => Make_Identifier (Loc, Iface_Kind))));
9899
9900         --  The pragma doesn't need to be analyzed because it is internally
9901         --  built. It is safe to directly register it as a rep item since we
9902         --  are only interested in the characters of the implementation kind.
9903
9904         Record_Rep_Item (Subp, Impl_Prag);
9905      end Inherit_Pragma_Implemented;
9906
9907   --  Start of processing for Check_Abstract_Overriding
9908
9909   begin
9910      Op_List := Primitive_Operations (T);
9911
9912      --  Loop to check primitive operations
9913
9914      Elmt := First_Elmt (Op_List);
9915      while Present (Elmt) loop
9916         Subp := Node (Elmt);
9917         Alias_Subp := Alias (Subp);
9918
9919         --  Inherited subprograms are identified by the fact that they do not
9920         --  come from source, and the associated source location is the
9921         --  location of the first subtype of the derived type.
9922
9923         --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
9924         --  subprograms that "require overriding".
9925
9926         --  Special exception, do not complain about failure to override the
9927         --  stream routines _Input and _Output, as well as the primitive
9928         --  operations used in dispatching selects since we always provide
9929         --  automatic overridings for these subprograms.
9930
9931         --  Also ignore this rule for convention CIL since .NET libraries
9932         --  do bizarre things with interfaces???
9933
9934         --  The partial view of T may have been a private extension, for
9935         --  which inherited functions dispatching on result are abstract.
9936         --  If the full view is a null extension, there is no need for
9937         --  overriding in Ada 2005, but wrappers need to be built for them
9938         --  (see exp_ch3, Build_Controlling_Function_Wrappers).
9939
9940         if Is_Null_Extension (T)
9941           and then Has_Controlling_Result (Subp)
9942           and then Ada_Version >= Ada_2005
9943           and then Present (Alias_Subp)
9944           and then not Comes_From_Source (Subp)
9945           and then not Is_Abstract_Subprogram (Alias_Subp)
9946           and then not Is_Access_Type (Etype (Subp))
9947         then
9948            null;
9949
9950         --  Ada 2005 (AI-251): Internal entities of interfaces need no
9951         --  processing because this check is done with the aliased
9952         --  entity
9953
9954         elsif Present (Interface_Alias (Subp)) then
9955            null;
9956
9957         elsif (Is_Abstract_Subprogram (Subp)
9958                 or else Requires_Overriding (Subp)
9959                 or else
9960                   (Has_Controlling_Result (Subp)
9961                     and then Present (Alias_Subp)
9962                     and then not Comes_From_Source (Subp)
9963                     and then Sloc (Subp) = Sloc (First_Subtype (T))))
9964           and then not Is_TSS (Subp, TSS_Stream_Input)
9965           and then not Is_TSS (Subp, TSS_Stream_Output)
9966           and then not Is_Abstract_Type (T)
9967           and then Convention (T) /= Convention_CIL
9968           and then not Is_Predefined_Interface_Primitive (Subp)
9969
9970            --  Ada 2005 (AI-251): Do not consider hidden entities associated
9971            --  with abstract interface types because the check will be done
9972            --  with the aliased entity (otherwise we generate a duplicated
9973            --  error message).
9974
9975           and then not Present (Interface_Alias (Subp))
9976         then
9977            if Present (Alias_Subp) then
9978
9979               --  Only perform the check for a derived subprogram when the
9980               --  type has an explicit record extension. This avoids incorrect
9981               --  flagging of abstract subprograms for the case of a type
9982               --  without an extension that is derived from a formal type
9983               --  with a tagged actual (can occur within a private part).
9984
9985               --  Ada 2005 (AI-391): In the case of an inherited function with
9986               --  a controlling result of the type, the rule does not apply if
9987               --  the type is a null extension (unless the parent function
9988               --  itself is abstract, in which case the function must still be
9989               --  be overridden). The expander will generate an overriding
9990               --  wrapper function calling the parent subprogram (see
9991               --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
9992
9993               Type_Def := Type_Definition (Parent (T));
9994
9995               if Nkind (Type_Def) = N_Derived_Type_Definition
9996                 and then Present (Record_Extension_Part (Type_Def))
9997                 and then
9998                   (Ada_Version < Ada_2005
9999                      or else not Is_Null_Extension (T)
10000                      or else Ekind (Subp) = E_Procedure
10001                      or else not Has_Controlling_Result (Subp)
10002                      or else Is_Abstract_Subprogram (Alias_Subp)
10003                      or else Requires_Overriding (Subp)
10004                      or else Is_Access_Type (Etype (Subp)))
10005               then
10006                  --  Avoid reporting error in case of abstract predefined
10007                  --  primitive inherited from interface type because the
10008                  --  body of internally generated predefined primitives
10009                  --  of tagged types are generated later by Freeze_Type
10010
10011                  if Is_Interface (Root_Type (T))
10012                    and then Is_Abstract_Subprogram (Subp)
10013                    and then Is_Predefined_Dispatching_Operation (Subp)
10014                    and then not Comes_From_Source (Ultimate_Alias (Subp))
10015                  then
10016                     null;
10017
10018                  --  A null extension is not obliged to override an inherited
10019                  --  procedure subject to pragma Extensions_Visible with value
10020                  --  False and at least one controlling OUT parameter
10021                  --  (SPARK RM 6.1.7(6)).
10022
10023                  elsif Is_Null_Extension (T)
10024                    and then Is_EVF_Procedure (Subp)
10025                  then
10026                     null;
10027
10028                  else
10029                     Error_Msg_NE
10030                       ("type must be declared abstract or & overridden",
10031                        T, Subp);
10032
10033                     --  Traverse the whole chain of aliased subprograms to
10034                     --  complete the error notification. This is especially
10035                     --  useful for traceability of the chain of entities when
10036                     --  the subprogram corresponds with an interface
10037                     --  subprogram (which may be defined in another package).
10038
10039                     if Present (Alias_Subp) then
10040                        declare
10041                           E : Entity_Id;
10042
10043                        begin
10044                           E := Subp;
10045                           while Present (Alias (E)) loop
10046
10047                              --  Avoid reporting redundant errors on entities
10048                              --  inherited from interfaces
10049
10050                              if Sloc (E) /= Sloc (T) then
10051                                 Error_Msg_Sloc := Sloc (E);
10052                                 Error_Msg_NE
10053                                   ("\& has been inherited #", T, Subp);
10054                              end if;
10055
10056                              E := Alias (E);
10057                           end loop;
10058
10059                           Error_Msg_Sloc := Sloc (E);
10060
10061                           --  AI05-0068: report if there is an overriding
10062                           --  non-abstract subprogram that is invisible.
10063
10064                           if Is_Hidden (E)
10065                             and then not Is_Abstract_Subprogram (E)
10066                           then
10067                              Error_Msg_NE
10068                                ("\& subprogram# is not visible",
10069                                 T, Subp);
10070
10071                           --  Clarify the case where a non-null extension must
10072                           --  override inherited procedure subject to pragma
10073                           --  Extensions_Visible with value False and at least
10074                           --  one controlling OUT param.
10075
10076                           elsif Is_EVF_Procedure (E) then
10077                              Error_Msg_NE
10078                                ("\& # is subject to Extensions_Visible False",
10079                                 T, Subp);
10080
10081                           else
10082                              Error_Msg_NE
10083                                ("\& has been inherited from subprogram #",
10084                                 T, Subp);
10085                           end if;
10086                        end;
10087                     end if;
10088                  end if;
10089
10090               --  Ada 2005 (AI-345): Protected or task type implementing
10091               --  abstract interfaces.
10092
10093               elsif Is_Concurrent_Record_Type (T)
10094                 and then Present (Interfaces (T))
10095               then
10096                  --  There is no need to check here RM 9.4(11.9/3) since we
10097                  --  are processing the corresponding record type and the
10098                  --  mode of the overriding subprograms was verified by
10099                  --  Check_Conformance when the corresponding concurrent
10100                  --  type declaration was analyzed.
10101
10102                  Error_Msg_NE
10103                    ("interface subprogram & must be overridden", T, Subp);
10104
10105                  --  Examine primitive operations of synchronized type to find
10106                  --  homonyms that have the wrong profile.
10107
10108                  declare
10109                     Prim : Entity_Id;
10110
10111                  begin
10112                     Prim := First_Entity (Corresponding_Concurrent_Type (T));
10113                     while Present (Prim) loop
10114                        if Chars (Prim) = Chars (Subp) then
10115                           Error_Msg_NE
10116                             ("profile is not type conformant with prefixed "
10117                              & "view profile of inherited operation&",
10118                              Prim, Subp);
10119                        end if;
10120
10121                        Next_Entity (Prim);
10122                     end loop;
10123                  end;
10124               end if;
10125
10126            else
10127               Error_Msg_Node_2 := T;
10128               Error_Msg_N
10129                 ("abstract subprogram& not allowed for type&", Subp);
10130
10131               --  Also post unconditional warning on the type (unconditional
10132               --  so that if there are more than one of these cases, we get
10133               --  them all, and not just the first one).
10134
10135               Error_Msg_Node_2 := Subp;
10136               Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
10137            end if;
10138
10139         --  A subprogram subject to pragma Extensions_Visible with value
10140         --  "True" cannot override a subprogram subject to the same pragma
10141         --  with value "False" (SPARK RM 6.1.7(5)).
10142
10143         elsif Extensions_Visible_Status (Subp) = Extensions_Visible_True
10144           and then Present (Overridden_Operation (Subp))
10145           and then Extensions_Visible_Status (Overridden_Operation (Subp)) =
10146                    Extensions_Visible_False
10147         then
10148            Error_Msg_Sloc := Sloc (Overridden_Operation (Subp));
10149            Error_Msg_N
10150              ("subprogram & with Extensions_Visible True cannot override "
10151               & "subprogram # with Extensions_Visible False", Subp);
10152         end if;
10153
10154         --  Ada 2012 (AI05-0030): Perform checks related to pragma Implemented
10155
10156         --  Subp is an expander-generated procedure which maps an interface
10157         --  alias to a protected wrapper. The interface alias is flagged by
10158         --  pragma Implemented. Ensure that Subp is a procedure when the
10159         --  implementation kind is By_Protected_Procedure or an entry when
10160         --  By_Entry.
10161
10162         if Ada_Version >= Ada_2012
10163           and then Is_Hidden (Subp)
10164           and then Present (Interface_Alias (Subp))
10165           and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
10166         then
10167            Check_Pragma_Implemented (Subp);
10168         end if;
10169
10170         --  Subp is an interface primitive which overrides another interface
10171         --  primitive marked with pragma Implemented.
10172
10173         if Ada_Version >= Ada_2012
10174           and then Present (Overridden_Operation (Subp))
10175           and then Has_Rep_Pragma
10176                      (Overridden_Operation (Subp), Name_Implemented)
10177         then
10178            --  If the overriding routine is also marked by Implemented, check
10179            --  that the two implementation kinds are conforming.
10180
10181            if Has_Rep_Pragma (Subp, Name_Implemented) then
10182               Check_Pragma_Implemented
10183                 (Subp       => Subp,
10184                  Iface_Subp => Overridden_Operation (Subp));
10185
10186            --  Otherwise the overriding routine inherits the implementation
10187            --  kind from the overridden subprogram.
10188
10189            else
10190               Inherit_Pragma_Implemented
10191                 (Subp       => Subp,
10192                  Iface_Subp => Overridden_Operation (Subp));
10193            end if;
10194         end if;
10195
10196         --  If the operation is a wrapper for a synchronized primitive, it
10197         --  may be called indirectly through a dispatching select. We assume
10198         --  that it will be referenced elsewhere indirectly, and suppress
10199         --  warnings about an unused entity.
10200
10201         if Is_Primitive_Wrapper (Subp)
10202           and then Present (Wrapped_Entity (Subp))
10203         then
10204            Set_Referenced (Wrapped_Entity (Subp));
10205         end if;
10206
10207         Next_Elmt (Elmt);
10208      end loop;
10209   end Check_Abstract_Overriding;
10210
10211   ------------------------------------------------
10212   -- Check_Access_Discriminant_Requires_Limited --
10213   ------------------------------------------------
10214
10215   procedure Check_Access_Discriminant_Requires_Limited
10216     (D   : Node_Id;
10217      Loc : Node_Id)
10218   is
10219   begin
10220      --  A discriminant_specification for an access discriminant shall appear
10221      --  only in the declaration for a task or protected type, or for a type
10222      --  with the reserved word 'limited' in its definition or in one of its
10223      --  ancestors (RM 3.7(10)).
10224
10225      --  AI-0063: The proper condition is that type must be immutably limited,
10226      --  or else be a partial view.
10227
10228      if Nkind (Discriminant_Type (D)) = N_Access_Definition then
10229         if Is_Limited_View (Current_Scope)
10230           or else
10231             (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
10232               and then Limited_Present (Parent (Current_Scope)))
10233         then
10234            null;
10235
10236         else
10237            Error_Msg_N
10238              ("access discriminants allowed only for limited types", Loc);
10239         end if;
10240      end if;
10241   end Check_Access_Discriminant_Requires_Limited;
10242
10243   -----------------------------------
10244   -- Check_Aliased_Component_Types --
10245   -----------------------------------
10246
10247   procedure Check_Aliased_Component_Types (T : Entity_Id) is
10248      C : Entity_Id;
10249
10250   begin
10251      --  ??? Also need to check components of record extensions, but not
10252      --  components of protected types (which are always limited).
10253
10254      --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
10255      --  types to be unconstrained. This is safe because it is illegal to
10256      --  create access subtypes to such types with explicit discriminant
10257      --  constraints.
10258
10259      if not Is_Limited_Type (T) then
10260         if Ekind (T) = E_Record_Type then
10261            C := First_Component (T);
10262            while Present (C) loop
10263               if Is_Aliased (C)
10264                 and then Has_Discriminants (Etype (C))
10265                 and then not Is_Constrained (Etype (C))
10266                 and then not In_Instance_Body
10267                 and then Ada_Version < Ada_2005
10268               then
10269                  Error_Msg_N
10270                    ("aliased component must be constrained (RM 3.6(11))",
10271                      C);
10272               end if;
10273
10274               Next_Component (C);
10275            end loop;
10276
10277         elsif Ekind (T) = E_Array_Type then
10278            if Has_Aliased_Components (T)
10279              and then Has_Discriminants (Component_Type (T))
10280              and then not Is_Constrained (Component_Type (T))
10281              and then not In_Instance_Body
10282              and then Ada_Version < Ada_2005
10283            then
10284               Error_Msg_N
10285                 ("aliased component type must be constrained (RM 3.6(11))",
10286                    T);
10287            end if;
10288         end if;
10289      end if;
10290   end Check_Aliased_Component_Types;
10291
10292   ---------------------------------------
10293   -- Check_Anonymous_Access_Components --
10294   ---------------------------------------
10295
10296   procedure Check_Anonymous_Access_Components
10297      (Typ_Decl  : Node_Id;
10298       Typ       : Entity_Id;
10299       Prev      : Entity_Id;
10300       Comp_List : Node_Id)
10301   is
10302      Loc         : constant Source_Ptr := Sloc (Typ_Decl);
10303      Anon_Access : Entity_Id;
10304      Acc_Def     : Node_Id;
10305      Comp        : Node_Id;
10306      Comp_Def    : Node_Id;
10307      Decl        : Node_Id;
10308      Type_Def    : Node_Id;
10309
10310      procedure Build_Incomplete_Type_Declaration;
10311      --  If the record type contains components that include an access to the
10312      --  current record, then create an incomplete type declaration for the
10313      --  record, to be used as the designated type of the anonymous access.
10314      --  This is done only once, and only if there is no previous partial
10315      --  view of the type.
10316
10317      function Designates_T (Subt : Node_Id) return Boolean;
10318      --  Check whether a node designates the enclosing record type, or 'Class
10319      --  of that type
10320
10321      function Mentions_T (Acc_Def : Node_Id) return Boolean;
10322      --  Check whether an access definition includes a reference to
10323      --  the enclosing record type. The reference can be a subtype mark
10324      --  in the access definition itself, a 'Class attribute reference, or
10325      --  recursively a reference appearing in a parameter specification
10326      --  or result definition of an access_to_subprogram definition.
10327
10328      --------------------------------------
10329      -- Build_Incomplete_Type_Declaration --
10330      --------------------------------------
10331
10332      procedure Build_Incomplete_Type_Declaration is
10333         Decl  : Node_Id;
10334         Inc_T : Entity_Id;
10335         H     : Entity_Id;
10336
10337         --  Is_Tagged indicates whether the type is tagged. It is tagged if
10338         --  it's "is new ... with record" or else "is tagged record ...".
10339
10340         Is_Tagged : constant Boolean :=
10341             (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
10342               and then
10343                 Present (Record_Extension_Part (Type_Definition (Typ_Decl))))
10344           or else
10345             (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
10346               and then Tagged_Present (Type_Definition (Typ_Decl)));
10347
10348      begin
10349         --  If there is a previous partial view, no need to create a new one
10350         --  If the partial view, given by Prev, is incomplete,  If Prev is
10351         --  a private declaration, full declaration is flagged accordingly.
10352
10353         if Prev /= Typ then
10354            if Is_Tagged then
10355               Make_Class_Wide_Type (Prev);
10356               Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
10357               Set_Etype (Class_Wide_Type (Typ), Typ);
10358            end if;
10359
10360            return;
10361
10362         elsif Has_Private_Declaration (Typ) then
10363
10364            --  If we refer to T'Class inside T, and T is the completion of a
10365            --  private type, then make sure the class-wide type exists.
10366
10367            if Is_Tagged then
10368               Make_Class_Wide_Type (Typ);
10369            end if;
10370
10371            return;
10372
10373         --  If there was a previous anonymous access type, the incomplete
10374         --  type declaration will have been created already.
10375
10376         elsif Present (Current_Entity (Typ))
10377           and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
10378           and then Full_View (Current_Entity (Typ)) = Typ
10379         then
10380            if Is_Tagged
10381              and then Comes_From_Source (Current_Entity (Typ))
10382              and then not Is_Tagged_Type (Current_Entity (Typ))
10383            then
10384               Make_Class_Wide_Type (Typ);
10385               Error_Msg_N
10386                 ("incomplete view of tagged type should be declared tagged??",
10387                  Parent (Current_Entity (Typ)));
10388            end if;
10389            return;
10390
10391         else
10392            Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
10393            Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
10394
10395            --  Type has already been inserted into the current scope. Remove
10396            --  it, and add incomplete declaration for type, so that subsequent
10397            --  anonymous access types can use it. The entity is unchained from
10398            --  the homonym list and from immediate visibility. After analysis,
10399            --  the entity in the incomplete declaration becomes immediately
10400            --  visible in the record declaration that follows.
10401
10402            H := Current_Entity (Typ);
10403
10404            if H = Typ then
10405               Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
10406            else
10407               while Present (H)
10408                 and then Homonym (H) /= Typ
10409               loop
10410                  H := Homonym (Typ);
10411               end loop;
10412
10413               Set_Homonym (H, Homonym (Typ));
10414            end if;
10415
10416            Insert_Before (Typ_Decl, Decl);
10417            Analyze (Decl);
10418            Set_Full_View (Inc_T, Typ);
10419
10420            if Is_Tagged then
10421
10422               --  Create a common class-wide type for both views, and set the
10423               --  Etype of the class-wide type to the full view.
10424
10425               Make_Class_Wide_Type (Inc_T);
10426               Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
10427               Set_Etype (Class_Wide_Type (Typ), Typ);
10428            end if;
10429         end if;
10430      end Build_Incomplete_Type_Declaration;
10431
10432      ------------------
10433      -- Designates_T --
10434      ------------------
10435
10436      function Designates_T (Subt : Node_Id) return Boolean is
10437         Type_Id : constant Name_Id := Chars (Typ);
10438
10439         function Names_T (Nam : Node_Id) return Boolean;
10440         --  The record type has not been introduced in the current scope
10441         --  yet, so we must examine the name of the type itself, either
10442         --  an identifier T, or an expanded name of the form P.T, where
10443         --  P denotes the current scope.
10444
10445         -------------
10446         -- Names_T --
10447         -------------
10448
10449         function Names_T (Nam : Node_Id) return Boolean is
10450         begin
10451            if Nkind (Nam) = N_Identifier then
10452               return Chars (Nam) = Type_Id;
10453
10454            elsif Nkind (Nam) = N_Selected_Component then
10455               if Chars (Selector_Name (Nam)) = Type_Id then
10456                  if Nkind (Prefix (Nam)) = N_Identifier then
10457                     return Chars (Prefix (Nam)) = Chars (Current_Scope);
10458
10459                  elsif Nkind (Prefix (Nam)) = N_Selected_Component then
10460                     return Chars (Selector_Name (Prefix (Nam))) =
10461                            Chars (Current_Scope);
10462                  else
10463                     return False;
10464                  end if;
10465
10466               else
10467                  return False;
10468               end if;
10469
10470            else
10471               return False;
10472            end if;
10473         end Names_T;
10474
10475      --  Start of processing for Designates_T
10476
10477      begin
10478         if Nkind (Subt) = N_Identifier then
10479            return Chars (Subt) = Type_Id;
10480
10481            --  Reference can be through an expanded name which has not been
10482            --  analyzed yet, and which designates enclosing scopes.
10483
10484         elsif Nkind (Subt) = N_Selected_Component then
10485            if Names_T (Subt) then
10486               return True;
10487
10488            --  Otherwise it must denote an entity that is already visible.
10489            --  The access definition may name a subtype of the enclosing
10490            --  type, if there is a previous incomplete declaration for it.
10491
10492            else
10493               Find_Selected_Component (Subt);
10494               return
10495                 Is_Entity_Name (Subt)
10496                   and then Scope (Entity (Subt)) = Current_Scope
10497                   and then
10498                     (Chars (Base_Type (Entity (Subt))) = Type_Id
10499                       or else
10500                         (Is_Class_Wide_Type (Entity (Subt))
10501                           and then
10502                             Chars (Etype (Base_Type (Entity (Subt)))) =
10503                                                                  Type_Id));
10504            end if;
10505
10506         --  A reference to the current type may appear as the prefix of
10507         --  a 'Class attribute.
10508
10509         elsif Nkind (Subt) = N_Attribute_Reference
10510           and then Attribute_Name (Subt) = Name_Class
10511         then
10512            return Names_T (Prefix (Subt));
10513
10514         else
10515            return False;
10516         end if;
10517      end Designates_T;
10518
10519      ----------------
10520      -- Mentions_T --
10521      ----------------
10522
10523      function Mentions_T (Acc_Def : Node_Id) return Boolean is
10524         Param_Spec : Node_Id;
10525
10526         Acc_Subprg : constant Node_Id :=
10527                        Access_To_Subprogram_Definition (Acc_Def);
10528
10529      begin
10530         if No (Acc_Subprg) then
10531            return Designates_T (Subtype_Mark (Acc_Def));
10532         end if;
10533
10534         --  Component is an access_to_subprogram: examine its formals,
10535         --  and result definition in the case of an access_to_function.
10536
10537         Param_Spec := First (Parameter_Specifications (Acc_Subprg));
10538         while Present (Param_Spec) loop
10539            if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
10540              and then Mentions_T (Parameter_Type (Param_Spec))
10541            then
10542               return True;
10543
10544            elsif Designates_T (Parameter_Type (Param_Spec)) then
10545               return True;
10546            end if;
10547
10548            Next (Param_Spec);
10549         end loop;
10550
10551         if Nkind (Acc_Subprg) = N_Access_Function_Definition then
10552            if Nkind (Result_Definition (Acc_Subprg)) =
10553                 N_Access_Definition
10554            then
10555               return Mentions_T (Result_Definition (Acc_Subprg));
10556            else
10557               return Designates_T (Result_Definition (Acc_Subprg));
10558            end if;
10559         end if;
10560
10561         return False;
10562      end Mentions_T;
10563
10564   --  Start of processing for Check_Anonymous_Access_Components
10565
10566   begin
10567      if No (Comp_List) then
10568         return;
10569      end if;
10570
10571      Comp := First (Component_Items (Comp_List));
10572      while Present (Comp) loop
10573         if Nkind (Comp) = N_Component_Declaration
10574           and then Present
10575             (Access_Definition (Component_Definition (Comp)))
10576           and then
10577             Mentions_T (Access_Definition (Component_Definition (Comp)))
10578         then
10579            Comp_Def := Component_Definition (Comp);
10580            Acc_Def :=
10581              Access_To_Subprogram_Definition (Access_Definition (Comp_Def));
10582
10583            Build_Incomplete_Type_Declaration;
10584            Anon_Access := Make_Temporary (Loc, 'S');
10585
10586            --  Create a declaration for the anonymous access type: either
10587            --  an access_to_object or an access_to_subprogram.
10588
10589            if Present (Acc_Def) then
10590               if Nkind (Acc_Def) = N_Access_Function_Definition then
10591                  Type_Def :=
10592                    Make_Access_Function_Definition (Loc,
10593                      Parameter_Specifications =>
10594                        Parameter_Specifications (Acc_Def),
10595                      Result_Definition        => Result_Definition (Acc_Def));
10596               else
10597                  Type_Def :=
10598                    Make_Access_Procedure_Definition (Loc,
10599                      Parameter_Specifications =>
10600                        Parameter_Specifications (Acc_Def));
10601               end if;
10602
10603            else
10604               Type_Def :=
10605                 Make_Access_To_Object_Definition (Loc,
10606                   Subtype_Indication =>
10607                      Relocate_Node
10608                        (Subtype_Mark (Access_Definition (Comp_Def))));
10609
10610               Set_Constant_Present
10611                 (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
10612               Set_All_Present
10613                 (Type_Def, All_Present (Access_Definition (Comp_Def)));
10614            end if;
10615
10616            Set_Null_Exclusion_Present
10617              (Type_Def,
10618               Null_Exclusion_Present (Access_Definition (Comp_Def)));
10619
10620            Decl :=
10621              Make_Full_Type_Declaration (Loc,
10622                Defining_Identifier => Anon_Access,
10623                Type_Definition     => Type_Def);
10624
10625            Insert_Before (Typ_Decl, Decl);
10626            Analyze (Decl);
10627
10628            --  If an access to subprogram, create the extra formals
10629
10630            if Present (Acc_Def) then
10631               Create_Extra_Formals (Designated_Type (Anon_Access));
10632
10633            --  If an access to object, preserve entity of designated type,
10634            --  for ASIS use, before rewriting the component definition.
10635
10636            else
10637               declare
10638                  Desig : Entity_Id;
10639
10640               begin
10641                  Desig := Entity (Subtype_Indication (Type_Def));
10642
10643                  --  If the access definition is to the current  record,
10644                  --  the visible entity at this point is an  incomplete
10645                  --  type. Retrieve the full view to simplify  ASIS queries
10646
10647                  if Ekind (Desig) = E_Incomplete_Type then
10648                     Desig := Full_View (Desig);
10649                  end if;
10650
10651                  Set_Entity
10652                    (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
10653               end;
10654            end if;
10655
10656            Rewrite (Comp_Def,
10657              Make_Component_Definition (Loc,
10658                Subtype_Indication =>
10659               New_Occurrence_Of (Anon_Access, Loc)));
10660
10661            if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
10662               Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
10663            else
10664               Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
10665            end if;
10666
10667            Set_Is_Local_Anonymous_Access (Anon_Access);
10668         end if;
10669
10670         Next (Comp);
10671      end loop;
10672
10673      if Present (Variant_Part (Comp_List)) then
10674         declare
10675            V : Node_Id;
10676         begin
10677            V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
10678            while Present (V) loop
10679               Check_Anonymous_Access_Components
10680                 (Typ_Decl, Typ, Prev, Component_List (V));
10681               Next_Non_Pragma (V);
10682            end loop;
10683         end;
10684      end if;
10685   end Check_Anonymous_Access_Components;
10686
10687   ----------------------
10688   -- Check_Completion --
10689   ----------------------
10690
10691   procedure Check_Completion (Body_Id : Node_Id := Empty) is
10692      E : Entity_Id;
10693
10694      procedure Post_Error;
10695      --  Post error message for lack of completion for entity E
10696
10697      ----------------
10698      -- Post_Error --
10699      ----------------
10700
10701      procedure Post_Error is
10702
10703         procedure Missing_Body;
10704         --  Output missing body message
10705
10706         ------------------
10707         -- Missing_Body --
10708         ------------------
10709
10710         procedure Missing_Body is
10711         begin
10712            --  Spec is in same unit, so we can post on spec
10713
10714            if In_Same_Source_Unit (Body_Id, E) then
10715               Error_Msg_N ("missing body for &", E);
10716
10717            --  Spec is in a separate unit, so we have to post on the body
10718
10719            else
10720               Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
10721            end if;
10722         end Missing_Body;
10723
10724      --  Start of processing for Post_Error
10725
10726      begin
10727         if not Comes_From_Source (E) then
10728
10729            if Ekind_In (E, E_Task_Type, E_Protected_Type) then
10730
10731               --  It may be an anonymous protected type created for a
10732               --  single variable. Post error on variable, if present.
10733
10734               declare
10735                  Var : Entity_Id;
10736
10737               begin
10738                  Var := First_Entity (Current_Scope);
10739                  while Present (Var) loop
10740                     exit when Etype (Var) = E
10741                       and then Comes_From_Source (Var);
10742
10743                     Next_Entity (Var);
10744                  end loop;
10745
10746                  if Present (Var) then
10747                     E := Var;
10748                  end if;
10749               end;
10750            end if;
10751         end if;
10752
10753         --  If a generated entity has no completion, then either previous
10754         --  semantic errors have disabled the expansion phase, or else we had
10755         --  missing subunits, or else we are compiling without expansion,
10756         --  or else something is very wrong.
10757
10758         if not Comes_From_Source (E) then
10759            pragma Assert
10760              (Serious_Errors_Detected > 0
10761                or else Configurable_Run_Time_Violations > 0
10762                or else Subunits_Missing
10763                or else not Expander_Active);
10764            return;
10765
10766         --  Here for source entity
10767
10768         else
10769            --  Here if no body to post the error message, so we post the error
10770            --  on the declaration that has no completion. This is not really
10771            --  the right place to post it, think about this later ???
10772
10773            if No (Body_Id) then
10774               if Is_Type (E) then
10775                  Error_Msg_NE
10776                    ("missing full declaration for }", Parent (E), E);
10777               else
10778                  Error_Msg_NE ("missing body for &", Parent (E), E);
10779               end if;
10780
10781            --  Package body has no completion for a declaration that appears
10782            --  in the corresponding spec. Post error on the body, with a
10783            --  reference to the non-completed declaration.
10784
10785            else
10786               Error_Msg_Sloc := Sloc (E);
10787
10788               if Is_Type (E) then
10789                  Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
10790
10791               elsif Is_Overloadable (E)
10792                 and then Current_Entity_In_Scope (E) /= E
10793               then
10794                  --  It may be that the completion is mistyped and appears as
10795                  --  a distinct overloading of the entity.
10796
10797                  declare
10798                     Candidate : constant Entity_Id :=
10799                                   Current_Entity_In_Scope (E);
10800                     Decl      : constant Node_Id :=
10801                                   Unit_Declaration_Node (Candidate);
10802
10803                  begin
10804                     if Is_Overloadable (Candidate)
10805                       and then Ekind (Candidate) = Ekind (E)
10806                       and then Nkind (Decl) = N_Subprogram_Body
10807                       and then Acts_As_Spec (Decl)
10808                     then
10809                        Check_Type_Conformant (Candidate, E);
10810
10811                     else
10812                        Missing_Body;
10813                     end if;
10814                  end;
10815
10816               else
10817                  Missing_Body;
10818               end if;
10819            end if;
10820         end if;
10821      end Post_Error;
10822
10823      --  Local variables
10824
10825      Pack_Id : constant Entity_Id := Current_Scope;
10826
10827   --  Start of processing for Check_Completion
10828
10829   begin
10830      E := First_Entity (Pack_Id);
10831      while Present (E) loop
10832         if Is_Intrinsic_Subprogram (E) then
10833            null;
10834
10835         --  A Ghost entity declared in a non-Ghost package does not force the
10836         --  need for a body (SPARK RM 6.9(11)).
10837
10838         elsif not Is_Ghost_Entity (Pack_Id) and then Is_Ghost_Entity (E) then
10839            null;
10840
10841         --  The following situation requires special handling: a child unit
10842         --  that appears in the context clause of the body of its parent:
10843
10844         --    procedure Parent.Child (...);
10845
10846         --    with Parent.Child;
10847         --    package body Parent is
10848
10849         --  Here Parent.Child appears as a local entity, but should not be
10850         --  flagged as requiring completion, because it is a compilation
10851         --  unit.
10852
10853         --  Ignore missing completion for a subprogram that does not come from
10854         --  source (including the _Call primitive operation of RAS types,
10855         --  which has to have the flag Comes_From_Source for other purposes):
10856         --  we assume that the expander will provide the missing completion.
10857         --  In case of previous errors, other expansion actions that provide
10858         --  bodies for null procedures with not be invoked, so inhibit message
10859         --  in those cases.
10860
10861         --  Note that E_Operator is not in the list that follows, because
10862         --  this kind is reserved for predefined operators, that are
10863         --  intrinsic and do not need completion.
10864
10865         elsif Ekind_In (E, E_Function,
10866                            E_Procedure,
10867                            E_Generic_Function,
10868                            E_Generic_Procedure)
10869         then
10870            if Has_Completion (E) then
10871               null;
10872
10873            elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
10874               null;
10875
10876            elsif Is_Subprogram (E)
10877              and then (not Comes_From_Source (E)
10878                         or else Chars (E) = Name_uCall)
10879            then
10880               null;
10881
10882            elsif
10883               Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
10884            then
10885               null;
10886
10887            elsif Nkind (Parent (E)) = N_Procedure_Specification
10888              and then Null_Present (Parent (E))
10889              and then Serious_Errors_Detected > 0
10890            then
10891               null;
10892
10893            else
10894               Post_Error;
10895            end if;
10896
10897         elsif Is_Entry (E) then
10898            if not Has_Completion (E) and then
10899              (Ekind (Scope (E)) = E_Protected_Object
10900                or else Ekind (Scope (E)) = E_Protected_Type)
10901            then
10902               Post_Error;
10903            end if;
10904
10905         elsif Is_Package_Or_Generic_Package (E) then
10906            if Unit_Requires_Body (E) then
10907               if not Has_Completion (E)
10908                 and then Nkind (Parent (Unit_Declaration_Node (E))) /=
10909                                                       N_Compilation_Unit
10910               then
10911                  Post_Error;
10912               end if;
10913
10914            elsif not Is_Child_Unit (E) then
10915               May_Need_Implicit_Body (E);
10916            end if;
10917
10918         --  A formal incomplete type (Ada 2012) does not require a completion;
10919         --  other incomplete type declarations do.
10920
10921         elsif Ekind (E) = E_Incomplete_Type
10922           and then No (Underlying_Type (E))
10923           and then not Is_Generic_Type (E)
10924         then
10925            Post_Error;
10926
10927         elsif Ekind_In (E, E_Task_Type, E_Protected_Type)
10928           and then not Has_Completion (E)
10929         then
10930            Post_Error;
10931
10932         --  A single task declared in the current scope is a constant, verify
10933         --  that the body of its anonymous type is in the same scope. If the
10934         --  task is defined elsewhere, this may be a renaming declaration for
10935         --  which no completion is needed.
10936
10937         elsif Ekind (E) = E_Constant
10938           and then Ekind (Etype (E)) = E_Task_Type
10939           and then not Has_Completion (Etype (E))
10940           and then Scope (Etype (E)) = Current_Scope
10941         then
10942            Post_Error;
10943
10944         elsif Ekind (E) = E_Protected_Object
10945           and then not Has_Completion (Etype (E))
10946         then
10947            Post_Error;
10948
10949         elsif Ekind (E) = E_Record_Type then
10950            if Is_Tagged_Type (E) then
10951               Check_Abstract_Overriding (E);
10952               Check_Conventions (E);
10953            end if;
10954
10955            Check_Aliased_Component_Types (E);
10956
10957         elsif Ekind (E) = E_Array_Type then
10958            Check_Aliased_Component_Types (E);
10959
10960         end if;
10961
10962         Next_Entity (E);
10963      end loop;
10964   end Check_Completion;
10965
10966   ------------------------------------
10967   -- Check_CPP_Type_Has_No_Defaults --
10968   ------------------------------------
10969
10970   procedure Check_CPP_Type_Has_No_Defaults (T : Entity_Id) is
10971      Tdef  : constant Node_Id := Type_Definition (Declaration_Node (T));
10972      Clist : Node_Id;
10973      Comp  : Node_Id;
10974
10975   begin
10976      --  Obtain the component list
10977
10978      if Nkind (Tdef) = N_Record_Definition then
10979         Clist := Component_List (Tdef);
10980      else pragma Assert (Nkind (Tdef) = N_Derived_Type_Definition);
10981         Clist := Component_List (Record_Extension_Part (Tdef));
10982      end if;
10983
10984      --  Check all components to ensure no default expressions
10985
10986      if Present (Clist) then
10987         Comp := First (Component_Items (Clist));
10988         while Present (Comp) loop
10989            if Present (Expression (Comp)) then
10990               Error_Msg_N
10991                 ("component of imported 'C'P'P type cannot have "
10992                  & "default expression", Expression (Comp));
10993            end if;
10994
10995            Next (Comp);
10996         end loop;
10997      end if;
10998   end Check_CPP_Type_Has_No_Defaults;
10999
11000   ----------------------------
11001   -- Check_Delta_Expression --
11002   ----------------------------
11003
11004   procedure Check_Delta_Expression (E : Node_Id) is
11005   begin
11006      if not (Is_Real_Type (Etype (E))) then
11007         Wrong_Type (E, Any_Real);
11008
11009      elsif not Is_OK_Static_Expression (E) then
11010         Flag_Non_Static_Expr
11011           ("non-static expression used for delta value!", E);
11012
11013      elsif not UR_Is_Positive (Expr_Value_R (E)) then
11014         Error_Msg_N ("delta expression must be positive", E);
11015
11016      else
11017         return;
11018      end if;
11019
11020      --  If any of above errors occurred, then replace the incorrect
11021      --  expression by the real 0.1, which should prevent further errors.
11022
11023      Rewrite (E,
11024        Make_Real_Literal (Sloc (E), Ureal_Tenth));
11025      Analyze_And_Resolve (E, Standard_Float);
11026   end Check_Delta_Expression;
11027
11028   -----------------------------
11029   -- Check_Digits_Expression --
11030   -----------------------------
11031
11032   procedure Check_Digits_Expression (E : Node_Id) is
11033   begin
11034      if not (Is_Integer_Type (Etype (E))) then
11035         Wrong_Type (E, Any_Integer);
11036
11037      elsif not Is_OK_Static_Expression (E) then
11038         Flag_Non_Static_Expr
11039           ("non-static expression used for digits value!", E);
11040
11041      elsif Expr_Value (E) <= 0 then
11042         Error_Msg_N ("digits value must be greater than zero", E);
11043
11044      else
11045         return;
11046      end if;
11047
11048      --  If any of above errors occurred, then replace the incorrect
11049      --  expression by the integer 1, which should prevent further errors.
11050
11051      Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
11052      Analyze_And_Resolve (E, Standard_Integer);
11053
11054   end Check_Digits_Expression;
11055
11056   --------------------------
11057   -- Check_Initialization --
11058   --------------------------
11059
11060   procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
11061   begin
11062      --  Special processing for limited types
11063
11064      if Is_Limited_Type (T)
11065        and then not In_Instance
11066        and then not In_Inlined_Body
11067      then
11068         if not OK_For_Limited_Init (T, Exp) then
11069
11070            --  In GNAT mode, this is just a warning, to allow it to be evilly
11071            --  turned off. Otherwise it is a real error.
11072
11073            if GNAT_Mode then
11074               Error_Msg_N
11075                 ("??cannot initialize entities of limited type!", Exp);
11076
11077            elsif Ada_Version < Ada_2005 then
11078
11079               --  The side effect removal machinery may generate illegal Ada
11080               --  code to avoid the usage of access types and 'reference in
11081               --  SPARK mode. Since this is legal code with respect to theorem
11082               --  proving, do not emit the error.
11083
11084               if GNATprove_Mode
11085                 and then Nkind (Exp) = N_Function_Call
11086                 and then Nkind (Parent (Exp)) = N_Object_Declaration
11087                 and then not Comes_From_Source
11088                                (Defining_Identifier (Parent (Exp)))
11089               then
11090                  null;
11091
11092               else
11093                  Error_Msg_N
11094                    ("cannot initialize entities of limited type", Exp);
11095                  Explain_Limited_Type (T, Exp);
11096               end if;
11097
11098            else
11099               --  Specialize error message according to kind of illegal
11100               --  initial expression.
11101
11102               if Nkind (Exp) = N_Type_Conversion
11103                 and then Nkind (Expression (Exp)) = N_Function_Call
11104               then
11105                  Error_Msg_N
11106                    ("illegal context for call"
11107                      & " to function with limited result", Exp);
11108
11109               else
11110                  Error_Msg_N
11111                    ("initialization of limited object requires aggregate "
11112                      & "or function call",  Exp);
11113               end if;
11114            end if;
11115         end if;
11116      end if;
11117
11118      --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag gets
11119      --  set unless we can be sure that no range check is required.
11120
11121      if (GNATprove_Mode or not Expander_Active)
11122        and then Is_Scalar_Type (T)
11123        and then not Is_In_Range (Exp, T, Assume_Valid => True)
11124      then
11125         Set_Do_Range_Check (Exp);
11126      end if;
11127   end Check_Initialization;
11128
11129   ----------------------
11130   -- Check_Interfaces --
11131   ----------------------
11132
11133   procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
11134      Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
11135
11136      Iface       : Node_Id;
11137      Iface_Def   : Node_Id;
11138      Iface_Typ   : Entity_Id;
11139      Parent_Node : Node_Id;
11140
11141      Is_Task : Boolean := False;
11142      --  Set True if parent type or any progenitor is a task interface
11143
11144      Is_Protected : Boolean := False;
11145      --  Set True if parent type or any progenitor is a protected interface
11146
11147      procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
11148      --  Check that a progenitor is compatible with declaration. If an error
11149      --  message is output, it is posted on Error_Node.
11150
11151      ------------------
11152      -- Check_Ifaces --
11153      ------------------
11154
11155      procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
11156         Iface_Id : constant Entity_Id :=
11157                      Defining_Identifier (Parent (Iface_Def));
11158         Type_Def : Node_Id;
11159
11160      begin
11161         if Nkind (N) = N_Private_Extension_Declaration then
11162            Type_Def := N;
11163         else
11164            Type_Def := Type_Definition (N);
11165         end if;
11166
11167         if Is_Task_Interface (Iface_Id) then
11168            Is_Task := True;
11169
11170         elsif Is_Protected_Interface (Iface_Id) then
11171            Is_Protected := True;
11172         end if;
11173
11174         if Is_Synchronized_Interface (Iface_Id) then
11175
11176            --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
11177            --  extension derived from a synchronized interface must explicitly
11178            --  be declared synchronized, because the full view will be a
11179            --  synchronized type.
11180
11181            if Nkind (N) = N_Private_Extension_Declaration then
11182               if not Synchronized_Present (N) then
11183                  Error_Msg_NE
11184                    ("private extension of& must be explicitly synchronized",
11185                      N, Iface_Id);
11186               end if;
11187
11188            --  However, by 3.9.4(16/2), a full type that is a record extension
11189            --  is never allowed to derive from a synchronized interface (note
11190            --  that interfaces must be excluded from this check, because those
11191            --  are represented by derived type definitions in some cases).
11192
11193            elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
11194              and then not Interface_Present (Type_Definition (N))
11195            then
11196               Error_Msg_N ("record extension cannot derive from synchronized "
11197                            & "interface", Error_Node);
11198            end if;
11199         end if;
11200
11201         --  Check that the characteristics of the progenitor are compatible
11202         --  with the explicit qualifier in the declaration.
11203         --  The check only applies to qualifiers that come from source.
11204         --  Limited_Present also appears in the declaration of corresponding
11205         --  records, and the check does not apply to them.
11206
11207         if Limited_Present (Type_Def)
11208           and then not
11209             Is_Concurrent_Record_Type (Defining_Identifier (N))
11210         then
11211            if Is_Limited_Interface (Parent_Type)
11212              and then not Is_Limited_Interface (Iface_Id)
11213            then
11214               Error_Msg_NE
11215                 ("progenitor & must be limited interface",
11216                   Error_Node, Iface_Id);
11217
11218            elsif
11219              (Task_Present (Iface_Def)
11220                or else Protected_Present (Iface_Def)
11221                or else Synchronized_Present (Iface_Def))
11222              and then Nkind (N) /= N_Private_Extension_Declaration
11223              and then not Error_Posted (N)
11224            then
11225               Error_Msg_NE
11226                 ("progenitor & must be limited interface",
11227                   Error_Node, Iface_Id);
11228            end if;
11229
11230         --  Protected interfaces can only inherit from limited, synchronized
11231         --  or protected interfaces.
11232
11233         elsif Nkind (N) = N_Full_Type_Declaration
11234           and then  Protected_Present (Type_Def)
11235         then
11236            if Limited_Present (Iface_Def)
11237              or else Synchronized_Present (Iface_Def)
11238              or else Protected_Present (Iface_Def)
11239            then
11240               null;
11241
11242            elsif Task_Present (Iface_Def) then
11243               Error_Msg_N ("(Ada 2005) protected interface cannot inherit "
11244                            & "from task interface", Error_Node);
11245
11246            else
11247               Error_Msg_N ("(Ada 2005) protected interface cannot inherit "
11248                            & "from non-limited interface", Error_Node);
11249            end if;
11250
11251         --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
11252         --  limited and synchronized.
11253
11254         elsif Synchronized_Present (Type_Def) then
11255            if Limited_Present (Iface_Def)
11256              or else Synchronized_Present (Iface_Def)
11257            then
11258               null;
11259
11260            elsif Protected_Present (Iface_Def)
11261              and then Nkind (N) /= N_Private_Extension_Declaration
11262            then
11263               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
11264                            & "from protected interface", Error_Node);
11265
11266            elsif Task_Present (Iface_Def)
11267              and then Nkind (N) /= N_Private_Extension_Declaration
11268            then
11269               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
11270                            & "from task interface", Error_Node);
11271
11272            elsif not Is_Limited_Interface (Iface_Id) then
11273               Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
11274                            & "from non-limited interface", Error_Node);
11275            end if;
11276
11277         --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
11278         --  synchronized or task interfaces.
11279
11280         elsif Nkind (N) = N_Full_Type_Declaration
11281           and then Task_Present (Type_Def)
11282         then
11283            if Limited_Present (Iface_Def)
11284              or else Synchronized_Present (Iface_Def)
11285              or else Task_Present (Iface_Def)
11286            then
11287               null;
11288
11289            elsif Protected_Present (Iface_Def) then
11290               Error_Msg_N ("(Ada 2005) task interface cannot inherit from "
11291                            & "protected interface", Error_Node);
11292
11293            else
11294               Error_Msg_N ("(Ada 2005) task interface cannot inherit from "
11295                            & "non-limited interface", Error_Node);
11296            end if;
11297         end if;
11298      end Check_Ifaces;
11299
11300   --  Start of processing for Check_Interfaces
11301
11302   begin
11303      if Is_Interface (Parent_Type) then
11304         if Is_Task_Interface (Parent_Type) then
11305            Is_Task := True;
11306
11307         elsif Is_Protected_Interface (Parent_Type) then
11308            Is_Protected := True;
11309         end if;
11310      end if;
11311
11312      if Nkind (N) = N_Private_Extension_Declaration then
11313
11314         --  Check that progenitors are compatible with declaration
11315
11316         Iface := First (Interface_List (Def));
11317         while Present (Iface) loop
11318            Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
11319
11320            Parent_Node := Parent (Base_Type (Iface_Typ));
11321            Iface_Def   := Type_Definition (Parent_Node);
11322
11323            if not Is_Interface (Iface_Typ) then
11324               Diagnose_Interface (Iface, Iface_Typ);
11325            else
11326               Check_Ifaces (Iface_Def, Iface);
11327            end if;
11328
11329            Next (Iface);
11330         end loop;
11331
11332         if Is_Task and Is_Protected then
11333            Error_Msg_N
11334              ("type cannot derive from task and protected interface", N);
11335         end if;
11336
11337         return;
11338      end if;
11339
11340      --  Full type declaration of derived type.
11341      --  Check compatibility with parent if it is interface type
11342
11343      if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
11344        and then Is_Interface (Parent_Type)
11345      then
11346         Parent_Node := Parent (Parent_Type);
11347
11348         --  More detailed checks for interface varieties
11349
11350         Check_Ifaces
11351           (Iface_Def  => Type_Definition (Parent_Node),
11352            Error_Node => Subtype_Indication (Type_Definition (N)));
11353      end if;
11354
11355      Iface := First (Interface_List (Def));
11356      while Present (Iface) loop
11357         Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
11358
11359         Parent_Node := Parent (Base_Type (Iface_Typ));
11360         Iface_Def   := Type_Definition (Parent_Node);
11361
11362         if not Is_Interface (Iface_Typ) then
11363            Diagnose_Interface (Iface, Iface_Typ);
11364
11365         else
11366            --  "The declaration of a specific descendant of an interface
11367            --   type freezes the interface type" RM 13.14
11368
11369            Freeze_Before (N, Iface_Typ);
11370            Check_Ifaces (Iface_Def, Error_Node => Iface);
11371         end if;
11372
11373         Next (Iface);
11374      end loop;
11375
11376      if Is_Task and Is_Protected then
11377         Error_Msg_N
11378           ("type cannot derive from task and protected interface", N);
11379      end if;
11380   end Check_Interfaces;
11381
11382   ------------------------------------
11383   -- Check_Or_Process_Discriminants --
11384   ------------------------------------
11385
11386   --  If an incomplete or private type declaration was already given for the
11387   --  type, the discriminants may have already been processed if they were
11388   --  present on the incomplete declaration. In this case a full conformance
11389   --  check has been performed in Find_Type_Name, and we then recheck here
11390   --  some properties that can't be checked on the partial view alone.
11391   --  Otherwise we call Process_Discriminants.
11392
11393   procedure Check_Or_Process_Discriminants
11394     (N    : Node_Id;
11395      T    : Entity_Id;
11396      Prev : Entity_Id := Empty)
11397   is
11398   begin
11399      if Has_Discriminants (T) then
11400
11401         --  Discriminants are already set on T if they were already present
11402         --  on the partial view. Make them visible to component declarations.
11403
11404         declare
11405            D : Entity_Id;
11406            --  Discriminant on T (full view) referencing expr on partial view
11407
11408            Prev_D : Entity_Id;
11409            --  Entity of corresponding discriminant on partial view
11410
11411            New_D : Node_Id;
11412            --  Discriminant specification for full view, expression is
11413            --  the syntactic copy on full view (which has been checked for
11414            --  conformance with partial view), only used here to post error
11415            --  message.
11416
11417         begin
11418            D     := First_Discriminant (T);
11419            New_D := First (Discriminant_Specifications (N));
11420            while Present (D) loop
11421               Prev_D := Current_Entity (D);
11422               Set_Current_Entity (D);
11423               Set_Is_Immediately_Visible (D);
11424               Set_Homonym (D, Prev_D);
11425
11426               --  Handle the case where there is an untagged partial view and
11427               --  the full view is tagged: must disallow discriminants with
11428               --  defaults, unless compiling for Ada 2012, which allows a
11429               --  limited tagged type to have defaulted discriminants (see
11430               --  AI05-0214). However, suppress error here if it was already
11431               --  reported on the default expression of the partial view.
11432
11433               if Is_Tagged_Type (T)
11434                 and then Present (Expression (Parent (D)))
11435                 and then (not Is_Limited_Type (Current_Scope)
11436                            or else Ada_Version < Ada_2012)
11437                 and then not Error_Posted (Expression (Parent (D)))
11438               then
11439                  if Ada_Version >= Ada_2012 then
11440                     Error_Msg_N
11441                       ("discriminants of nonlimited tagged type cannot have "
11442                        & "defaults",
11443                        Expression (New_D));
11444                  else
11445                     Error_Msg_N
11446                       ("discriminants of tagged type cannot have defaults",
11447                        Expression (New_D));
11448                  end if;
11449               end if;
11450
11451               --  Ada 2005 (AI-230): Access discriminant allowed in
11452               --  non-limited record types.
11453
11454               if Ada_Version < Ada_2005 then
11455
11456                  --  This restriction gets applied to the full type here. It
11457                  --  has already been applied earlier to the partial view.
11458
11459                  Check_Access_Discriminant_Requires_Limited (Parent (D), N);
11460               end if;
11461
11462               Next_Discriminant (D);
11463               Next (New_D);
11464            end loop;
11465         end;
11466
11467      elsif Present (Discriminant_Specifications (N)) then
11468         Process_Discriminants (N, Prev);
11469      end if;
11470   end Check_Or_Process_Discriminants;
11471
11472   ----------------------
11473   -- Check_Real_Bound --
11474   ----------------------
11475
11476   procedure Check_Real_Bound (Bound : Node_Id) is
11477   begin
11478      if not Is_Real_Type (Etype (Bound)) then
11479         Error_Msg_N
11480           ("bound in real type definition must be of real type", Bound);
11481
11482      elsif not Is_OK_Static_Expression (Bound) then
11483         Flag_Non_Static_Expr
11484           ("non-static expression used for real type bound!", Bound);
11485
11486      else
11487         return;
11488      end if;
11489
11490      Rewrite
11491        (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
11492      Analyze (Bound);
11493      Resolve (Bound, Standard_Float);
11494   end Check_Real_Bound;
11495
11496   ------------------------------
11497   -- Complete_Private_Subtype --
11498   ------------------------------
11499
11500   procedure Complete_Private_Subtype
11501     (Priv        : Entity_Id;
11502      Full        : Entity_Id;
11503      Full_Base   : Entity_Id;
11504      Related_Nod : Node_Id)
11505   is
11506      Save_Next_Entity : Entity_Id;
11507      Save_Homonym     : Entity_Id;
11508
11509   begin
11510      --  Set semantic attributes for (implicit) private subtype completion.
11511      --  If the full type has no discriminants, then it is a copy of the
11512      --  full view of the base. Otherwise, it is a subtype of the base with
11513      --  a possible discriminant constraint. Save and restore the original
11514      --  Next_Entity field of full to ensure that the calls to Copy_Node do
11515      --  not corrupt the entity chain.
11516
11517      --  Note that the type of the full view is the same entity as the type
11518      --  of the partial view. In this fashion, the subtype has access to the
11519      --  correct view of the parent.
11520
11521      Save_Next_Entity := Next_Entity (Full);
11522      Save_Homonym     := Homonym (Priv);
11523
11524      case Ekind (Full_Base) is
11525         when E_Record_Type    |
11526              E_Record_Subtype |
11527              Class_Wide_Kind  |
11528              Private_Kind     |
11529              Task_Kind        |
11530              Protected_Kind   =>
11531            Copy_Node (Priv, Full);
11532
11533            Set_Has_Discriminants
11534                             (Full, Has_Discriminants (Full_Base));
11535            Set_Has_Unknown_Discriminants
11536                             (Full, Has_Unknown_Discriminants (Full_Base));
11537            Set_First_Entity (Full, First_Entity (Full_Base));
11538            Set_Last_Entity  (Full, Last_Entity (Full_Base));
11539
11540            --  If the underlying base type is constrained, we know that the
11541            --  full view of the subtype is constrained as well (the converse
11542            --  is not necessarily true).
11543
11544            if Is_Constrained (Full_Base) then
11545               Set_Is_Constrained (Full);
11546            end if;
11547
11548         when others =>
11549            Copy_Node (Full_Base, Full);
11550
11551            Set_Chars         (Full, Chars (Priv));
11552            Conditional_Delay (Full, Priv);
11553            Set_Sloc          (Full, Sloc (Priv));
11554      end case;
11555
11556      Set_Next_Entity               (Full, Save_Next_Entity);
11557      Set_Homonym                   (Full, Save_Homonym);
11558      Set_Associated_Node_For_Itype (Full, Related_Nod);
11559
11560      --  Set common attributes for all subtypes: kind, convention, etc.
11561
11562      Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
11563      Set_Convention (Full, Convention (Full_Base));
11564
11565      --  The Etype of the full view is inconsistent. Gigi needs to see the
11566      --  structural full view, which is what the current scheme gives: the
11567      --  Etype of the full view is the etype of the full base. However, if the
11568      --  full base is a derived type, the full view then looks like a subtype
11569      --  of the parent, not a subtype of the full base. If instead we write:
11570
11571      --       Set_Etype (Full, Full_Base);
11572
11573      --  then we get inconsistencies in the front-end (confusion between
11574      --  views). Several outstanding bugs are related to this ???
11575
11576      Set_Is_First_Subtype (Full, False);
11577      Set_Scope            (Full, Scope (Priv));
11578      Set_Size_Info        (Full, Full_Base);
11579      Set_RM_Size          (Full, RM_Size (Full_Base));
11580      Set_Is_Itype         (Full);
11581
11582      --  A subtype of a private-type-without-discriminants, whose full-view
11583      --  has discriminants with default expressions, is not constrained.
11584
11585      if not Has_Discriminants (Priv) then
11586         Set_Is_Constrained (Full, Is_Constrained (Full_Base));
11587
11588         if Has_Discriminants (Full_Base) then
11589            Set_Discriminant_Constraint
11590              (Full, Discriminant_Constraint (Full_Base));
11591
11592            --  The partial view may have been indefinite, the full view
11593            --  might not be.
11594
11595            Set_Has_Unknown_Discriminants
11596              (Full, Has_Unknown_Discriminants (Full_Base));
11597         end if;
11598      end if;
11599
11600      Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
11601      Set_Depends_On_Private (Full, Has_Private_Component (Full));
11602
11603      --  Freeze the private subtype entity if its parent is delayed, and not
11604      --  already frozen. We skip this processing if the type is an anonymous
11605      --  subtype of a record component, or is the corresponding record of a
11606      --  protected type, since ???
11607
11608      if not Is_Type (Scope (Full)) then
11609         Set_Has_Delayed_Freeze (Full,
11610           Has_Delayed_Freeze (Full_Base)
11611             and then (not Is_Frozen (Full_Base)));
11612      end if;
11613
11614      Set_Freeze_Node (Full, Empty);
11615      Set_Is_Frozen (Full, False);
11616      Set_Full_View (Priv, Full);
11617
11618      if Has_Discriminants (Full) then
11619         Set_Stored_Constraint_From_Discriminant_Constraint (Full);
11620         Set_Stored_Constraint (Priv, Stored_Constraint (Full));
11621
11622         if Has_Unknown_Discriminants (Full) then
11623            Set_Discriminant_Constraint (Full, No_Elist);
11624         end if;
11625      end if;
11626
11627      if Ekind (Full_Base) = E_Record_Type
11628        and then Has_Discriminants (Full_Base)
11629        and then Has_Discriminants (Priv) -- might not, if errors
11630        and then not Has_Unknown_Discriminants (Priv)
11631        and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
11632      then
11633         Create_Constrained_Components
11634           (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
11635
11636      --  If the full base is itself derived from private, build a congruent
11637      --  subtype of its underlying type, for use by the back end. For a
11638      --  constrained record component, the declaration cannot be placed on
11639      --  the component list, but it must nevertheless be built an analyzed, to
11640      --  supply enough information for Gigi to compute the size of component.
11641
11642      elsif Ekind (Full_Base) in Private_Kind
11643        and then Is_Derived_Type (Full_Base)
11644        and then Has_Discriminants (Full_Base)
11645        and then (Ekind (Current_Scope) /= E_Record_Subtype)
11646      then
11647         if not Is_Itype (Priv)
11648           and then
11649             Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
11650         then
11651            Build_Underlying_Full_View
11652              (Parent (Priv), Full, Etype (Full_Base));
11653
11654         elsif Nkind (Related_Nod) = N_Component_Declaration then
11655            Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
11656         end if;
11657
11658      elsif Is_Record_Type (Full_Base) then
11659
11660         --  Show Full is simply a renaming of Full_Base
11661
11662         Set_Cloned_Subtype (Full, Full_Base);
11663      end if;
11664
11665      --  It is unsafe to share the bounds of a scalar type, because the Itype
11666      --  is elaborated on demand, and if a bound is non-static then different
11667      --  orders of elaboration in different units will lead to different
11668      --  external symbols.
11669
11670      if Is_Scalar_Type (Full_Base) then
11671         Set_Scalar_Range (Full,
11672           Make_Range (Sloc (Related_Nod),
11673             Low_Bound  =>
11674               Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
11675             High_Bound =>
11676               Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
11677
11678         --  This completion inherits the bounds of the full parent, but if
11679         --  the parent is an unconstrained floating point type, so is the
11680         --  completion.
11681
11682         if Is_Floating_Point_Type (Full_Base) then
11683            Set_Includes_Infinities
11684             (Scalar_Range (Full), Has_Infinities (Full_Base));
11685         end if;
11686      end if;
11687
11688      --  ??? It seems that a lot of fields are missing that should be copied
11689      --  from Full_Base to Full. Here are some that are introduced in a
11690      --  non-disruptive way but a cleanup is necessary.
11691
11692      if Is_Tagged_Type (Full_Base) then
11693         Set_Is_Tagged_Type (Full);
11694         Set_Direct_Primitive_Operations
11695           (Full, Direct_Primitive_Operations (Full_Base));
11696         Set_No_Tagged_Streams_Pragma
11697           (Full, No_Tagged_Streams_Pragma (Full_Base));
11698
11699         --  Inherit class_wide type of full_base in case the partial view was
11700         --  not tagged. Otherwise it has already been created when the private
11701         --  subtype was analyzed.
11702
11703         if No (Class_Wide_Type (Full)) then
11704            Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
11705         end if;
11706
11707      --  If this is a subtype of a protected or task type, constrain its
11708      --  corresponding record, unless this is a subtype without constraints,
11709      --  i.e. a simple renaming as with an actual subtype in an instance.
11710
11711      elsif Is_Concurrent_Type (Full_Base) then
11712         if Has_Discriminants (Full)
11713           and then Present (Corresponding_Record_Type (Full_Base))
11714           and then
11715             not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
11716         then
11717            Set_Corresponding_Record_Type (Full,
11718              Constrain_Corresponding_Record
11719                (Full, Corresponding_Record_Type (Full_Base), Related_Nod));
11720
11721         else
11722            Set_Corresponding_Record_Type (Full,
11723              Corresponding_Record_Type (Full_Base));
11724         end if;
11725      end if;
11726
11727      --  Link rep item chain, and also setting of Has_Predicates from private
11728      --  subtype to full subtype, since we will need these on the full subtype
11729      --  to create the predicate function. Note that the full subtype may
11730      --  already have rep items, inherited from the full view of the base
11731      --  type, so we must be sure not to overwrite these entries.
11732
11733      declare
11734         Append    : Boolean;
11735         Item      : Node_Id;
11736         Next_Item : Node_Id;
11737
11738      begin
11739         Item := First_Rep_Item (Full);
11740
11741         --  If no existing rep items on full type, we can just link directly
11742         --  to the list of items on the private type, if any exist.. Same if
11743         --  the rep items are only those inherited from the base
11744
11745         if (No (Item)
11746              or else Nkind (Item) /= N_Aspect_Specification
11747              or else Entity (Item) = Full_Base)
11748             and then Present (First_Rep_Item (Priv))
11749         then
11750            Set_First_Rep_Item (Full, First_Rep_Item (Priv));
11751
11752         --  Otherwise, search to the end of items currently linked to the full
11753         --  subtype and append the private items to the end. However, if Priv
11754         --  and Full already have the same list of rep items, then the append
11755         --  is not done, as that would create a circularity.
11756
11757         elsif Item /= First_Rep_Item (Priv) then
11758            Append := True;
11759            loop
11760               Next_Item := Next_Rep_Item (Item);
11761               exit when No (Next_Item);
11762               Item := Next_Item;
11763
11764               --  If the private view has aspect specifications, the full view
11765               --  inherits them. Since these aspects may already have been
11766               --  attached to the full view during derivation, do not append
11767               --  them if already present.
11768
11769               if Item = First_Rep_Item (Priv) then
11770                  Append := False;
11771                  exit;
11772               end if;
11773            end loop;
11774
11775            --  And link the private type items at the end of the chain
11776
11777            if Append then
11778               Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
11779            end if;
11780         end if;
11781      end;
11782
11783      --  Make sure Has_Predicates is set on full type if it is set on the
11784      --  private type. Note that it may already be set on the full type and
11785      --  if so, we don't want to unset it.
11786
11787      if Has_Predicates (Priv) then
11788         Set_Has_Predicates (Full);
11789      end if;
11790   end Complete_Private_Subtype;
11791
11792   ----------------------------
11793   -- Constant_Redeclaration --
11794   ----------------------------
11795
11796   procedure Constant_Redeclaration
11797     (Id : Entity_Id;
11798      N  : Node_Id;
11799      T  : out Entity_Id)
11800   is
11801      Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
11802      Obj_Def : constant Node_Id := Object_Definition (N);
11803      New_T   : Entity_Id;
11804
11805      procedure Check_Possible_Deferred_Completion
11806        (Prev_Id      : Entity_Id;
11807         Prev_Obj_Def : Node_Id;
11808         Curr_Obj_Def : Node_Id);
11809      --  Determine whether the two object definitions describe the partial
11810      --  and the full view of a constrained deferred constant. Generate
11811      --  a subtype for the full view and verify that it statically matches
11812      --  the subtype of the partial view.
11813
11814      procedure Check_Recursive_Declaration (Typ : Entity_Id);
11815      --  If deferred constant is an access type initialized with an allocator,
11816      --  check whether there is an illegal recursion in the definition,
11817      --  through a default value of some record subcomponent. This is normally
11818      --  detected when generating init procs, but requires this additional
11819      --  mechanism when expansion is disabled.
11820
11821      ----------------------------------------
11822      -- Check_Possible_Deferred_Completion --
11823      ----------------------------------------
11824
11825      procedure Check_Possible_Deferred_Completion
11826        (Prev_Id      : Entity_Id;
11827         Prev_Obj_Def : Node_Id;
11828         Curr_Obj_Def : Node_Id)
11829      is
11830      begin
11831         if Nkind (Prev_Obj_Def) = N_Subtype_Indication
11832           and then Present (Constraint (Prev_Obj_Def))
11833           and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
11834           and then Present (Constraint (Curr_Obj_Def))
11835         then
11836            declare
11837               Loc    : constant Source_Ptr := Sloc (N);
11838               Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
11839               Decl   : constant Node_Id    :=
11840                          Make_Subtype_Declaration (Loc,
11841                            Defining_Identifier => Def_Id,
11842                            Subtype_Indication  =>
11843                              Relocate_Node (Curr_Obj_Def));
11844
11845            begin
11846               Insert_Before_And_Analyze (N, Decl);
11847               Set_Etype (Id, Def_Id);
11848
11849               if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
11850                  Error_Msg_Sloc := Sloc (Prev_Id);
11851                  Error_Msg_N ("subtype does not statically match deferred "
11852                               & "declaration #", N);
11853               end if;
11854            end;
11855         end if;
11856      end Check_Possible_Deferred_Completion;
11857
11858      ---------------------------------
11859      -- Check_Recursive_Declaration --
11860      ---------------------------------
11861
11862      procedure Check_Recursive_Declaration (Typ : Entity_Id) is
11863         Comp : Entity_Id;
11864
11865      begin
11866         if Is_Record_Type (Typ) then
11867            Comp := First_Component (Typ);
11868            while Present (Comp) loop
11869               if Comes_From_Source (Comp) then
11870                  if Present (Expression (Parent (Comp)))
11871                    and then Is_Entity_Name (Expression (Parent (Comp)))
11872                    and then Entity (Expression (Parent (Comp))) = Prev
11873                  then
11874                     Error_Msg_Sloc := Sloc (Parent (Comp));
11875                     Error_Msg_NE
11876                       ("illegal circularity with declaration for & #",
11877                         N, Comp);
11878                     return;
11879
11880                  elsif Is_Record_Type (Etype (Comp)) then
11881                     Check_Recursive_Declaration (Etype (Comp));
11882                  end if;
11883               end if;
11884
11885               Next_Component (Comp);
11886            end loop;
11887         end if;
11888      end Check_Recursive_Declaration;
11889
11890   --  Start of processing for Constant_Redeclaration
11891
11892   begin
11893      if Nkind (Parent (Prev)) = N_Object_Declaration then
11894         if Nkind (Object_Definition
11895                     (Parent (Prev))) = N_Subtype_Indication
11896         then
11897            --  Find type of new declaration. The constraints of the two
11898            --  views must match statically, but there is no point in
11899            --  creating an itype for the full view.
11900
11901            if Nkind (Obj_Def) = N_Subtype_Indication then
11902               Find_Type (Subtype_Mark (Obj_Def));
11903               New_T := Entity (Subtype_Mark (Obj_Def));
11904
11905            else
11906               Find_Type (Obj_Def);
11907               New_T := Entity (Obj_Def);
11908            end if;
11909
11910            T := Etype (Prev);
11911
11912         else
11913            --  The full view may impose a constraint, even if the partial
11914            --  view does not, so construct the subtype.
11915
11916            New_T := Find_Type_Of_Object (Obj_Def, N);
11917            T     := New_T;
11918         end if;
11919
11920      else
11921         --  Current declaration is illegal, diagnosed below in Enter_Name
11922
11923         T := Empty;
11924         New_T := Any_Type;
11925      end if;
11926
11927      --  If previous full declaration or a renaming declaration exists, or if
11928      --  a homograph is present, let Enter_Name handle it, either with an
11929      --  error or with the removal of an overridden implicit subprogram.
11930      --  The previous one is a full declaration if it has an expression
11931      --  (which in the case of an aggregate is indicated by the Init flag).
11932
11933      if Ekind (Prev) /= E_Constant
11934        or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
11935        or else Present (Expression (Parent (Prev)))
11936        or else Has_Init_Expression (Parent (Prev))
11937        or else Present (Full_View (Prev))
11938      then
11939         Enter_Name (Id);
11940
11941      --  Verify that types of both declarations match, or else that both types
11942      --  are anonymous access types whose designated subtypes statically match
11943      --  (as allowed in Ada 2005 by AI-385).
11944
11945      elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
11946        and then
11947          (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
11948             or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
11949             or else Is_Access_Constant (Etype (New_T)) /=
11950                     Is_Access_Constant (Etype (Prev))
11951             or else Can_Never_Be_Null (Etype (New_T)) /=
11952                     Can_Never_Be_Null (Etype (Prev))
11953             or else Null_Exclusion_Present (Parent (Prev)) /=
11954                     Null_Exclusion_Present (Parent (Id))
11955             or else not Subtypes_Statically_Match
11956                           (Designated_Type (Etype (Prev)),
11957                            Designated_Type (Etype (New_T))))
11958      then
11959         Error_Msg_Sloc := Sloc (Prev);
11960         Error_Msg_N ("type does not match declaration#", N);
11961         Set_Full_View (Prev, Id);
11962         Set_Etype (Id, Any_Type);
11963
11964         --  A deferred constant whose type is an anonymous array is always
11965         --  illegal (unless imported). A detailed error message might be
11966         --  helpful for Ada beginners.
11967
11968         if Nkind (Object_Definition (Parent (Prev)))
11969            = N_Constrained_Array_Definition
11970           and then Nkind (Object_Definition (N))
11971              = N_Constrained_Array_Definition
11972         then
11973            Error_Msg_N ("\each anonymous array is a distinct type", N);
11974            Error_Msg_N ("a deferred constant must have a named type",
11975              Object_Definition (Parent (Prev)));
11976         end if;
11977
11978      elsif
11979        Null_Exclusion_Present (Parent (Prev))
11980          and then not Null_Exclusion_Present (N)
11981      then
11982         Error_Msg_Sloc := Sloc (Prev);
11983         Error_Msg_N ("null-exclusion does not match declaration#", N);
11984         Set_Full_View (Prev, Id);
11985         Set_Etype (Id, Any_Type);
11986
11987      --  If so, process the full constant declaration
11988
11989      else
11990         --  RM 7.4 (6): If the subtype defined by the subtype_indication in
11991         --  the deferred declaration is constrained, then the subtype defined
11992         --  by the subtype_indication in the full declaration shall match it
11993         --  statically.
11994
11995         Check_Possible_Deferred_Completion
11996           (Prev_Id      => Prev,
11997            Prev_Obj_Def => Object_Definition (Parent (Prev)),
11998            Curr_Obj_Def => Obj_Def);
11999
12000         Set_Full_View (Prev, Id);
12001         Set_Is_Public (Id, Is_Public (Prev));
12002         Set_Is_Internal (Id);
12003         Append_Entity (Id, Current_Scope);
12004
12005         --  Check ALIASED present if present before (RM 7.4(7))
12006
12007         if Is_Aliased (Prev)
12008           and then not Aliased_Present (N)
12009         then
12010            Error_Msg_Sloc := Sloc (Prev);
12011            Error_Msg_N ("ALIASED required (see declaration #)", N);
12012         end if;
12013
12014         --  Check that placement is in private part and that the incomplete
12015         --  declaration appeared in the visible part.
12016
12017         if Ekind (Current_Scope) = E_Package
12018           and then not In_Private_Part (Current_Scope)
12019         then
12020            Error_Msg_Sloc := Sloc (Prev);
12021            Error_Msg_N
12022              ("full constant for declaration # must be in private part", N);
12023
12024         elsif Ekind (Current_Scope) = E_Package
12025           and then
12026             List_Containing (Parent (Prev)) /=
12027               Visible_Declarations (Package_Specification (Current_Scope))
12028         then
12029            Error_Msg_N
12030              ("deferred constant must be declared in visible part",
12031                 Parent (Prev));
12032         end if;
12033
12034         if Is_Access_Type (T)
12035           and then Nkind (Expression (N)) = N_Allocator
12036         then
12037            Check_Recursive_Declaration (Designated_Type (T));
12038         end if;
12039
12040         --  A deferred constant is a visible entity. If type has invariants,
12041         --  verify that the initial value satisfies them.
12042
12043         if Has_Invariants (T) and then Present (Invariant_Procedure (T)) then
12044            Insert_After (N,
12045              Make_Invariant_Call (New_Occurrence_Of (Prev, Sloc (N))));
12046         end if;
12047      end if;
12048   end Constant_Redeclaration;
12049
12050   ----------------------
12051   -- Constrain_Access --
12052   ----------------------
12053
12054   procedure Constrain_Access
12055     (Def_Id      : in out Entity_Id;
12056      S           : Node_Id;
12057      Related_Nod : Node_Id)
12058   is
12059      T             : constant Entity_Id := Entity (Subtype_Mark (S));
12060      Desig_Type    : constant Entity_Id := Designated_Type (T);
12061      Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
12062      Constraint_OK : Boolean := True;
12063
12064   begin
12065      if Is_Array_Type (Desig_Type) then
12066         Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
12067
12068      elsif (Is_Record_Type (Desig_Type)
12069              or else Is_Incomplete_Or_Private_Type (Desig_Type))
12070        and then not Is_Constrained (Desig_Type)
12071      then
12072         --  ??? The following code is a temporary bypass to ignore a
12073         --  discriminant constraint on access type if it is constraining
12074         --  the current record. Avoid creating the implicit subtype of the
12075         --  record we are currently compiling since right now, we cannot
12076         --  handle these. For now, just return the access type itself.
12077
12078         if Desig_Type = Current_Scope
12079           and then No (Def_Id)
12080         then
12081            Set_Ekind (Desig_Subtype, E_Record_Subtype);
12082            Def_Id := Entity (Subtype_Mark (S));
12083
12084            --  This call added to ensure that the constraint is analyzed
12085            --  (needed for a B test). Note that we still return early from
12086            --  this procedure to avoid recursive processing. ???
12087
12088            Constrain_Discriminated_Type
12089              (Desig_Subtype, S, Related_Nod, For_Access => True);
12090            return;
12091         end if;
12092
12093         --  Enforce rule that the constraint is illegal if there is an
12094         --  unconstrained view of the designated type. This means that the
12095         --  partial view (either a private type declaration or a derivation
12096         --  from a private type) has no discriminants. (Defect Report
12097         --  8652/0008, Technical Corrigendum 1, checked by ACATS B371001).
12098
12099         --  Rule updated for Ada 2005: The private type is said to have
12100         --  a constrained partial view, given that objects of the type
12101         --  can be declared. Furthermore, the rule applies to all access
12102         --  types, unlike the rule concerning default discriminants (see
12103         --  RM 3.7.1(7/3))
12104
12105         if (Ekind (T) = E_General_Access_Type or else Ada_Version >= Ada_2005)
12106           and then Has_Private_Declaration (Desig_Type)
12107           and then In_Open_Scopes (Scope (Desig_Type))
12108           and then Has_Discriminants (Desig_Type)
12109         then
12110            declare
12111               Pack  : constant Node_Id :=
12112                         Unit_Declaration_Node (Scope (Desig_Type));
12113               Decls : List_Id;
12114               Decl  : Node_Id;
12115
12116            begin
12117               if Nkind (Pack) = N_Package_Declaration then
12118                  Decls := Visible_Declarations (Specification (Pack));
12119                  Decl := First (Decls);
12120                  while Present (Decl) loop
12121                     if (Nkind (Decl) = N_Private_Type_Declaration
12122                          and then Chars (Defining_Identifier (Decl)) =
12123                                                           Chars (Desig_Type))
12124
12125                       or else
12126                        (Nkind (Decl) = N_Full_Type_Declaration
12127                          and then
12128                            Chars (Defining_Identifier (Decl)) =
12129                                                     Chars (Desig_Type)
12130                          and then Is_Derived_Type (Desig_Type)
12131                          and then
12132                            Has_Private_Declaration (Etype (Desig_Type)))
12133                     then
12134                        if No (Discriminant_Specifications (Decl)) then
12135                           Error_Msg_N
12136                             ("cannot constrain access type if designated "
12137                              & "type has constrained partial view", S);
12138                        end if;
12139
12140                        exit;
12141                     end if;
12142
12143                     Next (Decl);
12144                  end loop;
12145               end if;
12146            end;
12147         end if;
12148
12149         Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
12150           For_Access => True);
12151
12152      elsif Is_Concurrent_Type (Desig_Type)
12153        and then not Is_Constrained (Desig_Type)
12154      then
12155         Constrain_Concurrent (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
12156
12157      else
12158         Error_Msg_N ("invalid constraint on access type", S);
12159
12160         --  We simply ignore an invalid constraint
12161
12162         Desig_Subtype := Desig_Type;
12163         Constraint_OK := False;
12164      end if;
12165
12166      if No (Def_Id) then
12167         Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
12168      else
12169         Set_Ekind (Def_Id, E_Access_Subtype);
12170      end if;
12171
12172      if Constraint_OK then
12173         Set_Etype (Def_Id, Base_Type (T));
12174
12175         if Is_Private_Type (Desig_Type) then
12176            Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
12177         end if;
12178      else
12179         Set_Etype (Def_Id, Any_Type);
12180      end if;
12181
12182      Set_Size_Info                (Def_Id, T);
12183      Set_Is_Constrained           (Def_Id, Constraint_OK);
12184      Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
12185      Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
12186      Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
12187
12188      Conditional_Delay (Def_Id, T);
12189
12190      --  AI-363 : Subtypes of general access types whose designated types have
12191      --  default discriminants are disallowed. In instances, the rule has to
12192      --  be checked against the actual, of which T is the subtype. In a
12193      --  generic body, the rule is checked assuming that the actual type has
12194      --  defaulted discriminants.
12195
12196      if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
12197         if Ekind (Base_Type (T)) = E_General_Access_Type
12198           and then Has_Defaulted_Discriminants (Desig_Type)
12199         then
12200            if Ada_Version < Ada_2005 then
12201               Error_Msg_N
12202                 ("access subtype of general access type would not " &
12203                  "be allowed in Ada 2005?y?", S);
12204            else
12205               Error_Msg_N
12206                 ("access subtype of general access type not allowed", S);
12207            end if;
12208
12209            Error_Msg_N ("\discriminants have defaults", S);
12210
12211         elsif Is_Access_Type (T)
12212           and then Is_Generic_Type (Desig_Type)
12213           and then Has_Discriminants (Desig_Type)
12214           and then In_Package_Body (Current_Scope)
12215         then
12216            if Ada_Version < Ada_2005 then
12217               Error_Msg_N
12218                 ("access subtype would not be allowed in generic body "
12219                  & "in Ada 2005?y?", S);
12220            else
12221               Error_Msg_N
12222                 ("access subtype not allowed in generic body", S);
12223            end if;
12224
12225            Error_Msg_N
12226              ("\designated type is a discriminated formal", S);
12227         end if;
12228      end if;
12229   end Constrain_Access;
12230
12231   ---------------------
12232   -- Constrain_Array --
12233   ---------------------
12234
12235   procedure Constrain_Array
12236     (Def_Id      : in out Entity_Id;
12237      SI          : Node_Id;
12238      Related_Nod : Node_Id;
12239      Related_Id  : Entity_Id;
12240      Suffix      : Character)
12241   is
12242      C                     : constant Node_Id := Constraint (SI);
12243      Number_Of_Constraints : Nat := 0;
12244      Index                 : Node_Id;
12245      S, T                  : Entity_Id;
12246      Constraint_OK         : Boolean := True;
12247
12248   begin
12249      T := Entity (Subtype_Mark (SI));
12250
12251      if Is_Access_Type (T) then
12252         T := Designated_Type (T);
12253      end if;
12254
12255      --  If an index constraint follows a subtype mark in a subtype indication
12256      --  then the type or subtype denoted by the subtype mark must not already
12257      --  impose an index constraint. The subtype mark must denote either an
12258      --  unconstrained array type or an access type whose designated type
12259      --  is such an array type... (RM 3.6.1)
12260
12261      if Is_Constrained (T) then
12262         Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
12263         Constraint_OK := False;
12264
12265      else
12266         S := First (Constraints (C));
12267         while Present (S) loop
12268            Number_Of_Constraints := Number_Of_Constraints + 1;
12269            Next (S);
12270         end loop;
12271
12272         --  In either case, the index constraint must provide a discrete
12273         --  range for each index of the array type and the type of each
12274         --  discrete range must be the same as that of the corresponding
12275         --  index. (RM 3.6.1)
12276
12277         if Number_Of_Constraints /= Number_Dimensions (T) then
12278            Error_Msg_NE ("incorrect number of index constraints for }", C, T);
12279            Constraint_OK := False;
12280
12281         else
12282            S := First (Constraints (C));
12283            Index := First_Index (T);
12284            Analyze (Index);
12285
12286            --  Apply constraints to each index type
12287
12288            for J in 1 .. Number_Of_Constraints loop
12289               Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
12290               Next (Index);
12291               Next (S);
12292            end loop;
12293
12294         end if;
12295      end if;
12296
12297      if No (Def_Id) then
12298         Def_Id :=
12299           Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
12300         Set_Parent (Def_Id, Related_Nod);
12301
12302      else
12303         Set_Ekind (Def_Id, E_Array_Subtype);
12304      end if;
12305
12306      Set_Size_Info      (Def_Id,                (T));
12307      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
12308      Set_Etype          (Def_Id, Base_Type      (T));
12309
12310      if Constraint_OK then
12311         Set_First_Index (Def_Id, First (Constraints (C)));
12312      else
12313         Set_First_Index (Def_Id, First_Index (T));
12314      end if;
12315
12316      Set_Is_Constrained     (Def_Id, True);
12317      Set_Is_Aliased         (Def_Id, Is_Aliased (T));
12318      Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
12319
12320      Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
12321      Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
12322
12323      --  A subtype does not inherit the Packed_Array_Impl_Type of is parent.
12324      --  We need to initialize the attribute because if Def_Id is previously
12325      --  analyzed through a limited_with clause, it will have the attributes
12326      --  of an incomplete type, one of which is an Elist that overlaps the
12327      --  Packed_Array_Impl_Type field.
12328
12329      Set_Packed_Array_Impl_Type (Def_Id, Empty);
12330
12331      --  Build a freeze node if parent still needs one. Also make sure that
12332      --  the Depends_On_Private status is set because the subtype will need
12333      --  reprocessing at the time the base type does, and also we must set a
12334      --  conditional delay.
12335
12336      Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
12337      Conditional_Delay (Def_Id, T);
12338   end Constrain_Array;
12339
12340   ------------------------------
12341   -- Constrain_Component_Type --
12342   ------------------------------
12343
12344   function Constrain_Component_Type
12345     (Comp            : Entity_Id;
12346      Constrained_Typ : Entity_Id;
12347      Related_Node    : Node_Id;
12348      Typ             : Entity_Id;
12349      Constraints     : Elist_Id) return Entity_Id
12350   is
12351      Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
12352      Compon_Type : constant Entity_Id := Etype (Comp);
12353
12354      function Build_Constrained_Array_Type
12355        (Old_Type : Entity_Id) return Entity_Id;
12356      --  If Old_Type is an array type, one of whose indexes is constrained
12357      --  by a discriminant, build an Itype whose constraint replaces the
12358      --  discriminant with its value in the constraint.
12359
12360      function Build_Constrained_Discriminated_Type
12361        (Old_Type : Entity_Id) return Entity_Id;
12362      --  Ditto for record components
12363
12364      function Build_Constrained_Access_Type
12365        (Old_Type : Entity_Id) return Entity_Id;
12366      --  Ditto for access types. Makes use of previous two functions, to
12367      --  constrain designated type.
12368
12369      function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
12370      --  T is an array or discriminated type, C is a list of constraints
12371      --  that apply to T. This routine builds the constrained subtype.
12372
12373      function Is_Discriminant (Expr : Node_Id) return Boolean;
12374      --  Returns True if Expr is a discriminant
12375
12376      function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
12377      --  Find the value of discriminant Discrim in Constraint
12378
12379      -----------------------------------
12380      -- Build_Constrained_Access_Type --
12381      -----------------------------------
12382
12383      function Build_Constrained_Access_Type
12384        (Old_Type : Entity_Id) return Entity_Id
12385      is
12386         Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
12387         Itype         : Entity_Id;
12388         Desig_Subtype : Entity_Id;
12389         Scop          : Entity_Id;
12390
12391      begin
12392         --  if the original access type was not embedded in the enclosing
12393         --  type definition, there is no need to produce a new access
12394         --  subtype. In fact every access type with an explicit constraint
12395         --  generates an itype whose scope is the enclosing record.
12396
12397         if not Is_Type (Scope (Old_Type)) then
12398            return Old_Type;
12399
12400         elsif Is_Array_Type (Desig_Type) then
12401            Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
12402
12403         elsif Has_Discriminants (Desig_Type) then
12404
12405            --  This may be an access type to an enclosing record type for
12406            --  which we are constructing the constrained components. Return
12407            --  the enclosing record subtype. This is not always correct,
12408            --  but avoids infinite recursion. ???
12409
12410            Desig_Subtype := Any_Type;
12411
12412            for J in reverse 0 .. Scope_Stack.Last loop
12413               Scop := Scope_Stack.Table (J).Entity;
12414
12415               if Is_Type (Scop)
12416                 and then Base_Type (Scop) = Base_Type (Desig_Type)
12417               then
12418                  Desig_Subtype := Scop;
12419               end if;
12420
12421               exit when not Is_Type (Scop);
12422            end loop;
12423
12424            if Desig_Subtype = Any_Type then
12425               Desig_Subtype :=
12426                 Build_Constrained_Discriminated_Type (Desig_Type);
12427            end if;
12428
12429         else
12430            return Old_Type;
12431         end if;
12432
12433         if Desig_Subtype /= Desig_Type then
12434
12435            --  The Related_Node better be here or else we won't be able
12436            --  to attach new itypes to a node in the tree.
12437
12438            pragma Assert (Present (Related_Node));
12439
12440            Itype := Create_Itype (E_Access_Subtype, Related_Node);
12441
12442            Set_Etype                    (Itype, Base_Type      (Old_Type));
12443            Set_Size_Info                (Itype,                (Old_Type));
12444            Set_Directly_Designated_Type (Itype, Desig_Subtype);
12445            Set_Depends_On_Private       (Itype, Has_Private_Component
12446                                                                (Old_Type));
12447            Set_Is_Access_Constant       (Itype, Is_Access_Constant
12448                                                                (Old_Type));
12449
12450            --  The new itype needs freezing when it depends on a not frozen
12451            --  type and the enclosing subtype needs freezing.
12452
12453            if Has_Delayed_Freeze (Constrained_Typ)
12454              and then not Is_Frozen (Constrained_Typ)
12455            then
12456               Conditional_Delay (Itype, Base_Type (Old_Type));
12457            end if;
12458
12459            return Itype;
12460
12461         else
12462            return Old_Type;
12463         end if;
12464      end Build_Constrained_Access_Type;
12465
12466      ----------------------------------
12467      -- Build_Constrained_Array_Type --
12468      ----------------------------------
12469
12470      function Build_Constrained_Array_Type
12471        (Old_Type : Entity_Id) return Entity_Id
12472      is
12473         Lo_Expr     : Node_Id;
12474         Hi_Expr     : Node_Id;
12475         Old_Index   : Node_Id;
12476         Range_Node  : Node_Id;
12477         Constr_List : List_Id;
12478
12479         Need_To_Create_Itype : Boolean := False;
12480
12481      begin
12482         Old_Index := First_Index (Old_Type);
12483         while Present (Old_Index) loop
12484            Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
12485
12486            if Is_Discriminant (Lo_Expr)
12487                 or else
12488               Is_Discriminant (Hi_Expr)
12489            then
12490               Need_To_Create_Itype := True;
12491            end if;
12492
12493            Next_Index (Old_Index);
12494         end loop;
12495
12496         if Need_To_Create_Itype then
12497            Constr_List := New_List;
12498
12499            Old_Index := First_Index (Old_Type);
12500            while Present (Old_Index) loop
12501               Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
12502
12503               if Is_Discriminant (Lo_Expr) then
12504                  Lo_Expr := Get_Discr_Value (Lo_Expr);
12505               end if;
12506
12507               if Is_Discriminant (Hi_Expr) then
12508                  Hi_Expr := Get_Discr_Value (Hi_Expr);
12509               end if;
12510
12511               Range_Node :=
12512                 Make_Range
12513                   (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
12514
12515               Append (Range_Node, To => Constr_List);
12516
12517               Next_Index (Old_Index);
12518            end loop;
12519
12520            return Build_Subtype (Old_Type, Constr_List);
12521
12522         else
12523            return Old_Type;
12524         end if;
12525      end Build_Constrained_Array_Type;
12526
12527      ------------------------------------------
12528      -- Build_Constrained_Discriminated_Type --
12529      ------------------------------------------
12530
12531      function Build_Constrained_Discriminated_Type
12532        (Old_Type : Entity_Id) return Entity_Id
12533      is
12534         Expr           : Node_Id;
12535         Constr_List    : List_Id;
12536         Old_Constraint : Elmt_Id;
12537
12538         Need_To_Create_Itype : Boolean := False;
12539
12540      begin
12541         Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
12542         while Present (Old_Constraint) loop
12543            Expr := Node (Old_Constraint);
12544
12545            if Is_Discriminant (Expr) then
12546               Need_To_Create_Itype := True;
12547            end if;
12548
12549            Next_Elmt (Old_Constraint);
12550         end loop;
12551
12552         if Need_To_Create_Itype then
12553            Constr_List := New_List;
12554
12555            Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
12556            while Present (Old_Constraint) loop
12557               Expr := Node (Old_Constraint);
12558
12559               if Is_Discriminant (Expr) then
12560                  Expr := Get_Discr_Value (Expr);
12561               end if;
12562
12563               Append (New_Copy_Tree (Expr), To => Constr_List);
12564
12565               Next_Elmt (Old_Constraint);
12566            end loop;
12567
12568            return Build_Subtype (Old_Type, Constr_List);
12569
12570         else
12571            return Old_Type;
12572         end if;
12573      end Build_Constrained_Discriminated_Type;
12574
12575      -------------------
12576      -- Build_Subtype --
12577      -------------------
12578
12579      function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
12580         Indic       : Node_Id;
12581         Subtyp_Decl : Node_Id;
12582         Def_Id      : Entity_Id;
12583         Btyp        : Entity_Id := Base_Type (T);
12584
12585      begin
12586         --  The Related_Node better be here or else we won't be able to
12587         --  attach new itypes to a node in the tree.
12588
12589         pragma Assert (Present (Related_Node));
12590
12591         --  If the view of the component's type is incomplete or private
12592         --  with unknown discriminants, then the constraint must be applied
12593         --  to the full type.
12594
12595         if Has_Unknown_Discriminants (Btyp)
12596           and then Present (Underlying_Type (Btyp))
12597         then
12598            Btyp := Underlying_Type (Btyp);
12599         end if;
12600
12601         Indic :=
12602           Make_Subtype_Indication (Loc,
12603             Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
12604             Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
12605
12606         Def_Id := Create_Itype (Ekind (T), Related_Node);
12607
12608         Subtyp_Decl :=
12609           Make_Subtype_Declaration (Loc,
12610             Defining_Identifier => Def_Id,
12611             Subtype_Indication  => Indic);
12612
12613         Set_Parent (Subtyp_Decl, Parent (Related_Node));
12614
12615         --  Itypes must be analyzed with checks off (see package Itypes)
12616
12617         Analyze (Subtyp_Decl, Suppress => All_Checks);
12618
12619         return Def_Id;
12620      end Build_Subtype;
12621
12622      ---------------------
12623      -- Get_Discr_Value --
12624      ---------------------
12625
12626      function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
12627         D : Entity_Id;
12628         E : Elmt_Id;
12629
12630      begin
12631         --  The discriminant may be declared for the type, in which case we
12632         --  find it by iterating over the list of discriminants. If the
12633         --  discriminant is inherited from a parent type, it appears as the
12634         --  corresponding discriminant of the current type. This will be the
12635         --  case when constraining an inherited component whose constraint is
12636         --  given by a discriminant of the parent.
12637
12638         D := First_Discriminant (Typ);
12639         E := First_Elmt (Constraints);
12640
12641         while Present (D) loop
12642            if D = Entity (Discrim)
12643              or else D = CR_Discriminant (Entity (Discrim))
12644              or else Corresponding_Discriminant (D) = Entity (Discrim)
12645            then
12646               return Node (E);
12647            end if;
12648
12649            Next_Discriminant (D);
12650            Next_Elmt (E);
12651         end loop;
12652
12653         --  The Corresponding_Discriminant mechanism is incomplete, because
12654         --  the correspondence between new and old discriminants is not one
12655         --  to one: one new discriminant can constrain several old ones. In
12656         --  that case, scan sequentially the stored_constraint, the list of
12657         --  discriminants of the parents, and the constraints.
12658
12659         --  Previous code checked for the present of the Stored_Constraint
12660         --  list for the derived type, but did not use it at all. Should it
12661         --  be present when the component is a discriminated task type?
12662
12663         if Is_Derived_Type (Typ)
12664           and then Scope (Entity (Discrim)) = Etype (Typ)
12665         then
12666            D := First_Discriminant (Etype (Typ));
12667            E := First_Elmt (Constraints);
12668            while Present (D) loop
12669               if D = Entity (Discrim) then
12670                  return Node (E);
12671               end if;
12672
12673               Next_Discriminant (D);
12674               Next_Elmt (E);
12675            end loop;
12676         end if;
12677
12678         --  Something is wrong if we did not find the value
12679
12680         raise Program_Error;
12681      end Get_Discr_Value;
12682
12683      ---------------------
12684      -- Is_Discriminant --
12685      ---------------------
12686
12687      function Is_Discriminant (Expr : Node_Id) return Boolean is
12688         Discrim_Scope : Entity_Id;
12689
12690      begin
12691         if Denotes_Discriminant (Expr) then
12692            Discrim_Scope := Scope (Entity (Expr));
12693
12694            --  Either we have a reference to one of Typ's discriminants,
12695
12696            pragma Assert (Discrim_Scope = Typ
12697
12698               --  or to the discriminants of the parent type, in the case
12699               --  of a derivation of a tagged type with variants.
12700
12701               or else Discrim_Scope = Etype (Typ)
12702               or else Full_View (Discrim_Scope) = Etype (Typ)
12703
12704               --  or same as above for the case where the discriminants
12705               --  were declared in Typ's private view.
12706
12707               or else (Is_Private_Type (Discrim_Scope)
12708                         and then Chars (Discrim_Scope) = Chars (Typ))
12709
12710               --  or else we are deriving from the full view and the
12711               --  discriminant is declared in the private entity.
12712
12713               or else (Is_Private_Type (Typ)
12714                         and then Chars (Discrim_Scope) = Chars (Typ))
12715
12716               --  Or we are constrained the corresponding record of a
12717               --  synchronized type that completes a private declaration.
12718
12719               or else (Is_Concurrent_Record_Type (Typ)
12720                         and then
12721                           Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
12722
12723               --  or we have a class-wide type, in which case make sure the
12724               --  discriminant found belongs to the root type.
12725
12726               or else (Is_Class_Wide_Type (Typ)
12727                         and then Etype (Typ) = Discrim_Scope));
12728
12729            return True;
12730         end if;
12731
12732         --  In all other cases we have something wrong
12733
12734         return False;
12735      end Is_Discriminant;
12736
12737   --  Start of processing for Constrain_Component_Type
12738
12739   begin
12740      if Nkind (Parent (Comp)) = N_Component_Declaration
12741        and then Comes_From_Source (Parent (Comp))
12742        and then Comes_From_Source
12743          (Subtype_Indication (Component_Definition (Parent (Comp))))
12744        and then
12745          Is_Entity_Name
12746            (Subtype_Indication (Component_Definition (Parent (Comp))))
12747      then
12748         return Compon_Type;
12749
12750      elsif Is_Array_Type (Compon_Type) then
12751         return Build_Constrained_Array_Type (Compon_Type);
12752
12753      elsif Has_Discriminants (Compon_Type) then
12754         return Build_Constrained_Discriminated_Type (Compon_Type);
12755
12756      elsif Is_Access_Type (Compon_Type) then
12757         return Build_Constrained_Access_Type (Compon_Type);
12758
12759      else
12760         return Compon_Type;
12761      end if;
12762   end Constrain_Component_Type;
12763
12764   --------------------------
12765   -- Constrain_Concurrent --
12766   --------------------------
12767
12768   --  For concurrent types, the associated record value type carries the same
12769   --  discriminants, so when we constrain a concurrent type, we must constrain
12770   --  the corresponding record type as well.
12771
12772   procedure Constrain_Concurrent
12773     (Def_Id      : in out Entity_Id;
12774      SI          : Node_Id;
12775      Related_Nod : Node_Id;
12776      Related_Id  : Entity_Id;
12777      Suffix      : Character)
12778   is
12779      --  Retrieve Base_Type to ensure getting to the concurrent type in the
12780      --  case of a private subtype (needed when only doing semantic analysis).
12781
12782      T_Ent : Entity_Id := Base_Type (Entity (Subtype_Mark (SI)));
12783      T_Val : Entity_Id;
12784
12785   begin
12786      if Is_Access_Type (T_Ent) then
12787         T_Ent := Designated_Type (T_Ent);
12788      end if;
12789
12790      T_Val := Corresponding_Record_Type (T_Ent);
12791
12792      if Present (T_Val) then
12793
12794         if No (Def_Id) then
12795            Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
12796         end if;
12797
12798         Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
12799
12800         Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
12801         Set_Corresponding_Record_Type (Def_Id,
12802           Constrain_Corresponding_Record (Def_Id, T_Val, Related_Nod));
12803
12804      else
12805         --  If there is no associated record, expansion is disabled and this
12806         --  is a generic context. Create a subtype in any case, so that
12807         --  semantic analysis can proceed.
12808
12809         if No (Def_Id) then
12810            Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
12811         end if;
12812
12813         Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
12814      end if;
12815   end Constrain_Concurrent;
12816
12817   ------------------------------------
12818   -- Constrain_Corresponding_Record --
12819   ------------------------------------
12820
12821   function Constrain_Corresponding_Record
12822     (Prot_Subt   : Entity_Id;
12823      Corr_Rec    : Entity_Id;
12824      Related_Nod : Node_Id) return Entity_Id
12825   is
12826      T_Sub : constant Entity_Id :=
12827                Create_Itype (E_Record_Subtype, Related_Nod, Corr_Rec, 'C');
12828
12829   begin
12830      Set_Etype             (T_Sub, Corr_Rec);
12831      Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
12832      Set_Is_Constrained    (T_Sub, True);
12833      Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
12834      Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
12835
12836      if Has_Discriminants (Prot_Subt) then -- False only if errors.
12837         Set_Discriminant_Constraint
12838           (T_Sub, Discriminant_Constraint (Prot_Subt));
12839         Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
12840         Create_Constrained_Components
12841           (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
12842      end if;
12843
12844      Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
12845
12846      if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
12847         Conditional_Delay (T_Sub, Corr_Rec);
12848
12849      else
12850         --  This is a component subtype: it will be frozen in the context of
12851         --  the enclosing record's init_proc, so that discriminant references
12852         --  are resolved to discriminals. (Note: we used to skip freezing
12853         --  altogether in that case, which caused errors downstream for
12854         --  components of a bit packed array type).
12855
12856         Set_Has_Delayed_Freeze (T_Sub);
12857      end if;
12858
12859      return T_Sub;
12860   end Constrain_Corresponding_Record;
12861
12862   -----------------------
12863   -- Constrain_Decimal --
12864   -----------------------
12865
12866   procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
12867      T           : constant Entity_Id  := Entity (Subtype_Mark (S));
12868      C           : constant Node_Id    := Constraint (S);
12869      Loc         : constant Source_Ptr := Sloc (C);
12870      Range_Expr  : Node_Id;
12871      Digits_Expr : Node_Id;
12872      Digits_Val  : Uint;
12873      Bound_Val   : Ureal;
12874
12875   begin
12876      Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
12877
12878      if Nkind (C) = N_Range_Constraint then
12879         Range_Expr := Range_Expression (C);
12880         Digits_Val := Digits_Value (T);
12881
12882      else
12883         pragma Assert (Nkind (C) = N_Digits_Constraint);
12884
12885         Check_SPARK_05_Restriction ("digits constraint is not allowed", S);
12886
12887         Digits_Expr := Digits_Expression (C);
12888         Analyze_And_Resolve (Digits_Expr, Any_Integer);
12889
12890         Check_Digits_Expression (Digits_Expr);
12891         Digits_Val := Expr_Value (Digits_Expr);
12892
12893         if Digits_Val > Digits_Value (T) then
12894            Error_Msg_N
12895               ("digits expression is incompatible with subtype", C);
12896            Digits_Val := Digits_Value (T);
12897         end if;
12898
12899         if Present (Range_Constraint (C)) then
12900            Range_Expr := Range_Expression (Range_Constraint (C));
12901         else
12902            Range_Expr := Empty;
12903         end if;
12904      end if;
12905
12906      Set_Etype            (Def_Id, Base_Type        (T));
12907      Set_Size_Info        (Def_Id,                  (T));
12908      Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
12909      Set_Delta_Value      (Def_Id, Delta_Value      (T));
12910      Set_Scale_Value      (Def_Id, Scale_Value      (T));
12911      Set_Small_Value      (Def_Id, Small_Value      (T));
12912      Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
12913      Set_Digits_Value     (Def_Id, Digits_Val);
12914
12915      --  Manufacture range from given digits value if no range present
12916
12917      if No (Range_Expr) then
12918         Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
12919         Range_Expr :=
12920           Make_Range (Loc,
12921             Low_Bound =>
12922               Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
12923             High_Bound =>
12924               Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
12925      end if;
12926
12927      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
12928      Set_Discrete_RM_Size (Def_Id);
12929
12930      --  Unconditionally delay the freeze, since we cannot set size
12931      --  information in all cases correctly until the freeze point.
12932
12933      Set_Has_Delayed_Freeze (Def_Id);
12934   end Constrain_Decimal;
12935
12936   ----------------------------------
12937   -- Constrain_Discriminated_Type --
12938   ----------------------------------
12939
12940   procedure Constrain_Discriminated_Type
12941     (Def_Id      : Entity_Id;
12942      S           : Node_Id;
12943      Related_Nod : Node_Id;
12944      For_Access  : Boolean := False)
12945   is
12946      E     : constant Entity_Id := Entity (Subtype_Mark (S));
12947      T     : Entity_Id;
12948      C     : Node_Id;
12949      Elist : Elist_Id := New_Elmt_List;
12950
12951      procedure Fixup_Bad_Constraint;
12952      --  This is called after finding a bad constraint, and after having
12953      --  posted an appropriate error message. The mission is to leave the
12954      --  entity T in as reasonable state as possible.
12955
12956      --------------------------
12957      -- Fixup_Bad_Constraint --
12958      --------------------------
12959
12960      procedure Fixup_Bad_Constraint is
12961      begin
12962         --  Set a reasonable Ekind for the entity. For an incomplete type,
12963         --  we can't do much, but for other types, we can set the proper
12964         --  corresponding subtype kind.
12965
12966         if Ekind (T) = E_Incomplete_Type then
12967            Set_Ekind (Def_Id, Ekind (T));
12968         else
12969            Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
12970         end if;
12971
12972         --  Set Etype to the known type, to reduce chances of cascaded errors
12973
12974         Set_Etype (Def_Id, E);
12975         Set_Error_Posted (Def_Id);
12976      end Fixup_Bad_Constraint;
12977
12978   --  Start of processing for Constrain_Discriminated_Type
12979
12980   begin
12981      C := Constraint (S);
12982
12983      --  A discriminant constraint is only allowed in a subtype indication,
12984      --  after a subtype mark. This subtype mark must denote either a type
12985      --  with discriminants, or an access type whose designated type is a
12986      --  type with discriminants. A discriminant constraint specifies the
12987      --  values of these discriminants (RM 3.7.2(5)).
12988
12989      T := Base_Type (Entity (Subtype_Mark (S)));
12990
12991      if Is_Access_Type (T) then
12992         T := Designated_Type (T);
12993      end if;
12994
12995      --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
12996      --  Avoid generating an error for access-to-incomplete subtypes.
12997
12998      if Ada_Version >= Ada_2005
12999        and then Ekind (T) = E_Incomplete_Type
13000        and then Nkind (Parent (S)) = N_Subtype_Declaration
13001        and then not Is_Itype (Def_Id)
13002      then
13003         --  A little sanity check, emit an error message if the type
13004         --  has discriminants to begin with. Type T may be a regular
13005         --  incomplete type or imported via a limited with clause.
13006
13007         if Has_Discriminants (T)
13008           or else (From_Limited_With (T)
13009                     and then Present (Non_Limited_View (T))
13010                     and then Nkind (Parent (Non_Limited_View (T))) =
13011                                               N_Full_Type_Declaration
13012                     and then Present (Discriminant_Specifications
13013                                         (Parent (Non_Limited_View (T)))))
13014         then
13015            Error_Msg_N
13016              ("(Ada 2005) incomplete subtype may not be constrained", C);
13017         else
13018            Error_Msg_N ("invalid constraint: type has no discriminant", C);
13019         end if;
13020
13021         Fixup_Bad_Constraint;
13022         return;
13023
13024      --  Check that the type has visible discriminants. The type may be
13025      --  a private type with unknown discriminants whose full view has
13026      --  discriminants which are invisible.
13027
13028      elsif not Has_Discriminants (T)
13029        or else
13030          (Has_Unknown_Discriminants (T)
13031             and then Is_Private_Type (T))
13032      then
13033         Error_Msg_N ("invalid constraint: type has no discriminant", C);
13034         Fixup_Bad_Constraint;
13035         return;
13036
13037      elsif Is_Constrained (E)
13038        or else (Ekind (E) = E_Class_Wide_Subtype
13039                  and then Present (Discriminant_Constraint (E)))
13040      then
13041         Error_Msg_N ("type is already constrained", Subtype_Mark (S));
13042         Fixup_Bad_Constraint;
13043         return;
13044      end if;
13045
13046      --  T may be an unconstrained subtype (e.g. a generic actual).
13047      --  Constraint applies to the base type.
13048
13049      T := Base_Type (T);
13050
13051      Elist := Build_Discriminant_Constraints (T, S);
13052
13053      --  If the list returned was empty we had an error in building the
13054      --  discriminant constraint. We have also already signalled an error
13055      --  in the incomplete type case
13056
13057      if Is_Empty_Elmt_List (Elist) then
13058         Fixup_Bad_Constraint;
13059         return;
13060      end if;
13061
13062      Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
13063   end Constrain_Discriminated_Type;
13064
13065   ---------------------------
13066   -- Constrain_Enumeration --
13067   ---------------------------
13068
13069   procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
13070      T : constant Entity_Id := Entity (Subtype_Mark (S));
13071      C : constant Node_Id   := Constraint (S);
13072
13073   begin
13074      Set_Ekind (Def_Id, E_Enumeration_Subtype);
13075
13076      Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
13077
13078      Set_Etype             (Def_Id, Base_Type         (T));
13079      Set_Size_Info         (Def_Id,                   (T));
13080      Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
13081      Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
13082
13083      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13084
13085      Set_Discrete_RM_Size (Def_Id);
13086   end Constrain_Enumeration;
13087
13088   ----------------------
13089   -- Constrain_Float --
13090   ----------------------
13091
13092   procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
13093      T    : constant Entity_Id := Entity (Subtype_Mark (S));
13094      C    : Node_Id;
13095      D    : Node_Id;
13096      Rais : Node_Id;
13097
13098   begin
13099      Set_Ekind (Def_Id, E_Floating_Point_Subtype);
13100
13101      Set_Etype          (Def_Id, Base_Type      (T));
13102      Set_Size_Info      (Def_Id,                (T));
13103      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
13104
13105      --  Process the constraint
13106
13107      C := Constraint (S);
13108
13109      --  Digits constraint present
13110
13111      if Nkind (C) = N_Digits_Constraint then
13112
13113         Check_SPARK_05_Restriction ("digits constraint is not allowed", S);
13114         Check_Restriction (No_Obsolescent_Features, C);
13115
13116         if Warn_On_Obsolescent_Feature then
13117            Error_Msg_N
13118              ("subtype digits constraint is an " &
13119               "obsolescent feature (RM J.3(8))?j?", C);
13120         end if;
13121
13122         D := Digits_Expression (C);
13123         Analyze_And_Resolve (D, Any_Integer);
13124         Check_Digits_Expression (D);
13125         Set_Digits_Value (Def_Id, Expr_Value (D));
13126
13127         --  Check that digits value is in range. Obviously we can do this
13128         --  at compile time, but it is strictly a runtime check, and of
13129         --  course there is an ACVC test that checks this.
13130
13131         if Digits_Value (Def_Id) > Digits_Value (T) then
13132            Error_Msg_Uint_1 := Digits_Value (T);
13133            Error_Msg_N ("??digits value is too large, maximum is ^", D);
13134            Rais :=
13135              Make_Raise_Constraint_Error (Sloc (D),
13136                Reason => CE_Range_Check_Failed);
13137            Insert_Action (Declaration_Node (Def_Id), Rais);
13138         end if;
13139
13140         C := Range_Constraint (C);
13141
13142      --  No digits constraint present
13143
13144      else
13145         Set_Digits_Value (Def_Id, Digits_Value (T));
13146      end if;
13147
13148      --  Range constraint present
13149
13150      if Nkind (C) = N_Range_Constraint then
13151         Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13152
13153      --  No range constraint present
13154
13155      else
13156         pragma Assert (No (C));
13157         Set_Scalar_Range (Def_Id, Scalar_Range (T));
13158      end if;
13159
13160      Set_Is_Constrained (Def_Id);
13161   end Constrain_Float;
13162
13163   ---------------------
13164   -- Constrain_Index --
13165   ---------------------
13166
13167   procedure Constrain_Index
13168     (Index        : Node_Id;
13169      S            : Node_Id;
13170      Related_Nod  : Node_Id;
13171      Related_Id   : Entity_Id;
13172      Suffix       : Character;
13173      Suffix_Index : Nat)
13174   is
13175      Def_Id : Entity_Id;
13176      R      : Node_Id := Empty;
13177      T      : constant Entity_Id := Etype (Index);
13178
13179   begin
13180      Def_Id :=
13181        Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
13182      Set_Etype (Def_Id, Base_Type (T));
13183
13184      if Nkind (S) = N_Range
13185        or else
13186          (Nkind (S) = N_Attribute_Reference
13187            and then Attribute_Name (S) = Name_Range)
13188      then
13189         --  A Range attribute will be transformed into N_Range by Resolve
13190
13191         Analyze (S);
13192         Set_Etype (S, T);
13193         R := S;
13194
13195         Process_Range_Expr_In_Decl (R, T);
13196
13197         if not Error_Posted (S)
13198           and then
13199             (Nkind (S) /= N_Range
13200               or else not Covers (T, (Etype (Low_Bound (S))))
13201               or else not Covers (T, (Etype (High_Bound (S)))))
13202         then
13203            if Base_Type (T) /= Any_Type
13204              and then Etype (Low_Bound (S)) /= Any_Type
13205              and then Etype (High_Bound (S)) /= Any_Type
13206            then
13207               Error_Msg_N ("range expected", S);
13208            end if;
13209         end if;
13210
13211      elsif Nkind (S) = N_Subtype_Indication then
13212
13213         --  The parser has verified that this is a discrete indication
13214
13215         Resolve_Discrete_Subtype_Indication (S, T);
13216         Bad_Predicated_Subtype_Use
13217           ("subtype& has predicate, not allowed in index constraint",
13218            S, Entity (Subtype_Mark (S)));
13219
13220         R := Range_Expression (Constraint (S));
13221
13222         --  Capture values of bounds and generate temporaries for them if
13223         --  needed, since checks may cause duplication of the expressions
13224         --  which must not be reevaluated.
13225
13226         --  The forced evaluation removes side effects from expressions, which
13227         --  should occur also in GNATprove mode. Otherwise, we end up with
13228         --  unexpected insertions of actions at places where this is not
13229         --  supposed to occur, e.g. on default parameters of a call.
13230
13231         if Expander_Active or GNATprove_Mode then
13232            Force_Evaluation
13233              (Low_Bound (R),  Related_Id => Def_Id, Is_Low_Bound  => True);
13234            Force_Evaluation
13235              (High_Bound (R), Related_Id => Def_Id, Is_High_Bound => True);
13236         end if;
13237
13238      elsif Nkind (S) = N_Discriminant_Association then
13239
13240         --  Syntactically valid in subtype indication
13241
13242         Error_Msg_N ("invalid index constraint", S);
13243         Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
13244         return;
13245
13246      --  Subtype_Mark case, no anonymous subtypes to construct
13247
13248      else
13249         Analyze (S);
13250
13251         if Is_Entity_Name (S) then
13252            if not Is_Type (Entity (S)) then
13253               Error_Msg_N ("expect subtype mark for index constraint", S);
13254
13255            elsif Base_Type (Entity (S)) /= Base_Type (T) then
13256               Wrong_Type (S, Base_Type (T));
13257
13258            --  Check error of subtype with predicate in index constraint
13259
13260            else
13261               Bad_Predicated_Subtype_Use
13262                 ("subtype& has predicate, not allowed in index constraint",
13263                  S, Entity (S));
13264            end if;
13265
13266            return;
13267
13268         else
13269            Error_Msg_N ("invalid index constraint", S);
13270            Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
13271            return;
13272         end if;
13273      end if;
13274
13275      --  Complete construction of the Itype
13276
13277      if Is_Modular_Integer_Type (T) then
13278         Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
13279
13280      elsif Is_Integer_Type (T) then
13281         Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
13282
13283      else
13284         Set_Ekind (Def_Id, E_Enumeration_Subtype);
13285         Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
13286         Set_First_Literal     (Def_Id, First_Literal (T));
13287      end if;
13288
13289      Set_Size_Info      (Def_Id,                (T));
13290      Set_RM_Size        (Def_Id, RM_Size        (T));
13291      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
13292
13293      Set_Scalar_Range   (Def_Id, R);
13294
13295      Set_Etype (S, Def_Id);
13296      Set_Discrete_RM_Size (Def_Id);
13297   end Constrain_Index;
13298
13299   -----------------------
13300   -- Constrain_Integer --
13301   -----------------------
13302
13303   procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
13304      T : constant Entity_Id := Entity (Subtype_Mark (S));
13305      C : constant Node_Id   := Constraint (S);
13306
13307   begin
13308      Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13309
13310      if Is_Modular_Integer_Type (T) then
13311         Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
13312      else
13313         Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
13314      end if;
13315
13316      Set_Etype            (Def_Id, Base_Type      (T));
13317      Set_Size_Info        (Def_Id,                (T));
13318      Set_First_Rep_Item   (Def_Id, First_Rep_Item (T));
13319      Set_Discrete_RM_Size (Def_Id);
13320   end Constrain_Integer;
13321
13322   ------------------------------
13323   -- Constrain_Ordinary_Fixed --
13324   ------------------------------
13325
13326   procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
13327      T    : constant Entity_Id := Entity (Subtype_Mark (S));
13328      C    : Node_Id;
13329      D    : Node_Id;
13330      Rais : Node_Id;
13331
13332   begin
13333      Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
13334      Set_Etype          (Def_Id, Base_Type      (T));
13335      Set_Size_Info      (Def_Id,                (T));
13336      Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
13337      Set_Small_Value    (Def_Id, Small_Value    (T));
13338
13339      --  Process the constraint
13340
13341      C := Constraint (S);
13342
13343      --  Delta constraint present
13344
13345      if Nkind (C) = N_Delta_Constraint then
13346
13347         Check_SPARK_05_Restriction ("delta constraint is not allowed", S);
13348         Check_Restriction (No_Obsolescent_Features, C);
13349
13350         if Warn_On_Obsolescent_Feature then
13351            Error_Msg_S
13352              ("subtype delta constraint is an " &
13353               "obsolescent feature (RM J.3(7))?j?");
13354         end if;
13355
13356         D := Delta_Expression (C);
13357         Analyze_And_Resolve (D, Any_Real);
13358         Check_Delta_Expression (D);
13359         Set_Delta_Value (Def_Id, Expr_Value_R (D));
13360
13361         --  Check that delta value is in range. Obviously we can do this
13362         --  at compile time, but it is strictly a runtime check, and of
13363         --  course there is an ACVC test that checks this.
13364
13365         if Delta_Value (Def_Id) < Delta_Value (T) then
13366            Error_Msg_N ("??delta value is too small", D);
13367            Rais :=
13368              Make_Raise_Constraint_Error (Sloc (D),
13369                Reason => CE_Range_Check_Failed);
13370            Insert_Action (Declaration_Node (Def_Id), Rais);
13371         end if;
13372
13373         C := Range_Constraint (C);
13374
13375      --  No delta constraint present
13376
13377      else
13378         Set_Delta_Value (Def_Id, Delta_Value (T));
13379      end if;
13380
13381      --  Range constraint present
13382
13383      if Nkind (C) = N_Range_Constraint then
13384         Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13385
13386      --  No range constraint present
13387
13388      else
13389         pragma Assert (No (C));
13390         Set_Scalar_Range (Def_Id, Scalar_Range (T));
13391      end if;
13392
13393      Set_Discrete_RM_Size (Def_Id);
13394
13395      --  Unconditionally delay the freeze, since we cannot set size
13396      --  information in all cases correctly until the freeze point.
13397
13398      Set_Has_Delayed_Freeze (Def_Id);
13399   end Constrain_Ordinary_Fixed;
13400
13401   -----------------------
13402   -- Contain_Interface --
13403   -----------------------
13404
13405   function Contain_Interface
13406     (Iface  : Entity_Id;
13407      Ifaces : Elist_Id) return Boolean
13408   is
13409      Iface_Elmt : Elmt_Id;
13410
13411   begin
13412      if Present (Ifaces) then
13413         Iface_Elmt := First_Elmt (Ifaces);
13414         while Present (Iface_Elmt) loop
13415            if Node (Iface_Elmt) = Iface then
13416               return True;
13417            end if;
13418
13419            Next_Elmt (Iface_Elmt);
13420         end loop;
13421      end if;
13422
13423      return False;
13424   end Contain_Interface;
13425
13426   ---------------------------
13427   -- Convert_Scalar_Bounds --
13428   ---------------------------
13429
13430   procedure Convert_Scalar_Bounds
13431     (N            : Node_Id;
13432      Parent_Type  : Entity_Id;
13433      Derived_Type : Entity_Id;
13434      Loc          : Source_Ptr)
13435   is
13436      Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
13437
13438      Lo  : Node_Id;
13439      Hi  : Node_Id;
13440      Rng : Node_Id;
13441
13442   begin
13443      --  Defend against previous errors
13444
13445      if No (Scalar_Range (Derived_Type)) then
13446         Check_Error_Detected;
13447         return;
13448      end if;
13449
13450      Lo := Build_Scalar_Bound
13451              (Type_Low_Bound (Derived_Type),
13452               Parent_Type, Implicit_Base);
13453
13454      Hi := Build_Scalar_Bound
13455              (Type_High_Bound (Derived_Type),
13456               Parent_Type, Implicit_Base);
13457
13458      Rng :=
13459        Make_Range (Loc,
13460          Low_Bound  => Lo,
13461          High_Bound => Hi);
13462
13463      Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
13464
13465      Set_Parent (Rng, N);
13466      Set_Scalar_Range (Derived_Type, Rng);
13467
13468      --  Analyze the bounds
13469
13470      Analyze_And_Resolve (Lo, Implicit_Base);
13471      Analyze_And_Resolve (Hi, Implicit_Base);
13472
13473      --  Analyze the range itself, except that we do not analyze it if
13474      --  the bounds are real literals, and we have a fixed-point type.
13475      --  The reason for this is that we delay setting the bounds in this
13476      --  case till we know the final Small and Size values (see circuit
13477      --  in Freeze.Freeze_Fixed_Point_Type for further details).
13478
13479      if Is_Fixed_Point_Type (Parent_Type)
13480        and then Nkind (Lo) = N_Real_Literal
13481        and then Nkind (Hi) = N_Real_Literal
13482      then
13483         return;
13484
13485      --  Here we do the analysis of the range
13486
13487      --  Note: we do this manually, since if we do a normal Analyze and
13488      --  Resolve call, there are problems with the conversions used for
13489      --  the derived type range.
13490
13491      else
13492         Set_Etype    (Rng, Implicit_Base);
13493         Set_Analyzed (Rng, True);
13494      end if;
13495   end Convert_Scalar_Bounds;
13496
13497   -------------------
13498   -- Copy_And_Swap --
13499   -------------------
13500
13501   procedure Copy_And_Swap (Priv, Full : Entity_Id) is
13502   begin
13503      --  Initialize new full declaration entity by copying the pertinent
13504      --  fields of the corresponding private declaration entity.
13505
13506      --  We temporarily set Ekind to a value appropriate for a type to
13507      --  avoid assert failures in Einfo from checking for setting type
13508      --  attributes on something that is not a type. Ekind (Priv) is an
13509      --  appropriate choice, since it allowed the attributes to be set
13510      --  in the first place. This Ekind value will be modified later.
13511
13512      Set_Ekind (Full, Ekind (Priv));
13513
13514      --  Also set Etype temporarily to Any_Type, again, in the absence
13515      --  of errors, it will be properly reset, and if there are errors,
13516      --  then we want a value of Any_Type to remain.
13517
13518      Set_Etype (Full, Any_Type);
13519
13520      --  Now start copying attributes
13521
13522      Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
13523
13524      if Has_Discriminants (Full) then
13525         Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
13526         Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
13527      end if;
13528
13529      Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
13530      Set_Homonym                    (Full, Homonym                 (Priv));
13531      Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
13532      Set_Is_Public                  (Full, Is_Public               (Priv));
13533      Set_Is_Pure                    (Full, Is_Pure                 (Priv));
13534      Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
13535      Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
13536      Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
13537      Set_Has_Pragma_Unreferenced_Objects
13538                                     (Full, Has_Pragma_Unreferenced_Objects
13539                                                                    (Priv));
13540
13541      Conditional_Delay              (Full,                          Priv);
13542
13543      if Is_Tagged_Type (Full) then
13544         Set_Direct_Primitive_Operations
13545           (Full, Direct_Primitive_Operations (Priv));
13546         Set_No_Tagged_Streams_Pragma
13547           (Full, No_Tagged_Streams_Pragma (Priv));
13548
13549         if Is_Base_Type (Priv) then
13550            Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
13551         end if;
13552      end if;
13553
13554      Set_Is_Volatile                (Full, Is_Volatile             (Priv));
13555      Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
13556      Set_Scope                      (Full, Scope                   (Priv));
13557      Set_Next_Entity                (Full, Next_Entity             (Priv));
13558      Set_First_Entity               (Full, First_Entity            (Priv));
13559      Set_Last_Entity                (Full, Last_Entity             (Priv));
13560
13561      --  If access types have been recorded for later handling, keep them in
13562      --  the full view so that they get handled when the full view freeze
13563      --  node is expanded.
13564
13565      if Present (Freeze_Node (Priv))
13566        and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
13567      then
13568         Ensure_Freeze_Node (Full);
13569         Set_Access_Types_To_Process
13570           (Freeze_Node (Full),
13571            Access_Types_To_Process (Freeze_Node (Priv)));
13572      end if;
13573
13574      --  Swap the two entities. Now Private is the full type entity and Full
13575      --  is the private one. They will be swapped back at the end of the
13576      --  private part. This swapping ensures that the entity that is visible
13577      --  in the private part is the full declaration.
13578
13579      Exchange_Entities (Priv, Full);
13580      Append_Entity (Full, Scope (Full));
13581   end Copy_And_Swap;
13582
13583   -------------------------------------
13584   -- Copy_Array_Base_Type_Attributes --
13585   -------------------------------------
13586
13587   procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
13588   begin
13589      Set_Component_Alignment      (T1, Component_Alignment      (T2));
13590      Set_Component_Type           (T1, Component_Type           (T2));
13591      Set_Component_Size           (T1, Component_Size           (T2));
13592      Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
13593      Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
13594      Set_Has_Protected            (T1, Has_Protected            (T2));
13595      Set_Has_Task                 (T1, Has_Task                 (T2));
13596      Set_Is_Packed                (T1, Is_Packed                (T2));
13597      Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
13598      Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
13599      Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
13600   end Copy_Array_Base_Type_Attributes;
13601
13602   -----------------------------------
13603   -- Copy_Array_Subtype_Attributes --
13604   -----------------------------------
13605
13606   procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
13607   begin
13608      Set_Size_Info (T1, T2);
13609
13610      Set_First_Index            (T1, First_Index            (T2));
13611      Set_Is_Aliased             (T1, Is_Aliased             (T2));
13612      Set_Is_Volatile            (T1, Is_Volatile            (T2));
13613      Set_Treat_As_Volatile      (T1, Treat_As_Volatile      (T2));
13614      Set_Is_Constrained         (T1, Is_Constrained         (T2));
13615      Set_Depends_On_Private     (T1, Has_Private_Component  (T2));
13616      Inherit_Rep_Item_Chain     (T1,                         T2);
13617      Set_Convention             (T1, Convention             (T2));
13618      Set_Is_Limited_Composite   (T1, Is_Limited_Composite   (T2));
13619      Set_Is_Private_Composite   (T1, Is_Private_Composite   (T2));
13620      Set_Packed_Array_Impl_Type (T1, Packed_Array_Impl_Type (T2));
13621   end Copy_Array_Subtype_Attributes;
13622
13623   -----------------------------------
13624   -- Create_Constrained_Components --
13625   -----------------------------------
13626
13627   procedure Create_Constrained_Components
13628     (Subt        : Entity_Id;
13629      Decl_Node   : Node_Id;
13630      Typ         : Entity_Id;
13631      Constraints : Elist_Id)
13632   is
13633      Loc         : constant Source_Ptr := Sloc (Subt);
13634      Comp_List   : constant Elist_Id   := New_Elmt_List;
13635      Parent_Type : constant Entity_Id  := Etype (Typ);
13636      Assoc_List  : constant List_Id    := New_List;
13637      Discr_Val   : Elmt_Id;
13638      Errors      : Boolean;
13639      New_C       : Entity_Id;
13640      Old_C       : Entity_Id;
13641      Is_Static   : Boolean := True;
13642
13643      procedure Collect_Fixed_Components (Typ : Entity_Id);
13644      --  Collect parent type components that do not appear in a variant part
13645
13646      procedure Create_All_Components;
13647      --  Iterate over Comp_List to create the components of the subtype
13648
13649      function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
13650      --  Creates a new component from Old_Compon, copying all the fields from
13651      --  it, including its Etype, inserts the new component in the Subt entity
13652      --  chain and returns the new component.
13653
13654      function Is_Variant_Record (T : Entity_Id) return Boolean;
13655      --  If true, and discriminants are static, collect only components from
13656      --  variants selected by discriminant values.
13657
13658      ------------------------------
13659      -- Collect_Fixed_Components --
13660      ------------------------------
13661
13662      procedure Collect_Fixed_Components (Typ : Entity_Id) is
13663      begin
13664      --  Build association list for discriminants, and find components of the
13665      --  variant part selected by the values of the discriminants.
13666
13667         Old_C := First_Discriminant (Typ);
13668         Discr_Val := First_Elmt (Constraints);
13669         while Present (Old_C) loop
13670            Append_To (Assoc_List,
13671              Make_Component_Association (Loc,
13672                 Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
13673                 Expression => New_Copy (Node (Discr_Val))));
13674
13675            Next_Elmt (Discr_Val);
13676            Next_Discriminant (Old_C);
13677         end loop;
13678
13679         --  The tag and the possible parent component are unconditionally in
13680         --  the subtype.
13681
13682         if Is_Tagged_Type (Typ) or else Has_Controlled_Component (Typ) then
13683            Old_C := First_Component (Typ);
13684            while Present (Old_C) loop
13685               if Nam_In (Chars (Old_C), Name_uTag, Name_uParent) then
13686                  Append_Elmt (Old_C, Comp_List);
13687               end if;
13688
13689               Next_Component (Old_C);
13690            end loop;
13691         end if;
13692      end Collect_Fixed_Components;
13693
13694      ---------------------------
13695      -- Create_All_Components --
13696      ---------------------------
13697
13698      procedure Create_All_Components is
13699         Comp : Elmt_Id;
13700
13701      begin
13702         Comp := First_Elmt (Comp_List);
13703         while Present (Comp) loop
13704            Old_C := Node (Comp);
13705            New_C := Create_Component (Old_C);
13706
13707            Set_Etype
13708              (New_C,
13709               Constrain_Component_Type
13710                 (Old_C, Subt, Decl_Node, Typ, Constraints));
13711            Set_Is_Public (New_C, Is_Public (Subt));
13712
13713            Next_Elmt (Comp);
13714         end loop;
13715      end Create_All_Components;
13716
13717      ----------------------
13718      -- Create_Component --
13719      ----------------------
13720
13721      function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
13722         New_Compon : constant Entity_Id := New_Copy (Old_Compon);
13723
13724      begin
13725         if Ekind (Old_Compon) = E_Discriminant
13726           and then Is_Completely_Hidden (Old_Compon)
13727         then
13728            --  This is a shadow discriminant created for a discriminant of
13729            --  the parent type, which needs to be present in the subtype.
13730            --  Give the shadow discriminant an internal name that cannot
13731            --  conflict with that of visible components.
13732
13733            Set_Chars (New_Compon, New_Internal_Name ('C'));
13734         end if;
13735
13736         --  Set the parent so we have a proper link for freezing etc. This is
13737         --  not a real parent pointer, since of course our parent does not own
13738         --  up to us and reference us, we are an illegitimate child of the
13739         --  original parent.
13740
13741         Set_Parent (New_Compon, Parent (Old_Compon));
13742
13743         --  If the old component's Esize was already determined and is a
13744         --  static value, then the new component simply inherits it. Otherwise
13745         --  the old component's size may require run-time determination, but
13746         --  the new component's size still might be statically determinable
13747         --  (if, for example it has a static constraint). In that case we want
13748         --  Layout_Type to recompute the component's size, so we reset its
13749         --  size and positional fields.
13750
13751         if Frontend_Layout_On_Target
13752           and then not Known_Static_Esize (Old_Compon)
13753         then
13754            Set_Esize (New_Compon, Uint_0);
13755            Init_Normalized_First_Bit    (New_Compon);
13756            Init_Normalized_Position     (New_Compon);
13757            Init_Normalized_Position_Max (New_Compon);
13758         end if;
13759
13760         --  We do not want this node marked as Comes_From_Source, since
13761         --  otherwise it would get first class status and a separate cross-
13762         --  reference line would be generated. Illegitimate children do not
13763         --  rate such recognition.
13764
13765         Set_Comes_From_Source (New_Compon, False);
13766
13767         --  But it is a real entity, and a birth certificate must be properly
13768         --  registered by entering it into the entity list.
13769
13770         Enter_Name (New_Compon);
13771
13772         return New_Compon;
13773      end Create_Component;
13774
13775      -----------------------
13776      -- Is_Variant_Record --
13777      -----------------------
13778
13779      function Is_Variant_Record (T : Entity_Id) return Boolean is
13780      begin
13781         return Nkind (Parent (T)) = N_Full_Type_Declaration
13782           and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
13783           and then Present (Component_List (Type_Definition (Parent (T))))
13784           and then
13785             Present
13786               (Variant_Part (Component_List (Type_Definition (Parent (T)))));
13787      end Is_Variant_Record;
13788
13789   --  Start of processing for Create_Constrained_Components
13790
13791   begin
13792      pragma Assert (Subt /= Base_Type (Subt));
13793      pragma Assert (Typ = Base_Type (Typ));
13794
13795      Set_First_Entity (Subt, Empty);
13796      Set_Last_Entity  (Subt, Empty);
13797
13798      --  Check whether constraint is fully static, in which case we can
13799      --  optimize the list of components.
13800
13801      Discr_Val := First_Elmt (Constraints);
13802      while Present (Discr_Val) loop
13803         if not Is_OK_Static_Expression (Node (Discr_Val)) then
13804            Is_Static := False;
13805            exit;
13806         end if;
13807
13808         Next_Elmt (Discr_Val);
13809      end loop;
13810
13811      Set_Has_Static_Discriminants (Subt, Is_Static);
13812
13813      Push_Scope (Subt);
13814
13815      --  Inherit the discriminants of the parent type
13816
13817      Add_Discriminants : declare
13818         Num_Disc : Int;
13819         Num_Gird : Int;
13820
13821      begin
13822         Num_Disc := 0;
13823         Old_C := First_Discriminant (Typ);
13824
13825         while Present (Old_C) loop
13826            Num_Disc := Num_Disc + 1;
13827            New_C := Create_Component (Old_C);
13828            Set_Is_Public (New_C, Is_Public (Subt));
13829            Next_Discriminant (Old_C);
13830         end loop;
13831
13832         --  For an untagged derived subtype, the number of discriminants may
13833         --  be smaller than the number of inherited discriminants, because
13834         --  several of them may be renamed by a single new discriminant or
13835         --  constrained. In this case, add the hidden discriminants back into
13836         --  the subtype, because they need to be present if the optimizer of
13837         --  the GCC 4.x back-end decides to break apart assignments between
13838         --  objects using the parent view into member-wise assignments.
13839
13840         Num_Gird := 0;
13841
13842         if Is_Derived_Type (Typ)
13843           and then not Is_Tagged_Type (Typ)
13844         then
13845            Old_C := First_Stored_Discriminant (Typ);
13846
13847            while Present (Old_C) loop
13848               Num_Gird := Num_Gird + 1;
13849               Next_Stored_Discriminant (Old_C);
13850            end loop;
13851         end if;
13852
13853         if Num_Gird > Num_Disc then
13854
13855            --  Find out multiple uses of new discriminants, and add hidden
13856            --  components for the extra renamed discriminants. We recognize
13857            --  multiple uses through the Corresponding_Discriminant of a
13858            --  new discriminant: if it constrains several old discriminants,
13859            --  this field points to the last one in the parent type. The
13860            --  stored discriminants of the derived type have the same name
13861            --  as those of the parent.
13862
13863            declare
13864               Constr    : Elmt_Id;
13865               New_Discr : Entity_Id;
13866               Old_Discr : Entity_Id;
13867
13868            begin
13869               Constr    := First_Elmt (Stored_Constraint (Typ));
13870               Old_Discr := First_Stored_Discriminant (Typ);
13871               while Present (Constr) loop
13872                  if Is_Entity_Name (Node (Constr))
13873                    and then Ekind (Entity (Node (Constr))) = E_Discriminant
13874                  then
13875                     New_Discr := Entity (Node (Constr));
13876
13877                     if Chars (Corresponding_Discriminant (New_Discr)) /=
13878                        Chars (Old_Discr)
13879                     then
13880                        --  The new discriminant has been used to rename a
13881                        --  subsequent old discriminant. Introduce a shadow
13882                        --  component for the current old discriminant.
13883
13884                        New_C := Create_Component (Old_Discr);
13885                        Set_Original_Record_Component (New_C, Old_Discr);
13886                     end if;
13887
13888                  else
13889                     --  The constraint has eliminated the old discriminant.
13890                     --  Introduce a shadow component.
13891
13892                     New_C := Create_Component (Old_Discr);
13893                     Set_Original_Record_Component (New_C, Old_Discr);
13894                  end if;
13895
13896                  Next_Elmt (Constr);
13897                  Next_Stored_Discriminant (Old_Discr);
13898               end loop;
13899            end;
13900         end if;
13901      end Add_Discriminants;
13902
13903      if Is_Static
13904        and then Is_Variant_Record (Typ)
13905      then
13906         Collect_Fixed_Components (Typ);
13907
13908         Gather_Components (
13909           Typ,
13910           Component_List (Type_Definition (Parent (Typ))),
13911           Governed_By   => Assoc_List,
13912           Into          => Comp_List,
13913           Report_Errors => Errors);
13914         pragma Assert (not Errors);
13915
13916         Create_All_Components;
13917
13918      --  If the subtype declaration is created for a tagged type derivation
13919      --  with constraints, we retrieve the record definition of the parent
13920      --  type to select the components of the proper variant.
13921
13922      elsif Is_Static
13923        and then Is_Tagged_Type (Typ)
13924        and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
13925        and then
13926          Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
13927        and then Is_Variant_Record (Parent_Type)
13928      then
13929         Collect_Fixed_Components (Typ);
13930
13931         Gather_Components
13932           (Typ,
13933            Component_List (Type_Definition (Parent (Parent_Type))),
13934            Governed_By   => Assoc_List,
13935            Into          => Comp_List,
13936            Report_Errors => Errors);
13937
13938         --  Note: previously there was a check at this point that no errors
13939         --  were detected. As a consequence of AI05-220 there may be an error
13940         --  if an inherited discriminant that controls a variant has a non-
13941         --  static constraint.
13942
13943         --  If the tagged derivation has a type extension, collect all the
13944         --  new components therein.
13945
13946         if Present (Record_Extension_Part (Type_Definition (Parent (Typ))))
13947         then
13948            Old_C := First_Component (Typ);
13949            while Present (Old_C) loop
13950               if Original_Record_Component (Old_C) = Old_C
13951                 and then Chars (Old_C) /= Name_uTag
13952                 and then Chars (Old_C) /= Name_uParent
13953               then
13954                  Append_Elmt (Old_C, Comp_List);
13955               end if;
13956
13957               Next_Component (Old_C);
13958            end loop;
13959         end if;
13960
13961         Create_All_Components;
13962
13963      else
13964         --  If discriminants are not static, or if this is a multi-level type
13965         --  extension, we have to include all components of the parent type.
13966
13967         Old_C := First_Component (Typ);
13968         while Present (Old_C) loop
13969            New_C := Create_Component (Old_C);
13970
13971            Set_Etype
13972              (New_C,
13973               Constrain_Component_Type
13974                 (Old_C, Subt, Decl_Node, Typ, Constraints));
13975            Set_Is_Public (New_C, Is_Public (Subt));
13976
13977            Next_Component (Old_C);
13978         end loop;
13979      end if;
13980
13981      End_Scope;
13982   end Create_Constrained_Components;
13983
13984   ------------------------------------------
13985   -- Decimal_Fixed_Point_Type_Declaration --
13986   ------------------------------------------
13987
13988   procedure Decimal_Fixed_Point_Type_Declaration
13989     (T   : Entity_Id;
13990      Def : Node_Id)
13991   is
13992      Loc           : constant Source_Ptr := Sloc (Def);
13993      Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
13994      Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
13995      Implicit_Base : Entity_Id;
13996      Digs_Val      : Uint;
13997      Delta_Val     : Ureal;
13998      Scale_Val     : Uint;
13999      Bound_Val     : Ureal;
14000
14001   begin
14002      Check_SPARK_05_Restriction
14003        ("decimal fixed point type is not allowed", Def);
14004      Check_Restriction (No_Fixed_Point, Def);
14005
14006      --  Create implicit base type
14007
14008      Implicit_Base :=
14009        Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
14010      Set_Etype (Implicit_Base, Implicit_Base);
14011
14012      --  Analyze and process delta expression
14013
14014      Analyze_And_Resolve (Delta_Expr, Universal_Real);
14015
14016      Check_Delta_Expression (Delta_Expr);
14017      Delta_Val := Expr_Value_R (Delta_Expr);
14018
14019      --  Check delta is power of 10, and determine scale value from it
14020
14021      declare
14022         Val : Ureal;
14023
14024      begin
14025         Scale_Val := Uint_0;
14026         Val := Delta_Val;
14027
14028         if Val < Ureal_1 then
14029            while Val < Ureal_1 loop
14030               Val := Val * Ureal_10;
14031               Scale_Val := Scale_Val + 1;
14032            end loop;
14033
14034            if Scale_Val > 18 then
14035               Error_Msg_N ("scale exceeds maximum value of 18", Def);
14036               Scale_Val := UI_From_Int (+18);
14037            end if;
14038
14039         else
14040            while Val > Ureal_1 loop
14041               Val := Val / Ureal_10;
14042               Scale_Val := Scale_Val - 1;
14043            end loop;
14044
14045            if Scale_Val < -18 then
14046               Error_Msg_N ("scale is less than minimum value of -18", Def);
14047               Scale_Val := UI_From_Int (-18);
14048            end if;
14049         end if;
14050
14051         if Val /= Ureal_1 then
14052            Error_Msg_N ("delta expression must be a power of 10", Def);
14053            Delta_Val := Ureal_10 ** (-Scale_Val);
14054         end if;
14055      end;
14056
14057      --  Set delta, scale and small (small = delta for decimal type)
14058
14059      Set_Delta_Value (Implicit_Base, Delta_Val);
14060      Set_Scale_Value (Implicit_Base, Scale_Val);
14061      Set_Small_Value (Implicit_Base, Delta_Val);
14062
14063      --  Analyze and process digits expression
14064
14065      Analyze_And_Resolve (Digs_Expr, Any_Integer);
14066      Check_Digits_Expression (Digs_Expr);
14067      Digs_Val := Expr_Value (Digs_Expr);
14068
14069      if Digs_Val > 18 then
14070         Digs_Val := UI_From_Int (+18);
14071         Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
14072      end if;
14073
14074      Set_Digits_Value (Implicit_Base, Digs_Val);
14075      Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
14076
14077      --  Set range of base type from digits value for now. This will be
14078      --  expanded to represent the true underlying base range by Freeze.
14079
14080      Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
14081
14082      --  Note: We leave size as zero for now, size will be set at freeze
14083      --  time. We have to do this for ordinary fixed-point, because the size
14084      --  depends on the specified small, and we might as well do the same for
14085      --  decimal fixed-point.
14086
14087      pragma Assert (Esize (Implicit_Base) = Uint_0);
14088
14089      --  If there are bounds given in the declaration use them as the
14090      --  bounds of the first named subtype.
14091
14092      if Present (Real_Range_Specification (Def)) then
14093         declare
14094            RRS      : constant Node_Id := Real_Range_Specification (Def);
14095            Low      : constant Node_Id := Low_Bound (RRS);
14096            High     : constant Node_Id := High_Bound (RRS);
14097            Low_Val  : Ureal;
14098            High_Val : Ureal;
14099
14100         begin
14101            Analyze_And_Resolve (Low, Any_Real);
14102            Analyze_And_Resolve (High, Any_Real);
14103            Check_Real_Bound (Low);
14104            Check_Real_Bound (High);
14105            Low_Val := Expr_Value_R (Low);
14106            High_Val := Expr_Value_R (High);
14107
14108            if Low_Val < (-Bound_Val) then
14109               Error_Msg_N
14110                 ("range low bound too small for digits value", Low);
14111               Low_Val := -Bound_Val;
14112            end if;
14113
14114            if High_Val > Bound_Val then
14115               Error_Msg_N
14116                 ("range high bound too large for digits value", High);
14117               High_Val := Bound_Val;
14118            end if;
14119
14120            Set_Fixed_Range (T, Loc, Low_Val, High_Val);
14121         end;
14122
14123      --  If no explicit range, use range that corresponds to given
14124      --  digits value. This will end up as the final range for the
14125      --  first subtype.
14126
14127      else
14128         Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
14129      end if;
14130
14131      --  Complete entity for first subtype. The inheritance of the rep item
14132      --  chain ensures that SPARK-related pragmas are not clobbered when the
14133      --  decimal fixed point type acts as a full view of a private type.
14134
14135      Set_Ekind              (T, E_Decimal_Fixed_Point_Subtype);
14136      Set_Etype              (T, Implicit_Base);
14137      Set_Size_Info          (T, Implicit_Base);
14138      Inherit_Rep_Item_Chain (T, Implicit_Base);
14139      Set_Digits_Value       (T, Digs_Val);
14140      Set_Delta_Value        (T, Delta_Val);
14141      Set_Small_Value        (T, Delta_Val);
14142      Set_Scale_Value        (T, Scale_Val);
14143      Set_Is_Constrained     (T);
14144   end Decimal_Fixed_Point_Type_Declaration;
14145
14146   -----------------------------------
14147   -- Derive_Progenitor_Subprograms --
14148   -----------------------------------
14149
14150   procedure Derive_Progenitor_Subprograms
14151     (Parent_Type : Entity_Id;
14152      Tagged_Type : Entity_Id)
14153   is
14154      E          : Entity_Id;
14155      Elmt       : Elmt_Id;
14156      Iface      : Entity_Id;
14157      Iface_Elmt : Elmt_Id;
14158      Iface_Subp : Entity_Id;
14159      New_Subp   : Entity_Id := Empty;
14160      Prim_Elmt  : Elmt_Id;
14161      Subp       : Entity_Id;
14162      Typ        : Entity_Id;
14163
14164   begin
14165      pragma Assert (Ada_Version >= Ada_2005
14166        and then Is_Record_Type (Tagged_Type)
14167        and then Is_Tagged_Type (Tagged_Type)
14168        and then Has_Interfaces (Tagged_Type));
14169
14170      --  Step 1: Transfer to the full-view primitives associated with the
14171      --  partial-view that cover interface primitives. Conceptually this
14172      --  work should be done later by Process_Full_View; done here to
14173      --  simplify its implementation at later stages. It can be safely
14174      --  done here because interfaces must be visible in the partial and
14175      --  private view (RM 7.3(7.3/2)).
14176
14177      --  Small optimization: This work is only required if the parent may
14178      --  have entities whose Alias attribute reference an interface primitive.
14179      --  Such a situation may occur if the parent is an abstract type and the
14180      --  primitive has not been yet overridden or if the parent is a generic
14181      --  formal type covering interfaces.
14182
14183      --  If the tagged type is not abstract, it cannot have abstract
14184      --  primitives (the only entities in the list of primitives of
14185      --  non-abstract tagged types that can reference abstract primitives
14186      --  through its Alias attribute are the internal entities that have
14187      --  attribute Interface_Alias, and these entities are generated later
14188      --  by Add_Internal_Interface_Entities).
14189
14190      if In_Private_Part (Current_Scope)
14191        and then (Is_Abstract_Type (Parent_Type)
14192                    or else
14193                  Is_Generic_Type  (Parent_Type))
14194      then
14195         Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
14196         while Present (Elmt) loop
14197            Subp := Node (Elmt);
14198
14199            --  At this stage it is not possible to have entities in the list
14200            --  of primitives that have attribute Interface_Alias.
14201
14202            pragma Assert (No (Interface_Alias (Subp)));
14203
14204            Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
14205
14206            if Is_Interface (Typ) then
14207               E := Find_Primitive_Covering_Interface
14208                      (Tagged_Type => Tagged_Type,
14209                       Iface_Prim  => Subp);
14210
14211               if Present (E)
14212                 and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
14213               then
14214                  Replace_Elmt (Elmt, E);
14215                  Remove_Homonym (Subp);
14216               end if;
14217            end if;
14218
14219            Next_Elmt (Elmt);
14220         end loop;
14221      end if;
14222
14223      --  Step 2: Add primitives of progenitors that are not implemented by
14224      --  parents of Tagged_Type.
14225
14226      if Present (Interfaces (Base_Type (Tagged_Type))) then
14227         Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
14228         while Present (Iface_Elmt) loop
14229            Iface := Node (Iface_Elmt);
14230
14231            Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
14232            while Present (Prim_Elmt) loop
14233               Iface_Subp := Node (Prim_Elmt);
14234
14235               --  Exclude derivation of predefined primitives except those
14236               --  that come from source, or are inherited from one that comes
14237               --  from source. Required to catch declarations of equality
14238               --  operators of interfaces. For example:
14239
14240               --     type Iface is interface;
14241               --     function "=" (Left, Right : Iface) return Boolean;
14242
14243               if not Is_Predefined_Dispatching_Operation (Iface_Subp)
14244                 or else Comes_From_Source (Ultimate_Alias (Iface_Subp))
14245               then
14246                  E := Find_Primitive_Covering_Interface
14247                         (Tagged_Type => Tagged_Type,
14248                          Iface_Prim  => Iface_Subp);
14249
14250                  --  If not found we derive a new primitive leaving its alias
14251                  --  attribute referencing the interface primitive.
14252
14253                  if No (E) then
14254                     Derive_Subprogram
14255                       (New_Subp, Iface_Subp, Tagged_Type, Iface);
14256
14257                  --  Ada 2012 (AI05-0197): If the covering primitive's name
14258                  --  differs from the name of the interface primitive then it
14259                  --  is a private primitive inherited from a parent type. In
14260                  --  such case, given that Tagged_Type covers the interface,
14261                  --  the inherited private primitive becomes visible. For such
14262                  --  purpose we add a new entity that renames the inherited
14263                  --  private primitive.
14264
14265                  elsif Chars (E) /= Chars (Iface_Subp) then
14266                     pragma Assert (Has_Suffix (E, 'P'));
14267                     Derive_Subprogram
14268                       (New_Subp, Iface_Subp, Tagged_Type, Iface);
14269                     Set_Alias (New_Subp, E);
14270                     Set_Is_Abstract_Subprogram (New_Subp,
14271                       Is_Abstract_Subprogram (E));
14272
14273                  --  Propagate to the full view interface entities associated
14274                  --  with the partial view.
14275
14276                  elsif In_Private_Part (Current_Scope)
14277                    and then Present (Alias (E))
14278                    and then Alias (E) = Iface_Subp
14279                    and then
14280                      List_Containing (Parent (E)) /=
14281                        Private_Declarations
14282                          (Specification
14283                            (Unit_Declaration_Node (Current_Scope)))
14284                  then
14285                     Append_Elmt (E, Primitive_Operations (Tagged_Type));
14286                  end if;
14287               end if;
14288
14289               Next_Elmt (Prim_Elmt);
14290            end loop;
14291
14292            Next_Elmt (Iface_Elmt);
14293         end loop;
14294      end if;
14295   end Derive_Progenitor_Subprograms;
14296
14297   -----------------------
14298   -- Derive_Subprogram --
14299   -----------------------
14300
14301   procedure Derive_Subprogram
14302     (New_Subp     : in out Entity_Id;
14303      Parent_Subp  : Entity_Id;
14304      Derived_Type : Entity_Id;
14305      Parent_Type  : Entity_Id;
14306      Actual_Subp  : Entity_Id := Empty)
14307   is
14308      Formal : Entity_Id;
14309      --  Formal parameter of parent primitive operation
14310
14311      Formal_Of_Actual : Entity_Id;
14312      --  Formal parameter of actual operation, when the derivation is to
14313      --  create a renaming for a primitive operation of an actual in an
14314      --  instantiation.
14315
14316      New_Formal : Entity_Id;
14317      --  Formal of inherited operation
14318
14319      Visible_Subp : Entity_Id := Parent_Subp;
14320
14321      function Is_Private_Overriding return Boolean;
14322      --  If Subp is a private overriding of a visible operation, the inherited
14323      --  operation derives from the overridden op (even though its body is the
14324      --  overriding one) and the inherited operation is visible now. See
14325      --  sem_disp to see the full details of the handling of the overridden
14326      --  subprogram, which is removed from the list of primitive operations of
14327      --  the type. The overridden subprogram is saved locally in Visible_Subp,
14328      --  and used to diagnose abstract operations that need overriding in the
14329      --  derived type.
14330
14331      procedure Replace_Type (Id, New_Id : Entity_Id);
14332      --  When the type is an anonymous access type, create a new access type
14333      --  designating the derived type.
14334
14335      procedure Set_Derived_Name;
14336      --  This procedure sets the appropriate Chars name for New_Subp. This
14337      --  is normally just a copy of the parent name. An exception arises for
14338      --  type support subprograms, where the name is changed to reflect the
14339      --  name of the derived type, e.g. if type foo is derived from type bar,
14340      --  then a procedure barDA is derived with a name fooDA.
14341
14342      ---------------------------
14343      -- Is_Private_Overriding --
14344      ---------------------------
14345
14346      function Is_Private_Overriding return Boolean is
14347         Prev : Entity_Id;
14348
14349      begin
14350         --  If the parent is not a dispatching operation there is no
14351         --  need to investigate overridings
14352
14353         if not Is_Dispatching_Operation (Parent_Subp) then
14354            return False;
14355         end if;
14356
14357         --  The visible operation that is overridden is a homonym of the
14358         --  parent subprogram. We scan the homonym chain to find the one
14359         --  whose alias is the subprogram we are deriving.
14360
14361         Prev := Current_Entity (Parent_Subp);
14362         while Present (Prev) loop
14363            if Ekind (Prev) = Ekind (Parent_Subp)
14364              and then Alias (Prev) = Parent_Subp
14365              and then Scope (Parent_Subp) = Scope (Prev)
14366              and then not Is_Hidden (Prev)
14367            then
14368               Visible_Subp := Prev;
14369               return True;
14370            end if;
14371
14372            Prev := Homonym (Prev);
14373         end loop;
14374
14375         return False;
14376      end Is_Private_Overriding;
14377
14378      ------------------
14379      -- Replace_Type --
14380      ------------------
14381
14382      procedure Replace_Type (Id, New_Id : Entity_Id) is
14383         Id_Type  : constant Entity_Id := Etype (Id);
14384         Acc_Type : Entity_Id;
14385         Par      : constant Node_Id := Parent (Derived_Type);
14386
14387      begin
14388         --  When the type is an anonymous access type, create a new access
14389         --  type designating the derived type. This itype must be elaborated
14390         --  at the point of the derivation, not on subsequent calls that may
14391         --  be out of the proper scope for Gigi, so we insert a reference to
14392         --  it after the derivation.
14393
14394         if Ekind (Id_Type) = E_Anonymous_Access_Type then
14395            declare
14396               Desig_Typ : Entity_Id := Designated_Type (Id_Type);
14397
14398            begin
14399               if Ekind (Desig_Typ) = E_Record_Type_With_Private
14400                 and then Present (Full_View (Desig_Typ))
14401                 and then not Is_Private_Type (Parent_Type)
14402               then
14403                  Desig_Typ := Full_View (Desig_Typ);
14404               end if;
14405
14406               if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
14407
14408                  --  Ada 2005 (AI-251): Handle also derivations of abstract
14409                  --  interface primitives.
14410
14411                 or else (Is_Interface (Desig_Typ)
14412                           and then not Is_Class_Wide_Type (Desig_Typ))
14413               then
14414                  Acc_Type := New_Copy (Id_Type);
14415                  Set_Etype (Acc_Type, Acc_Type);
14416                  Set_Scope (Acc_Type, New_Subp);
14417
14418                  --  Set size of anonymous access type. If we have an access
14419                  --  to an unconstrained array, this is a fat pointer, so it
14420                  --  is sizes at twice addtress size.
14421
14422                  if Is_Array_Type (Desig_Typ)
14423                    and then not Is_Constrained (Desig_Typ)
14424                  then
14425                     Init_Size (Acc_Type, 2 * System_Address_Size);
14426
14427                  --  Other cases use a thin pointer
14428
14429                  else
14430                     Init_Size (Acc_Type, System_Address_Size);
14431                  end if;
14432
14433                  --  Set remaining characterstics of anonymous access type
14434
14435                  Init_Alignment (Acc_Type);
14436                  Set_Directly_Designated_Type (Acc_Type, Derived_Type);
14437
14438                  Set_Etype (New_Id, Acc_Type);
14439                  Set_Scope (New_Id, New_Subp);
14440
14441                  --  Create a reference to it
14442
14443                  Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
14444
14445               else
14446                  Set_Etype (New_Id, Id_Type);
14447               end if;
14448            end;
14449
14450         --  In Ada2012, a formal may have an incomplete type but the type
14451         --  derivation that inherits the primitive follows the full view.
14452
14453         elsif Base_Type (Id_Type) = Base_Type (Parent_Type)
14454           or else
14455             (Ekind (Id_Type) = E_Record_Type_With_Private
14456               and then Present (Full_View (Id_Type))
14457               and then
14458                 Base_Type (Full_View (Id_Type)) = Base_Type (Parent_Type))
14459           or else
14460             (Ada_Version >= Ada_2012
14461               and then Ekind (Id_Type) = E_Incomplete_Type
14462               and then Full_View (Id_Type) = Parent_Type)
14463         then
14464            --  Constraint checks on formals are generated during expansion,
14465            --  based on the signature of the original subprogram. The bounds
14466            --  of the derived type are not relevant, and thus we can use
14467            --  the base type for the formals. However, the return type may be
14468            --  used in a context that requires that the proper static bounds
14469            --  be used (a case statement, for example)  and for those cases
14470            --  we must use the derived type (first subtype), not its base.
14471
14472            --  If the derived_type_definition has no constraints, we know that
14473            --  the derived type has the same constraints as the first subtype
14474            --  of the parent, and we can also use it rather than its base,
14475            --  which can lead to more efficient code.
14476
14477            if Etype (Id) = Parent_Type then
14478               if Is_Scalar_Type (Parent_Type)
14479                 and then
14480                   Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
14481               then
14482                  Set_Etype (New_Id, Derived_Type);
14483
14484               elsif Nkind (Par) = N_Full_Type_Declaration
14485                 and then
14486                   Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
14487                 and then
14488                   Is_Entity_Name
14489                     (Subtype_Indication (Type_Definition (Par)))
14490               then
14491                  Set_Etype (New_Id, Derived_Type);
14492
14493               else
14494                  Set_Etype (New_Id, Base_Type (Derived_Type));
14495               end if;
14496
14497            else
14498               Set_Etype (New_Id, Base_Type (Derived_Type));
14499            end if;
14500
14501         else
14502            Set_Etype (New_Id, Etype (Id));
14503         end if;
14504      end Replace_Type;
14505
14506      ----------------------
14507      -- Set_Derived_Name --
14508      ----------------------
14509
14510      procedure Set_Derived_Name is
14511         Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
14512      begin
14513         if Nm = TSS_Null then
14514            Set_Chars (New_Subp, Chars (Parent_Subp));
14515         else
14516            Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
14517         end if;
14518      end Set_Derived_Name;
14519
14520   --  Start of processing for Derive_Subprogram
14521
14522   begin
14523      New_Subp := New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
14524      Set_Ekind (New_Subp, Ekind (Parent_Subp));
14525
14526      --  Check whether the inherited subprogram is a private operation that
14527      --  should be inherited but not yet made visible. Such subprograms can
14528      --  become visible at a later point (e.g., the private part of a public
14529      --  child unit) via Declare_Inherited_Private_Subprograms. If the
14530      --  following predicate is true, then this is not such a private
14531      --  operation and the subprogram simply inherits the name of the parent
14532      --  subprogram. Note the special check for the names of controlled
14533      --  operations, which are currently exempted from being inherited with
14534      --  a hidden name because they must be findable for generation of
14535      --  implicit run-time calls.
14536
14537      if not Is_Hidden (Parent_Subp)
14538        or else Is_Internal (Parent_Subp)
14539        or else Is_Private_Overriding
14540        or else Is_Internal_Name (Chars (Parent_Subp))
14541        or else Nam_In (Chars (Parent_Subp), Name_Initialize,
14542                                             Name_Adjust,
14543                                             Name_Finalize)
14544      then
14545         Set_Derived_Name;
14546
14547      --  An inherited dispatching equality will be overridden by an internally
14548      --  generated one, or by an explicit one, so preserve its name and thus
14549      --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
14550      --  private operation it may become invisible if the full view has
14551      --  progenitors, and the dispatch table will be malformed.
14552      --  We check that the type is limited to handle the anomalous declaration
14553      --  of Limited_Controlled, which is derived from a non-limited type, and
14554      --  which is handled specially elsewhere as well.
14555
14556      elsif Chars (Parent_Subp) = Name_Op_Eq
14557        and then Is_Dispatching_Operation (Parent_Subp)
14558        and then Etype (Parent_Subp) = Standard_Boolean
14559        and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
14560        and then
14561          Etype (First_Formal (Parent_Subp)) =
14562            Etype (Next_Formal (First_Formal (Parent_Subp)))
14563      then
14564         Set_Derived_Name;
14565
14566      --  If parent is hidden, this can be a regular derivation if the
14567      --  parent is immediately visible in a non-instantiating context,
14568      --  or if we are in the private part of an instance. This test
14569      --  should still be refined ???
14570
14571      --  The test for In_Instance_Not_Visible avoids inheriting the derived
14572      --  operation as a non-visible operation in cases where the parent
14573      --  subprogram might not be visible now, but was visible within the
14574      --  original generic, so it would be wrong to make the inherited
14575      --  subprogram non-visible now. (Not clear if this test is fully
14576      --  correct; are there any cases where we should declare the inherited
14577      --  operation as not visible to avoid it being overridden, e.g., when
14578      --  the parent type is a generic actual with private primitives ???)
14579
14580      --  (they should be treated the same as other private inherited
14581      --  subprograms, but it's not clear how to do this cleanly). ???
14582
14583      elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
14584              and then Is_Immediately_Visible (Parent_Subp)
14585              and then not In_Instance)
14586        or else In_Instance_Not_Visible
14587      then
14588         Set_Derived_Name;
14589
14590      --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
14591      --  overrides an interface primitive because interface primitives
14592      --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
14593
14594      elsif Ada_Version >= Ada_2005
14595         and then Is_Dispatching_Operation (Parent_Subp)
14596         and then Covers_Some_Interface (Parent_Subp)
14597      then
14598         Set_Derived_Name;
14599
14600      --  Otherwise, the type is inheriting a private operation, so enter
14601      --  it with a special name so it can't be overridden.
14602
14603      else
14604         Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
14605      end if;
14606
14607      Set_Parent (New_Subp, Parent (Derived_Type));
14608
14609      if Present (Actual_Subp) then
14610         Replace_Type (Actual_Subp, New_Subp);
14611      else
14612         Replace_Type (Parent_Subp, New_Subp);
14613      end if;
14614
14615      Conditional_Delay (New_Subp, Parent_Subp);
14616
14617      --  If we are creating a renaming for a primitive operation of an
14618      --  actual of a generic derived type, we must examine the signature
14619      --  of the actual primitive, not that of the generic formal, which for
14620      --  example may be an interface. However the name and initial value
14621      --  of the inherited operation are those of the formal primitive.
14622
14623      Formal := First_Formal (Parent_Subp);
14624
14625      if Present (Actual_Subp) then
14626         Formal_Of_Actual := First_Formal (Actual_Subp);
14627      else
14628         Formal_Of_Actual := Empty;
14629      end if;
14630
14631      while Present (Formal) loop
14632         New_Formal := New_Copy (Formal);
14633
14634         --  Normally we do not go copying parents, but in the case of
14635         --  formals, we need to link up to the declaration (which is the
14636         --  parameter specification), and it is fine to link up to the
14637         --  original formal's parameter specification in this case.
14638
14639         Set_Parent (New_Formal, Parent (Formal));
14640         Append_Entity (New_Formal, New_Subp);
14641
14642         if Present (Formal_Of_Actual) then
14643            Replace_Type (Formal_Of_Actual, New_Formal);
14644            Next_Formal (Formal_Of_Actual);
14645         else
14646            Replace_Type (Formal, New_Formal);
14647         end if;
14648
14649         Next_Formal (Formal);
14650      end loop;
14651
14652      --  If this derivation corresponds to a tagged generic actual, then
14653      --  primitive operations rename those of the actual. Otherwise the
14654      --  primitive operations rename those of the parent type, If the parent
14655      --  renames an intrinsic operator, so does the new subprogram. We except
14656      --  concatenation, which is always properly typed, and does not get
14657      --  expanded as other intrinsic operations.
14658
14659      if No (Actual_Subp) then
14660         if Is_Intrinsic_Subprogram (Parent_Subp) then
14661            Set_Is_Intrinsic_Subprogram (New_Subp);
14662
14663            if Present (Alias (Parent_Subp))
14664              and then Chars (Parent_Subp) /= Name_Op_Concat
14665            then
14666               Set_Alias (New_Subp, Alias (Parent_Subp));
14667            else
14668               Set_Alias (New_Subp, Parent_Subp);
14669            end if;
14670
14671         else
14672            Set_Alias (New_Subp, Parent_Subp);
14673         end if;
14674
14675      else
14676         Set_Alias (New_Subp, Actual_Subp);
14677      end if;
14678
14679      --  Inherit the "ghostness" from the parent subprogram
14680
14681      if Is_Ghost_Entity (Alias (New_Subp)) then
14682         Set_Is_Ghost_Entity (New_Subp);
14683      end if;
14684
14685      --  Derived subprograms of a tagged type must inherit the convention
14686      --  of the parent subprogram (a requirement of AI-117). Derived
14687      --  subprograms of untagged types simply get convention Ada by default.
14688
14689      --  If the derived type is a tagged generic formal type with unknown
14690      --  discriminants, its convention is intrinsic (RM 6.3.1 (8)).
14691
14692      --  However, if the type is derived from a generic formal, the further
14693      --  inherited subprogram has the convention of the non-generic ancestor.
14694      --  Otherwise there would be no way to override the operation.
14695      --  (This is subject to forthcoming ARG discussions).
14696
14697      if Is_Tagged_Type (Derived_Type) then
14698         if Is_Generic_Type (Derived_Type)
14699           and then Has_Unknown_Discriminants (Derived_Type)
14700         then
14701            Set_Convention (New_Subp, Convention_Intrinsic);
14702
14703         else
14704            if Is_Generic_Type (Parent_Type)
14705              and then Has_Unknown_Discriminants (Parent_Type)
14706            then
14707               Set_Convention (New_Subp, Convention (Alias (Parent_Subp)));
14708            else
14709               Set_Convention (New_Subp, Convention (Parent_Subp));
14710            end if;
14711         end if;
14712      end if;
14713
14714      --  Predefined controlled operations retain their name even if the parent
14715      --  is hidden (see above), but they are not primitive operations if the
14716      --  ancestor is not visible, for example if the parent is a private
14717      --  extension completed with a controlled extension. Note that a full
14718      --  type that is controlled can break privacy: the flag Is_Controlled is
14719      --  set on both views of the type.
14720
14721      if Is_Controlled (Parent_Type)
14722        and then Nam_In (Chars (Parent_Subp), Name_Initialize,
14723                                              Name_Adjust,
14724                                              Name_Finalize)
14725        and then Is_Hidden (Parent_Subp)
14726        and then not Is_Visibly_Controlled (Parent_Type)
14727      then
14728         Set_Is_Hidden (New_Subp);
14729      end if;
14730
14731      Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
14732      Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
14733
14734      if Ekind (Parent_Subp) = E_Procedure then
14735         Set_Is_Valued_Procedure
14736           (New_Subp, Is_Valued_Procedure (Parent_Subp));
14737      else
14738         Set_Has_Controlling_Result
14739           (New_Subp, Has_Controlling_Result (Parent_Subp));
14740      end if;
14741
14742      --  No_Return must be inherited properly. If this is overridden in the
14743      --  case of a dispatching operation, then a check is made in Sem_Disp
14744      --  that the overriding operation is also No_Return (no such check is
14745      --  required for the case of non-dispatching operation.
14746
14747      Set_No_Return (New_Subp, No_Return (Parent_Subp));
14748
14749      --  A derived function with a controlling result is abstract. If the
14750      --  Derived_Type is a nonabstract formal generic derived type, then
14751      --  inherited operations are not abstract: the required check is done at
14752      --  instantiation time. If the derivation is for a generic actual, the
14753      --  function is not abstract unless the actual is.
14754
14755      if Is_Generic_Type (Derived_Type)
14756        and then not Is_Abstract_Type (Derived_Type)
14757      then
14758         null;
14759
14760      --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
14761      --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
14762
14763      --  A subprogram subject to pragma Extensions_Visible with value False
14764      --  requires overriding if the subprogram has at least one controlling
14765      --  OUT parameter (SPARK RM 6.1.7(6)).
14766
14767      elsif Ada_Version >= Ada_2005
14768        and then (Is_Abstract_Subprogram (Alias (New_Subp))
14769                   or else (Is_Tagged_Type (Derived_Type)
14770                             and then Etype (New_Subp) = Derived_Type
14771                             and then not Is_Null_Extension (Derived_Type))
14772                   or else (Is_Tagged_Type (Derived_Type)
14773                             and then Ekind (Etype (New_Subp)) =
14774                                                       E_Anonymous_Access_Type
14775                             and then Designated_Type (Etype (New_Subp)) =
14776                                                        Derived_Type
14777                             and then not Is_Null_Extension (Derived_Type))
14778                   or else (Comes_From_Source (Alias (New_Subp))
14779                             and then Is_EVF_Procedure (Alias (New_Subp))))
14780        and then No (Actual_Subp)
14781      then
14782         if not Is_Tagged_Type (Derived_Type)
14783           or else Is_Abstract_Type (Derived_Type)
14784           or else Is_Abstract_Subprogram (Alias (New_Subp))
14785         then
14786            Set_Is_Abstract_Subprogram (New_Subp);
14787         else
14788            Set_Requires_Overriding (New_Subp);
14789         end if;
14790
14791      elsif Ada_Version < Ada_2005
14792        and then (Is_Abstract_Subprogram (Alias (New_Subp))
14793                   or else (Is_Tagged_Type (Derived_Type)
14794                             and then Etype (New_Subp) = Derived_Type
14795                             and then No (Actual_Subp)))
14796      then
14797         Set_Is_Abstract_Subprogram (New_Subp);
14798
14799      --  AI05-0097 : an inherited operation that dispatches on result is
14800      --  abstract if the derived type is abstract, even if the parent type
14801      --  is concrete and the derived type is a null extension.
14802
14803      elsif Has_Controlling_Result (Alias (New_Subp))
14804        and then Is_Abstract_Type (Etype (New_Subp))
14805      then
14806         Set_Is_Abstract_Subprogram (New_Subp);
14807
14808      --  Finally, if the parent type is abstract we must verify that all
14809      --  inherited operations are either non-abstract or overridden, or that
14810      --  the derived type itself is abstract (this check is performed at the
14811      --  end of a package declaration, in Check_Abstract_Overriding). A
14812      --  private overriding in the parent type will not be visible in the
14813      --  derivation if we are not in an inner package or in a child unit of
14814      --  the parent type, in which case the abstractness of the inherited
14815      --  operation is carried to the new subprogram.
14816
14817      elsif Is_Abstract_Type (Parent_Type)
14818        and then not In_Open_Scopes (Scope (Parent_Type))
14819        and then Is_Private_Overriding
14820        and then Is_Abstract_Subprogram (Visible_Subp)
14821      then
14822         if No (Actual_Subp) then
14823            Set_Alias (New_Subp, Visible_Subp);
14824            Set_Is_Abstract_Subprogram (New_Subp, True);
14825
14826         else
14827            --  If this is a derivation for an instance of a formal derived
14828            --  type, abstractness comes from the primitive operation of the
14829            --  actual, not from the operation inherited from the ancestor.
14830
14831            Set_Is_Abstract_Subprogram
14832              (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
14833         end if;
14834      end if;
14835
14836      New_Overloaded_Entity (New_Subp, Derived_Type);
14837
14838      --  Check for case of a derived subprogram for the instantiation of a
14839      --  formal derived tagged type, if so mark the subprogram as dispatching
14840      --  and inherit the dispatching attributes of the actual subprogram. The
14841      --  derived subprogram is effectively renaming of the actual subprogram,
14842      --  so it needs to have the same attributes as the actual.
14843
14844      if Present (Actual_Subp)
14845        and then Is_Dispatching_Operation (Actual_Subp)
14846      then
14847         Set_Is_Dispatching_Operation (New_Subp);
14848
14849         if Present (DTC_Entity (Actual_Subp)) then
14850            Set_DTC_Entity (New_Subp, DTC_Entity (Actual_Subp));
14851            Set_DT_Position_Value (New_Subp, DT_Position (Actual_Subp));
14852         end if;
14853      end if;
14854
14855      --  Indicate that a derived subprogram does not require a body and that
14856      --  it does not require processing of default expressions.
14857
14858      Set_Has_Completion (New_Subp);
14859      Set_Default_Expressions_Processed (New_Subp);
14860
14861      if Ekind (New_Subp) = E_Function then
14862         Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
14863      end if;
14864   end Derive_Subprogram;
14865
14866   ------------------------
14867   -- Derive_Subprograms --
14868   ------------------------
14869
14870   procedure Derive_Subprograms
14871     (Parent_Type    : Entity_Id;
14872      Derived_Type   : Entity_Id;
14873      Generic_Actual : Entity_Id := Empty)
14874   is
14875      Op_List : constant Elist_Id :=
14876                  Collect_Primitive_Operations (Parent_Type);
14877
14878      function Check_Derived_Type return Boolean;
14879      --  Check that all the entities derived from Parent_Type are found in
14880      --  the list of primitives of Derived_Type exactly in the same order.
14881
14882      procedure Derive_Interface_Subprogram
14883        (New_Subp    : in out Entity_Id;
14884         Subp        : Entity_Id;
14885         Actual_Subp : Entity_Id);
14886      --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
14887      --  (which is an interface primitive). If Generic_Actual is present then
14888      --  Actual_Subp is the actual subprogram corresponding with the generic
14889      --  subprogram Subp.
14890
14891      function Check_Derived_Type return Boolean is
14892         E        : Entity_Id;
14893         Elmt     : Elmt_Id;
14894         List     : Elist_Id;
14895         New_Subp : Entity_Id;
14896         Op_Elmt  : Elmt_Id;
14897         Subp     : Entity_Id;
14898
14899      begin
14900         --  Traverse list of entities in the current scope searching for
14901         --  an incomplete type whose full-view is derived type
14902
14903         E := First_Entity (Scope (Derived_Type));
14904         while Present (E) and then E /= Derived_Type loop
14905            if Ekind (E) = E_Incomplete_Type
14906              and then Present (Full_View (E))
14907              and then Full_View (E) = Derived_Type
14908            then
14909               --  Disable this test if Derived_Type completes an incomplete
14910               --  type because in such case more primitives can be added
14911               --  later to the list of primitives of Derived_Type by routine
14912               --  Process_Incomplete_Dependents
14913
14914               return True;
14915            end if;
14916
14917            E := Next_Entity (E);
14918         end loop;
14919
14920         List := Collect_Primitive_Operations (Derived_Type);
14921         Elmt := First_Elmt (List);
14922
14923         Op_Elmt := First_Elmt (Op_List);
14924         while Present (Op_Elmt) loop
14925            Subp     := Node (Op_Elmt);
14926            New_Subp := Node (Elmt);
14927
14928            --  At this early stage Derived_Type has no entities with attribute
14929            --  Interface_Alias. In addition, such primitives are always
14930            --  located at the end of the list of primitives of Parent_Type.
14931            --  Therefore, if found we can safely stop processing pending
14932            --  entities.
14933
14934            exit when Present (Interface_Alias (Subp));
14935
14936            --  Handle hidden entities
14937
14938            if not Is_Predefined_Dispatching_Operation (Subp)
14939              and then Is_Hidden (Subp)
14940            then
14941               if Present (New_Subp)
14942                 and then Primitive_Names_Match (Subp, New_Subp)
14943               then
14944                  Next_Elmt (Elmt);
14945               end if;
14946
14947            else
14948               if not Present (New_Subp)
14949                 or else Ekind (Subp) /= Ekind (New_Subp)
14950                 or else not Primitive_Names_Match (Subp, New_Subp)
14951               then
14952                  return False;
14953               end if;
14954
14955               Next_Elmt (Elmt);
14956            end if;
14957
14958            Next_Elmt (Op_Elmt);
14959         end loop;
14960
14961         return True;
14962      end Check_Derived_Type;
14963
14964      ---------------------------------
14965      -- Derive_Interface_Subprogram --
14966      ---------------------------------
14967
14968      procedure Derive_Interface_Subprogram
14969        (New_Subp    : in out Entity_Id;
14970         Subp        : Entity_Id;
14971         Actual_Subp : Entity_Id)
14972      is
14973         Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
14974         Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
14975
14976      begin
14977         pragma Assert (Is_Interface (Iface_Type));
14978
14979         Derive_Subprogram
14980           (New_Subp     => New_Subp,
14981            Parent_Subp  => Iface_Subp,
14982            Derived_Type => Derived_Type,
14983            Parent_Type  => Iface_Type,
14984            Actual_Subp  => Actual_Subp);
14985
14986         --  Given that this new interface entity corresponds with a primitive
14987         --  of the parent that was not overridden we must leave it associated
14988         --  with its parent primitive to ensure that it will share the same
14989         --  dispatch table slot when overridden.
14990
14991         if No (Actual_Subp) then
14992            Set_Alias (New_Subp, Subp);
14993
14994         --  For instantiations this is not needed since the previous call to
14995         --  Derive_Subprogram leaves the entity well decorated.
14996
14997         else
14998            pragma Assert (Alias (New_Subp) = Actual_Subp);
14999            null;
15000         end if;
15001      end Derive_Interface_Subprogram;
15002
15003      --  Local variables
15004
15005      Alias_Subp   : Entity_Id;
15006      Act_List     : Elist_Id;
15007      Act_Elmt     : Elmt_Id;
15008      Act_Subp     : Entity_Id := Empty;
15009      Elmt         : Elmt_Id;
15010      Need_Search  : Boolean   := False;
15011      New_Subp     : Entity_Id := Empty;
15012      Parent_Base  : Entity_Id;
15013      Subp         : Entity_Id;
15014
15015   --  Start of processing for Derive_Subprograms
15016
15017   begin
15018      if Ekind (Parent_Type) = E_Record_Type_With_Private
15019        and then Has_Discriminants (Parent_Type)
15020        and then Present (Full_View (Parent_Type))
15021      then
15022         Parent_Base := Full_View (Parent_Type);
15023      else
15024         Parent_Base := Parent_Type;
15025      end if;
15026
15027      if Present (Generic_Actual) then
15028         Act_List := Collect_Primitive_Operations (Generic_Actual);
15029         Act_Elmt := First_Elmt (Act_List);
15030      else
15031         Act_List := No_Elist;
15032         Act_Elmt := No_Elmt;
15033      end if;
15034
15035      --  Derive primitives inherited from the parent. Note that if the generic
15036      --  actual is present, this is not really a type derivation, it is a
15037      --  completion within an instance.
15038
15039      --  Case 1: Derived_Type does not implement interfaces
15040
15041      if not Is_Tagged_Type (Derived_Type)
15042        or else (not Has_Interfaces (Derived_Type)
15043                  and then not (Present (Generic_Actual)
15044                                 and then Has_Interfaces (Generic_Actual)))
15045      then
15046         Elmt := First_Elmt (Op_List);
15047         while Present (Elmt) loop
15048            Subp := Node (Elmt);
15049
15050            --  Literals are derived earlier in the process of building the
15051            --  derived type, and are skipped here.
15052
15053            if Ekind (Subp) = E_Enumeration_Literal then
15054               null;
15055
15056            --  The actual is a direct descendant and the common primitive
15057            --  operations appear in the same order.
15058
15059            --  If the generic parent type is present, the derived type is an
15060            --  instance of a formal derived type, and within the instance its
15061            --  operations are those of the actual. We derive from the formal
15062            --  type but make the inherited operations aliases of the
15063            --  corresponding operations of the actual.
15064
15065            else
15066               pragma Assert (No (Node (Act_Elmt))
15067                 or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
15068                           and then
15069                             Type_Conformant
15070                               (Subp, Node (Act_Elmt),
15071                                Skip_Controlling_Formals => True)));
15072
15073               Derive_Subprogram
15074                 (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
15075
15076               if Present (Act_Elmt) then
15077                  Next_Elmt (Act_Elmt);
15078               end if;
15079            end if;
15080
15081            Next_Elmt (Elmt);
15082         end loop;
15083
15084      --  Case 2: Derived_Type implements interfaces
15085
15086      else
15087         --  If the parent type has no predefined primitives we remove
15088         --  predefined primitives from the list of primitives of generic
15089         --  actual to simplify the complexity of this algorithm.
15090
15091         if Present (Generic_Actual) then
15092            declare
15093               Has_Predefined_Primitives : Boolean := False;
15094
15095            begin
15096               --  Check if the parent type has predefined primitives
15097
15098               Elmt := First_Elmt (Op_List);
15099               while Present (Elmt) loop
15100                  Subp := Node (Elmt);
15101
15102                  if Is_Predefined_Dispatching_Operation (Subp)
15103                    and then not Comes_From_Source (Ultimate_Alias (Subp))
15104                  then
15105                     Has_Predefined_Primitives := True;
15106                     exit;
15107                  end if;
15108
15109                  Next_Elmt (Elmt);
15110               end loop;
15111
15112               --  Remove predefined primitives of Generic_Actual. We must use
15113               --  an auxiliary list because in case of tagged types the value
15114               --  returned by Collect_Primitive_Operations is the value stored
15115               --  in its Primitive_Operations attribute (and we don't want to
15116               --  modify its current contents).
15117
15118               if not Has_Predefined_Primitives then
15119                  declare
15120                     Aux_List : constant Elist_Id := New_Elmt_List;
15121
15122                  begin
15123                     Elmt := First_Elmt (Act_List);
15124                     while Present (Elmt) loop
15125                        Subp := Node (Elmt);
15126
15127                        if not Is_Predefined_Dispatching_Operation (Subp)
15128                          or else Comes_From_Source (Subp)
15129                        then
15130                           Append_Elmt (Subp, Aux_List);
15131                        end if;
15132
15133                        Next_Elmt (Elmt);
15134                     end loop;
15135
15136                     Act_List := Aux_List;
15137                  end;
15138               end if;
15139
15140               Act_Elmt := First_Elmt (Act_List);
15141               Act_Subp := Node (Act_Elmt);
15142            end;
15143         end if;
15144
15145         --  Stage 1: If the generic actual is not present we derive the
15146         --  primitives inherited from the parent type. If the generic parent
15147         --  type is present, the derived type is an instance of a formal
15148         --  derived type, and within the instance its operations are those of
15149         --  the actual. We derive from the formal type but make the inherited
15150         --  operations aliases of the corresponding operations of the actual.
15151
15152         Elmt := First_Elmt (Op_List);
15153         while Present (Elmt) loop
15154            Subp       := Node (Elmt);
15155            Alias_Subp := Ultimate_Alias (Subp);
15156
15157            --  Do not derive internal entities of the parent that link
15158            --  interface primitives with their covering primitive. These
15159            --  entities will be added to this type when frozen.
15160
15161            if Present (Interface_Alias (Subp)) then
15162               goto Continue;
15163            end if;
15164
15165            --  If the generic actual is present find the corresponding
15166            --  operation in the generic actual. If the parent type is a
15167            --  direct ancestor of the derived type then, even if it is an
15168            --  interface, the operations are inherited from the primary
15169            --  dispatch table and are in the proper order. If we detect here
15170            --  that primitives are not in the same order we traverse the list
15171            --  of primitive operations of the actual to find the one that
15172            --  implements the interface primitive.
15173
15174            if Need_Search
15175              or else
15176                (Present (Generic_Actual)
15177                  and then Present (Act_Subp)
15178                  and then not
15179                    (Primitive_Names_Match (Subp, Act_Subp)
15180                       and then
15181                     Type_Conformant (Subp, Act_Subp,
15182                                      Skip_Controlling_Formals => True)))
15183            then
15184               pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
15185                                               Use_Full_View => True));
15186
15187               --  Remember that we need searching for all pending primitives
15188
15189               Need_Search := True;
15190
15191               --  Handle entities associated with interface primitives
15192
15193               if Present (Alias_Subp)
15194                 and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
15195                 and then not Is_Predefined_Dispatching_Operation (Subp)
15196               then
15197                  --  Search for the primitive in the homonym chain
15198
15199                  Act_Subp :=
15200                    Find_Primitive_Covering_Interface
15201                      (Tagged_Type => Generic_Actual,
15202                       Iface_Prim  => Alias_Subp);
15203
15204                  --  Previous search may not locate primitives covering
15205                  --  interfaces defined in generics units or instantiations.
15206                  --  (it fails if the covering primitive has formals whose
15207                  --  type is also defined in generics or instantiations).
15208                  --  In such case we search in the list of primitives of the
15209                  --  generic actual for the internal entity that links the
15210                  --  interface primitive and the covering primitive.
15211
15212                  if No (Act_Subp)
15213                    and then Is_Generic_Type (Parent_Type)
15214                  then
15215                     --  This code has been designed to handle only generic
15216                     --  formals that implement interfaces that are defined
15217                     --  in a generic unit or instantiation. If this code is
15218                     --  needed for other cases we must review it because
15219                     --  (given that it relies on Original_Location to locate
15220                     --  the primitive of Generic_Actual that covers the
15221                     --  interface) it could leave linked through attribute
15222                     --  Alias entities of unrelated instantiations).
15223
15224                     pragma Assert
15225                       (Is_Generic_Unit
15226                          (Scope (Find_Dispatching_Type (Alias_Subp)))
15227                         or else
15228                           Instantiation_Depth
15229                             (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
15230
15231                     declare
15232                        Iface_Prim_Loc : constant Source_Ptr :=
15233                                         Original_Location (Sloc (Alias_Subp));
15234
15235                        Elmt : Elmt_Id;
15236                        Prim : Entity_Id;
15237
15238                     begin
15239                        Elmt :=
15240                          First_Elmt (Primitive_Operations (Generic_Actual));
15241
15242                        Search : while Present (Elmt) loop
15243                           Prim := Node (Elmt);
15244
15245                           if Present (Interface_Alias (Prim))
15246                             and then Original_Location
15247                                        (Sloc (Interface_Alias (Prim))) =
15248                                                              Iface_Prim_Loc
15249                           then
15250                              Act_Subp := Alias (Prim);
15251                              exit Search;
15252                           end if;
15253
15254                           Next_Elmt (Elmt);
15255                        end loop Search;
15256                     end;
15257                  end if;
15258
15259                  pragma Assert (Present (Act_Subp)
15260                    or else Is_Abstract_Type (Generic_Actual)
15261                    or else Serious_Errors_Detected > 0);
15262
15263               --  Handle predefined primitives plus the rest of user-defined
15264               --  primitives
15265
15266               else
15267                  Act_Elmt := First_Elmt (Act_List);
15268                  while Present (Act_Elmt) loop
15269                     Act_Subp := Node (Act_Elmt);
15270
15271                     exit when Primitive_Names_Match (Subp, Act_Subp)
15272                       and then Type_Conformant
15273                                  (Subp, Act_Subp,
15274                                   Skip_Controlling_Formals => True)
15275                       and then No (Interface_Alias (Act_Subp));
15276
15277                     Next_Elmt (Act_Elmt);
15278                  end loop;
15279
15280                  if No (Act_Elmt) then
15281                     Act_Subp := Empty;
15282                  end if;
15283               end if;
15284            end if;
15285
15286            --   Case 1: If the parent is a limited interface then it has the
15287            --   predefined primitives of synchronized interfaces. However, the
15288            --   actual type may be a non-limited type and hence it does not
15289            --   have such primitives.
15290
15291            if Present (Generic_Actual)
15292              and then not Present (Act_Subp)
15293              and then Is_Limited_Interface (Parent_Base)
15294              and then Is_Predefined_Interface_Primitive (Subp)
15295            then
15296               null;
15297
15298            --  Case 2: Inherit entities associated with interfaces that were
15299            --  not covered by the parent type. We exclude here null interface
15300            --  primitives because they do not need special management.
15301
15302            --  We also exclude interface operations that are renamings. If the
15303            --  subprogram is an explicit renaming of an interface primitive,
15304            --  it is a regular primitive operation, and the presence of its
15305            --  alias is not relevant: it has to be derived like any other
15306            --  primitive.
15307
15308            elsif Present (Alias (Subp))
15309              and then Nkind (Unit_Declaration_Node (Subp)) /=
15310                                            N_Subprogram_Renaming_Declaration
15311              and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
15312              and then not
15313                (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
15314                  and then Null_Present (Parent (Alias_Subp)))
15315            then
15316               --  If this is an abstract private type then we transfer the
15317               --  derivation of the interface primitive from the partial view
15318               --  to the full view. This is safe because all the interfaces
15319               --  must be visible in the partial view. Done to avoid adding
15320               --  a new interface derivation to the private part of the
15321               --  enclosing package; otherwise this new derivation would be
15322               --  decorated as hidden when the analysis of the enclosing
15323               --  package completes.
15324
15325               if Is_Abstract_Type (Derived_Type)
15326                 and then In_Private_Part (Current_Scope)
15327                 and then Has_Private_Declaration (Derived_Type)
15328               then
15329                  declare
15330                     Partial_View : Entity_Id;
15331                     Elmt         : Elmt_Id;
15332                     Ent          : Entity_Id;
15333
15334                  begin
15335                     Partial_View := First_Entity (Current_Scope);
15336                     loop
15337                        exit when No (Partial_View)
15338                          or else (Has_Private_Declaration (Partial_View)
15339                                    and then
15340                                      Full_View (Partial_View) = Derived_Type);
15341
15342                        Next_Entity (Partial_View);
15343                     end loop;
15344
15345                     --  If the partial view was not found then the source code
15346                     --  has errors and the derivation is not needed.
15347
15348                     if Present (Partial_View) then
15349                        Elmt :=
15350                          First_Elmt (Primitive_Operations (Partial_View));
15351                        while Present (Elmt) loop
15352                           Ent := Node (Elmt);
15353
15354                           if Present (Alias (Ent))
15355                             and then Ultimate_Alias (Ent) = Alias (Subp)
15356                           then
15357                              Append_Elmt
15358                                (Ent, Primitive_Operations (Derived_Type));
15359                              exit;
15360                           end if;
15361
15362                           Next_Elmt (Elmt);
15363                        end loop;
15364
15365                        --  If the interface primitive was not found in the
15366                        --  partial view then this interface primitive was
15367                        --  overridden. We add a derivation to activate in
15368                        --  Derive_Progenitor_Subprograms the machinery to
15369                        --  search for it.
15370
15371                        if No (Elmt) then
15372                           Derive_Interface_Subprogram
15373                             (New_Subp    => New_Subp,
15374                              Subp        => Subp,
15375                              Actual_Subp => Act_Subp);
15376                        end if;
15377                     end if;
15378                  end;
15379               else
15380                  Derive_Interface_Subprogram
15381                    (New_Subp     => New_Subp,
15382                     Subp         => Subp,
15383                     Actual_Subp  => Act_Subp);
15384               end if;
15385
15386            --  Case 3: Common derivation
15387
15388            else
15389               Derive_Subprogram
15390                 (New_Subp     => New_Subp,
15391                  Parent_Subp  => Subp,
15392                  Derived_Type => Derived_Type,
15393                  Parent_Type  => Parent_Base,
15394                  Actual_Subp  => Act_Subp);
15395            end if;
15396
15397            --  No need to update Act_Elm if we must search for the
15398            --  corresponding operation in the generic actual
15399
15400            if not Need_Search
15401              and then Present (Act_Elmt)
15402            then
15403               Next_Elmt (Act_Elmt);
15404               Act_Subp := Node (Act_Elmt);
15405            end if;
15406
15407            <<Continue>>
15408            Next_Elmt (Elmt);
15409         end loop;
15410
15411         --  Inherit additional operations from progenitors. If the derived
15412         --  type is a generic actual, there are not new primitive operations
15413         --  for the type because it has those of the actual, and therefore
15414         --  nothing needs to be done. The renamings generated above are not
15415         --  primitive operations, and their purpose is simply to make the
15416         --  proper operations visible within an instantiation.
15417
15418         if No (Generic_Actual) then
15419            Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
15420         end if;
15421      end if;
15422
15423      --  Final check: Direct descendants must have their primitives in the
15424      --  same order. We exclude from this test untagged types and instances
15425      --  of formal derived types. We skip this test if we have already
15426      --  reported serious errors in the sources.
15427
15428      pragma Assert (not Is_Tagged_Type (Derived_Type)
15429        or else Present (Generic_Actual)
15430        or else Serious_Errors_Detected > 0
15431        or else Check_Derived_Type);
15432   end Derive_Subprograms;
15433
15434   --------------------------------
15435   -- Derived_Standard_Character --
15436   --------------------------------
15437
15438   procedure Derived_Standard_Character
15439     (N            : Node_Id;
15440      Parent_Type  : Entity_Id;
15441      Derived_Type : Entity_Id)
15442   is
15443      Loc           : constant Source_Ptr := Sloc (N);
15444      Def           : constant Node_Id    := Type_Definition (N);
15445      Indic         : constant Node_Id    := Subtype_Indication (Def);
15446      Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
15447      Implicit_Base : constant Entity_Id  :=
15448                        Create_Itype
15449                          (E_Enumeration_Type, N, Derived_Type, 'B');
15450
15451      Lo : Node_Id;
15452      Hi : Node_Id;
15453
15454   begin
15455      Discard_Node (Process_Subtype (Indic, N));
15456
15457      Set_Etype     (Implicit_Base, Parent_Base);
15458      Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
15459      Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
15460
15461      Set_Is_Character_Type  (Implicit_Base, True);
15462      Set_Has_Delayed_Freeze (Implicit_Base);
15463
15464      --  The bounds of the implicit base are the bounds of the parent base.
15465      --  Note that their type is the parent base.
15466
15467      Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
15468      Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
15469
15470      Set_Scalar_Range (Implicit_Base,
15471        Make_Range (Loc,
15472          Low_Bound  => Lo,
15473          High_Bound => Hi));
15474
15475      Conditional_Delay (Derived_Type, Parent_Type);
15476
15477      Set_Ekind (Derived_Type, E_Enumeration_Subtype);
15478      Set_Etype (Derived_Type, Implicit_Base);
15479      Set_Size_Info         (Derived_Type, Parent_Type);
15480
15481      if Unknown_RM_Size (Derived_Type) then
15482         Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
15483      end if;
15484
15485      Set_Is_Character_Type (Derived_Type, True);
15486
15487      if Nkind (Indic) /= N_Subtype_Indication then
15488
15489         --  If no explicit constraint, the bounds are those
15490         --  of the parent type.
15491
15492         Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
15493         Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
15494         Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
15495      end if;
15496
15497      Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
15498
15499      --  Because the implicit base is used in the conversion of the bounds, we
15500      --  have to freeze it now. This is similar to what is done for numeric
15501      --  types, and it equally suspicious, but otherwise a non-static bound
15502      --  will have a reference to an unfrozen type, which is rejected by Gigi
15503      --  (???). This requires specific care for definition of stream
15504      --  attributes. For details, see comments at the end of
15505      --  Build_Derived_Numeric_Type.
15506
15507      Freeze_Before (N, Implicit_Base);
15508   end Derived_Standard_Character;
15509
15510   ------------------------------
15511   -- Derived_Type_Declaration --
15512   ------------------------------
15513
15514   procedure Derived_Type_Declaration
15515     (T             : Entity_Id;
15516      N             : Node_Id;
15517      Is_Completion : Boolean)
15518   is
15519      Parent_Type  : Entity_Id;
15520
15521      function Comes_From_Generic (Typ : Entity_Id) return Boolean;
15522      --  Check whether the parent type is a generic formal, or derives
15523      --  directly or indirectly from one.
15524
15525      ------------------------
15526      -- Comes_From_Generic --
15527      ------------------------
15528
15529      function Comes_From_Generic (Typ : Entity_Id) return Boolean is
15530      begin
15531         if Is_Generic_Type (Typ) then
15532            return True;
15533
15534         elsif Is_Generic_Type (Root_Type (Parent_Type)) then
15535            return True;
15536
15537         elsif Is_Private_Type (Typ)
15538           and then Present (Full_View (Typ))
15539           and then Is_Generic_Type (Root_Type (Full_View (Typ)))
15540         then
15541            return True;
15542
15543         elsif Is_Generic_Actual_Type (Typ) then
15544            return True;
15545
15546         else
15547            return False;
15548         end if;
15549      end Comes_From_Generic;
15550
15551      --  Local variables
15552
15553      Def          : constant Node_Id := Type_Definition (N);
15554      Iface_Def    : Node_Id;
15555      Indic        : constant Node_Id := Subtype_Indication (Def);
15556      Extension    : constant Node_Id := Record_Extension_Part (Def);
15557      Parent_Node  : Node_Id;
15558      Taggd        : Boolean;
15559
15560   --  Start of processing for Derived_Type_Declaration
15561
15562   begin
15563      Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
15564
15565      --  Ada 2005 (AI-251): In case of interface derivation check that the
15566      --  parent is also an interface.
15567
15568      if Interface_Present (Def) then
15569         Check_SPARK_05_Restriction ("interface is not allowed", Def);
15570
15571         if not Is_Interface (Parent_Type) then
15572            Diagnose_Interface (Indic, Parent_Type);
15573
15574         else
15575            Parent_Node := Parent (Base_Type (Parent_Type));
15576            Iface_Def   := Type_Definition (Parent_Node);
15577
15578            --  Ada 2005 (AI-251): Limited interfaces can only inherit from
15579            --  other limited interfaces.
15580
15581            if Limited_Present (Def) then
15582               if Limited_Present (Iface_Def) then
15583                  null;
15584
15585               elsif Protected_Present (Iface_Def) then
15586                  Error_Msg_NE
15587                    ("descendant of& must be declared"
15588                       & " as a protected interface",
15589                         N, Parent_Type);
15590
15591               elsif Synchronized_Present (Iface_Def) then
15592                  Error_Msg_NE
15593                    ("descendant of& must be declared"
15594                       & " as a synchronized interface",
15595                         N, Parent_Type);
15596
15597               elsif Task_Present (Iface_Def) then
15598                  Error_Msg_NE
15599                    ("descendant of& must be declared as a task interface",
15600                       N, Parent_Type);
15601
15602               else
15603                  Error_Msg_N
15604                    ("(Ada 2005) limited interface cannot "
15605                     & "inherit from non-limited interface", Indic);
15606               end if;
15607
15608            --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
15609            --  from non-limited or limited interfaces.
15610
15611            elsif not Protected_Present (Def)
15612              and then not Synchronized_Present (Def)
15613              and then not Task_Present (Def)
15614            then
15615               if Limited_Present (Iface_Def) then
15616                  null;
15617
15618               elsif Protected_Present (Iface_Def) then
15619                  Error_Msg_NE
15620                    ("descendant of& must be declared"
15621                       & " as a protected interface",
15622                         N, Parent_Type);
15623
15624               elsif Synchronized_Present (Iface_Def) then
15625                  Error_Msg_NE
15626                    ("descendant of& must be declared"
15627                       & " as a synchronized interface",
15628                         N, Parent_Type);
15629
15630               elsif Task_Present (Iface_Def) then
15631                  Error_Msg_NE
15632                    ("descendant of& must be declared as a task interface",
15633                       N, Parent_Type);
15634               else
15635                  null;
15636               end if;
15637            end if;
15638         end if;
15639      end if;
15640
15641      if Is_Tagged_Type (Parent_Type)
15642        and then Is_Concurrent_Type (Parent_Type)
15643        and then not Is_Interface (Parent_Type)
15644      then
15645         Error_Msg_N
15646           ("parent type of a record extension cannot be "
15647            & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
15648         Set_Etype (T, Any_Type);
15649         return;
15650      end if;
15651
15652      --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
15653      --  interfaces
15654
15655      if Is_Tagged_Type (Parent_Type)
15656        and then Is_Non_Empty_List (Interface_List (Def))
15657      then
15658         declare
15659            Intf : Node_Id;
15660            T    : Entity_Id;
15661
15662         begin
15663            Intf := First (Interface_List (Def));
15664            while Present (Intf) loop
15665               T := Find_Type_Of_Subtype_Indic (Intf);
15666
15667               if not Is_Interface (T) then
15668                  Diagnose_Interface (Intf, T);
15669
15670               --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
15671               --  a limited type from having a nonlimited progenitor.
15672
15673               elsif (Limited_Present (Def)
15674                       or else (not Is_Interface (Parent_Type)
15675                                 and then Is_Limited_Type (Parent_Type)))
15676                 and then not Is_Limited_Interface (T)
15677               then
15678                  Error_Msg_NE
15679                   ("progenitor interface& of limited type must be limited",
15680                     N, T);
15681               end if;
15682
15683               Next (Intf);
15684            end loop;
15685         end;
15686      end if;
15687
15688      if Parent_Type = Any_Type
15689        or else Etype (Parent_Type) = Any_Type
15690        or else (Is_Class_Wide_Type (Parent_Type)
15691                  and then Etype (Parent_Type) = T)
15692      then
15693         --  If Parent_Type is undefined or illegal, make new type into a
15694         --  subtype of Any_Type, and set a few attributes to prevent cascaded
15695         --  errors. If this is a self-definition, emit error now.
15696
15697         if T = Parent_Type or else T = Etype (Parent_Type) then
15698            Error_Msg_N ("type cannot be used in its own definition", Indic);
15699         end if;
15700
15701         Set_Ekind        (T, Ekind (Parent_Type));
15702         Set_Etype        (T, Any_Type);
15703         Set_Scalar_Range (T, Scalar_Range (Any_Type));
15704
15705         if Is_Tagged_Type (T)
15706           and then Is_Record_Type (T)
15707         then
15708            Set_Direct_Primitive_Operations (T, New_Elmt_List);
15709         end if;
15710
15711         return;
15712      end if;
15713
15714      --  Ada 2005 (AI-251): The case in which the parent of the full-view is
15715      --  an interface is special because the list of interfaces in the full
15716      --  view can be given in any order. For example:
15717
15718      --     type A is interface;
15719      --     type B is interface and A;
15720      --     type D is new B with private;
15721      --   private
15722      --     type D is new A and B with null record; -- 1 --
15723
15724      --  In this case we perform the following transformation of -1-:
15725
15726      --     type D is new B and A with null record;
15727
15728      --  If the parent of the full-view covers the parent of the partial-view
15729      --  we have two possible cases:
15730
15731      --     1) They have the same parent
15732      --     2) The parent of the full-view implements some further interfaces
15733
15734      --  In both cases we do not need to perform the transformation. In the
15735      --  first case the source program is correct and the transformation is
15736      --  not needed; in the second case the source program does not fulfill
15737      --  the no-hidden interfaces rule (AI-396) and the error will be reported
15738      --  later.
15739
15740      --  This transformation not only simplifies the rest of the analysis of
15741      --  this type declaration but also simplifies the correct generation of
15742      --  the object layout to the expander.
15743
15744      if In_Private_Part (Current_Scope)
15745        and then Is_Interface (Parent_Type)
15746      then
15747         declare
15748            Iface               : Node_Id;
15749            Partial_View        : Entity_Id;
15750            Partial_View_Parent : Entity_Id;
15751            New_Iface           : Node_Id;
15752
15753         begin
15754            --  Look for the associated private type declaration
15755
15756            Partial_View := First_Entity (Current_Scope);
15757            loop
15758               exit when No (Partial_View)
15759                 or else (Has_Private_Declaration (Partial_View)
15760                           and then Full_View (Partial_View) = T);
15761
15762               Next_Entity (Partial_View);
15763            end loop;
15764
15765            --  If the partial view was not found then the source code has
15766            --  errors and the transformation is not needed.
15767
15768            if Present (Partial_View) then
15769               Partial_View_Parent := Etype (Partial_View);
15770
15771               --  If the parent of the full-view covers the parent of the
15772               --  partial-view we have nothing else to do.
15773
15774               if Interface_Present_In_Ancestor
15775                    (Parent_Type, Partial_View_Parent)
15776               then
15777                  null;
15778
15779               --  Traverse the list of interfaces of the full-view to look
15780               --  for the parent of the partial-view and perform the tree
15781               --  transformation.
15782
15783               else
15784                  Iface := First (Interface_List (Def));
15785                  while Present (Iface) loop
15786                     if Etype (Iface) = Etype (Partial_View) then
15787                        Rewrite (Subtype_Indication (Def),
15788                          New_Copy (Subtype_Indication
15789                                     (Parent (Partial_View))));
15790
15791                        New_Iface :=
15792                          Make_Identifier (Sloc (N), Chars (Parent_Type));
15793                        Append (New_Iface, Interface_List (Def));
15794
15795                        --  Analyze the transformed code
15796
15797                        Derived_Type_Declaration (T, N, Is_Completion);
15798                        return;
15799                     end if;
15800
15801                     Next (Iface);
15802                  end loop;
15803               end if;
15804            end if;
15805         end;
15806      end if;
15807
15808      --  Only composite types other than array types are allowed to have
15809      --  discriminants.
15810
15811      if Present (Discriminant_Specifications (N)) then
15812         if (Is_Elementary_Type (Parent_Type)
15813               or else
15814             Is_Array_Type      (Parent_Type))
15815           and then not Error_Posted (N)
15816         then
15817            Error_Msg_N
15818              ("elementary or array type cannot have discriminants",
15819               Defining_Identifier (First (Discriminant_Specifications (N))));
15820            Set_Has_Discriminants (T, False);
15821
15822         --  The type is allowed to have discriminants
15823
15824         else
15825            Check_SPARK_05_Restriction ("discriminant type is not allowed", N);
15826         end if;
15827      end if;
15828
15829      --  In Ada 83, a derived type defined in a package specification cannot
15830      --  be used for further derivation until the end of its visible part.
15831      --  Note that derivation in the private part of the package is allowed.
15832
15833      if Ada_Version = Ada_83
15834        and then Is_Derived_Type (Parent_Type)
15835        and then In_Visible_Part (Scope (Parent_Type))
15836      then
15837         if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
15838            Error_Msg_N
15839              ("(Ada 83): premature use of type for derivation", Indic);
15840         end if;
15841      end if;
15842
15843      --  Check for early use of incomplete or private type
15844
15845      if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
15846         Error_Msg_N ("premature derivation of incomplete type", Indic);
15847         return;
15848
15849      elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
15850              and then not Comes_From_Generic (Parent_Type))
15851        or else Has_Private_Component (Parent_Type)
15852      then
15853         --  The ancestor type of a formal type can be incomplete, in which
15854         --  case only the operations of the partial view are available in the
15855         --  generic. Subsequent checks may be required when the full view is
15856         --  analyzed to verify that a derivation from a tagged type has an
15857         --  extension.
15858
15859         if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
15860            null;
15861
15862         elsif No (Underlying_Type (Parent_Type))
15863           or else Has_Private_Component (Parent_Type)
15864         then
15865            Error_Msg_N
15866              ("premature derivation of derived or private type", Indic);
15867
15868            --  Flag the type itself as being in error, this prevents some
15869            --  nasty problems with subsequent uses of the malformed type.
15870
15871            Set_Error_Posted (T);
15872
15873         --  Check that within the immediate scope of an untagged partial
15874         --  view it's illegal to derive from the partial view if the
15875         --  full view is tagged. (7.3(7))
15876
15877         --  We verify that the Parent_Type is a partial view by checking
15878         --  that it is not a Full_Type_Declaration (i.e. a private type or
15879         --  private extension declaration), to distinguish a partial view
15880         --  from  a derivation from a private type which also appears as
15881         --  E_Private_Type. If the parent base type is not declared in an
15882         --  enclosing scope there is no need to check.
15883
15884         elsif Present (Full_View (Parent_Type))
15885           and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
15886           and then not Is_Tagged_Type (Parent_Type)
15887           and then Is_Tagged_Type (Full_View (Parent_Type))
15888           and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
15889         then
15890            Error_Msg_N
15891              ("premature derivation from type with tagged full view",
15892                Indic);
15893         end if;
15894      end if;
15895
15896      --  Check that form of derivation is appropriate
15897
15898      Taggd := Is_Tagged_Type (Parent_Type);
15899
15900      --  Set the parent type to the class-wide type's specific type in this
15901      --  case to prevent cascading errors
15902
15903      if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
15904         Error_Msg_N ("parent type must not be a class-wide type", Indic);
15905         Set_Etype (T, Etype (Parent_Type));
15906         return;
15907      end if;
15908
15909      if Present (Extension) and then not Taggd then
15910         Error_Msg_N
15911           ("type derived from untagged type cannot have extension", Indic);
15912
15913      elsif No (Extension) and then Taggd then
15914
15915         --  If this declaration is within a private part (or body) of a
15916         --  generic instantiation then the derivation is allowed (the parent
15917         --  type can only appear tagged in this case if it's a generic actual
15918         --  type, since it would otherwise have been rejected in the analysis
15919         --  of the generic template).
15920
15921         if not Is_Generic_Actual_Type (Parent_Type)
15922           or else In_Visible_Part (Scope (Parent_Type))
15923         then
15924            if Is_Class_Wide_Type (Parent_Type) then
15925               Error_Msg_N
15926                 ("parent type must not be a class-wide type", Indic);
15927
15928               --  Use specific type to prevent cascaded errors.
15929
15930               Parent_Type := Etype (Parent_Type);
15931
15932            else
15933               Error_Msg_N
15934                 ("type derived from tagged type must have extension", Indic);
15935            end if;
15936         end if;
15937      end if;
15938
15939      --  AI-443: Synchronized formal derived types require a private
15940      --  extension. There is no point in checking the ancestor type or
15941      --  the progenitors since the construct is wrong to begin with.
15942
15943      if Ada_Version >= Ada_2005
15944        and then Is_Generic_Type (T)
15945        and then Present (Original_Node (N))
15946      then
15947         declare
15948            Decl : constant Node_Id := Original_Node (N);
15949
15950         begin
15951            if Nkind (Decl) = N_Formal_Type_Declaration
15952              and then Nkind (Formal_Type_Definition (Decl)) =
15953                                          N_Formal_Derived_Type_Definition
15954              and then Synchronized_Present (Formal_Type_Definition (Decl))
15955              and then No (Extension)
15956
15957               --  Avoid emitting a duplicate error message
15958
15959              and then not Error_Posted (Indic)
15960            then
15961               Error_Msg_N
15962                 ("synchronized derived type must have extension", N);
15963            end if;
15964         end;
15965      end if;
15966
15967      if Null_Exclusion_Present (Def)
15968        and then not Is_Access_Type (Parent_Type)
15969      then
15970         Error_Msg_N ("null exclusion can only apply to an access type", N);
15971      end if;
15972
15973      --  Avoid deriving parent primitives of underlying record views
15974
15975      Build_Derived_Type (N, Parent_Type, T, Is_Completion,
15976        Derive_Subps => not Is_Underlying_Record_View (T));
15977
15978      --  AI-419: The parent type of an explicitly limited derived type must
15979      --  be a limited type or a limited interface.
15980
15981      if Limited_Present (Def) then
15982         Set_Is_Limited_Record (T);
15983
15984         if Is_Interface (T) then
15985            Set_Is_Limited_Interface (T);
15986         end if;
15987
15988         if not Is_Limited_Type (Parent_Type)
15989           and then
15990             (not Is_Interface (Parent_Type)
15991               or else not Is_Limited_Interface (Parent_Type))
15992         then
15993            --  AI05-0096: a derivation in the private part of an instance is
15994            --  legal if the generic formal is untagged limited, and the actual
15995            --  is non-limited.
15996
15997            if Is_Generic_Actual_Type (Parent_Type)
15998              and then In_Private_Part (Current_Scope)
15999              and then
16000                not Is_Tagged_Type
16001                      (Generic_Parent_Type (Parent (Parent_Type)))
16002            then
16003               null;
16004
16005            else
16006               Error_Msg_NE
16007                 ("parent type& of limited type must be limited",
16008                  N, Parent_Type);
16009            end if;
16010         end if;
16011      end if;
16012
16013      --  In SPARK, there are no derived type definitions other than type
16014      --  extensions of tagged record types.
16015
16016      if No (Extension) then
16017         Check_SPARK_05_Restriction
16018           ("derived type is not allowed", Original_Node (N));
16019      end if;
16020   end Derived_Type_Declaration;
16021
16022   ------------------------
16023   -- Diagnose_Interface --
16024   ------------------------
16025
16026   procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
16027   begin
16028      if not Is_Interface (E) and then  E /= Any_Type then
16029         Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
16030      end if;
16031   end Diagnose_Interface;
16032
16033   ----------------------------------
16034   -- Enumeration_Type_Declaration --
16035   ----------------------------------
16036
16037   procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16038      Ev     : Uint;
16039      L      : Node_Id;
16040      R_Node : Node_Id;
16041      B_Node : Node_Id;
16042
16043   begin
16044      --  Create identifier node representing lower bound
16045
16046      B_Node := New_Node (N_Identifier, Sloc (Def));
16047      L := First (Literals (Def));
16048      Set_Chars (B_Node, Chars (L));
16049      Set_Entity (B_Node,  L);
16050      Set_Etype (B_Node, T);
16051      Set_Is_Static_Expression (B_Node, True);
16052
16053      R_Node := New_Node (N_Range, Sloc (Def));
16054      Set_Low_Bound  (R_Node, B_Node);
16055
16056      Set_Ekind (T, E_Enumeration_Type);
16057      Set_First_Literal (T, L);
16058      Set_Etype (T, T);
16059      Set_Is_Constrained (T);
16060
16061      Ev := Uint_0;
16062
16063      --  Loop through literals of enumeration type setting pos and rep values
16064      --  except that if the Ekind is already set, then it means the literal
16065      --  was already constructed (case of a derived type declaration and we
16066      --  should not disturb the Pos and Rep values.
16067
16068      while Present (L) loop
16069         if Ekind (L) /= E_Enumeration_Literal then
16070            Set_Ekind (L, E_Enumeration_Literal);
16071            Set_Enumeration_Pos (L, Ev);
16072            Set_Enumeration_Rep (L, Ev);
16073            Set_Is_Known_Valid  (L, True);
16074         end if;
16075
16076         Set_Etype (L, T);
16077         New_Overloaded_Entity (L);
16078         Generate_Definition (L);
16079         Set_Convention (L, Convention_Intrinsic);
16080
16081         --  Case of character literal
16082
16083         if Nkind (L) = N_Defining_Character_Literal then
16084            Set_Is_Character_Type (T, True);
16085
16086            --  Check violation of No_Wide_Characters
16087
16088            if Restriction_Check_Required (No_Wide_Characters) then
16089               Get_Name_String (Chars (L));
16090
16091               if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
16092                  Check_Restriction (No_Wide_Characters, L);
16093               end if;
16094            end if;
16095         end if;
16096
16097         Ev := Ev + 1;
16098         Next (L);
16099      end loop;
16100
16101      --  Now create a node representing upper bound
16102
16103      B_Node := New_Node (N_Identifier, Sloc (Def));
16104      Set_Chars (B_Node, Chars (Last (Literals (Def))));
16105      Set_Entity (B_Node,  Last (Literals (Def)));
16106      Set_Etype (B_Node, T);
16107      Set_Is_Static_Expression (B_Node, True);
16108
16109      Set_High_Bound (R_Node, B_Node);
16110
16111      --  Initialize various fields of the type. Some of this information
16112      --  may be overwritten later through rep.clauses.
16113
16114      Set_Scalar_Range    (T, R_Node);
16115      Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
16116      Set_Enum_Esize      (T);
16117      Set_Enum_Pos_To_Rep (T, Empty);
16118
16119      --  Set Discard_Names if configuration pragma set, or if there is
16120      --  a parameterless pragma in the current declarative region
16121
16122      if Global_Discard_Names or else Discard_Names (Scope (T)) then
16123         Set_Discard_Names (T);
16124      end if;
16125
16126      --  Process end label if there is one
16127
16128      if Present (Def) then
16129         Process_End_Label (Def, 'e', T);
16130      end if;
16131   end Enumeration_Type_Declaration;
16132
16133   ---------------------------------
16134   -- Expand_To_Stored_Constraint --
16135   ---------------------------------
16136
16137   function Expand_To_Stored_Constraint
16138     (Typ        : Entity_Id;
16139      Constraint : Elist_Id) return Elist_Id
16140   is
16141      Explicitly_Discriminated_Type : Entity_Id;
16142      Expansion    : Elist_Id;
16143      Discriminant : Entity_Id;
16144
16145      function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
16146      --  Find the nearest type that actually specifies discriminants
16147
16148      ---------------------------------
16149      -- Type_With_Explicit_Discrims --
16150      ---------------------------------
16151
16152      function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
16153         Typ : constant E := Base_Type (Id);
16154
16155      begin
16156         if Ekind (Typ) in Incomplete_Or_Private_Kind then
16157            if Present (Full_View (Typ)) then
16158               return Type_With_Explicit_Discrims (Full_View (Typ));
16159            end if;
16160
16161         else
16162            if Has_Discriminants (Typ) then
16163               return Typ;
16164            end if;
16165         end if;
16166
16167         if Etype (Typ) = Typ then
16168            return Empty;
16169         elsif Has_Discriminants (Typ) then
16170            return Typ;
16171         else
16172            return Type_With_Explicit_Discrims (Etype (Typ));
16173         end if;
16174
16175      end Type_With_Explicit_Discrims;
16176
16177   --  Start of processing for Expand_To_Stored_Constraint
16178
16179   begin
16180      if No (Constraint) or else Is_Empty_Elmt_List (Constraint) then
16181         return No_Elist;
16182      end if;
16183
16184      Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
16185
16186      if No (Explicitly_Discriminated_Type) then
16187         return No_Elist;
16188      end if;
16189
16190      Expansion := New_Elmt_List;
16191
16192      Discriminant :=
16193         First_Stored_Discriminant (Explicitly_Discriminated_Type);
16194      while Present (Discriminant) loop
16195         Append_Elmt
16196           (Get_Discriminant_Value
16197              (Discriminant, Explicitly_Discriminated_Type, Constraint),
16198            To => Expansion);
16199         Next_Stored_Discriminant (Discriminant);
16200      end loop;
16201
16202      return Expansion;
16203   end Expand_To_Stored_Constraint;
16204
16205   ---------------------------
16206   -- Find_Hidden_Interface --
16207   ---------------------------
16208
16209   function Find_Hidden_Interface
16210     (Src  : Elist_Id;
16211      Dest : Elist_Id) return Entity_Id
16212   is
16213      Iface      : Entity_Id;
16214      Iface_Elmt : Elmt_Id;
16215
16216   begin
16217      if Present (Src) and then Present (Dest) then
16218         Iface_Elmt := First_Elmt (Src);
16219         while Present (Iface_Elmt) loop
16220            Iface := Node (Iface_Elmt);
16221
16222            if Is_Interface (Iface)
16223              and then not Contain_Interface (Iface, Dest)
16224            then
16225               return Iface;
16226            end if;
16227
16228            Next_Elmt (Iface_Elmt);
16229         end loop;
16230      end if;
16231
16232      return Empty;
16233   end Find_Hidden_Interface;
16234
16235   --------------------
16236   -- Find_Type_Name --
16237   --------------------
16238
16239   function Find_Type_Name (N : Node_Id) return Entity_Id is
16240      Id       : constant Entity_Id := Defining_Identifier (N);
16241      Prev     : Entity_Id;
16242      New_Id   : Entity_Id;
16243      Prev_Par : Node_Id;
16244
16245      procedure Check_Duplicate_Aspects;
16246      --  Check that aspects specified in a completion have not been specified
16247      --  already in the partial view. Type_Invariant and others can be
16248      --  specified on either view but never on both.
16249
16250      procedure Tag_Mismatch;
16251      --  Diagnose a tagged partial view whose full view is untagged.
16252      --  We post the message on the full view, with a reference to
16253      --  the previous partial view. The partial view can be private
16254      --  or incomplete, and these are handled in a different manner,
16255      --  so we determine the position of the error message from the
16256      --  respective slocs of both.
16257
16258      -----------------------------
16259      -- Check_Duplicate_Aspects --
16260      -----------------------------
16261      procedure Check_Duplicate_Aspects is
16262         Prev_Aspects   : constant List_Id := Aspect_Specifications (Prev_Par);
16263         Full_Aspects   : constant List_Id := Aspect_Specifications (N);
16264         F_Spec, P_Spec : Node_Id;
16265
16266      begin
16267         if Present (Prev_Aspects) and then Present (Full_Aspects) then
16268            F_Spec := First (Full_Aspects);
16269            while Present (F_Spec) loop
16270               P_Spec := First (Prev_Aspects);
16271               while Present (P_Spec) loop
16272                  if Chars (Identifier (P_Spec)) = Chars (Identifier (F_Spec))
16273                  then
16274                     Error_Msg_N
16275                       ("aspect already specified in private declaration",
16276                         F_Spec);
16277                     Remove (F_Spec);
16278                     return;
16279                  end if;
16280
16281                  Next (P_Spec);
16282               end loop;
16283
16284               Next (F_Spec);
16285            end loop;
16286         end if;
16287      end Check_Duplicate_Aspects;
16288
16289      ------------------
16290      -- Tag_Mismatch --
16291      ------------------
16292
16293      procedure Tag_Mismatch is
16294      begin
16295         if Sloc (Prev) < Sloc (Id) then
16296            if Ada_Version >= Ada_2012
16297              and then Nkind (N) = N_Private_Type_Declaration
16298            then
16299               Error_Msg_NE
16300                 ("declaration of private } must be a tagged type ", Id, Prev);
16301            else
16302               Error_Msg_NE
16303                 ("full declaration of } must be a tagged type ", Id, Prev);
16304            end if;
16305
16306         else
16307            if Ada_Version >= Ada_2012
16308              and then Nkind (N) = N_Private_Type_Declaration
16309            then
16310               Error_Msg_NE
16311                 ("declaration of private } must be a tagged type ", Prev, Id);
16312            else
16313               Error_Msg_NE
16314                 ("full declaration of } must be a tagged type ", Prev, Id);
16315            end if;
16316         end if;
16317      end Tag_Mismatch;
16318
16319   --  Start of processing for Find_Type_Name
16320
16321   begin
16322      --  Find incomplete declaration, if one was given
16323
16324      Prev := Current_Entity_In_Scope (Id);
16325
16326      --  New type declaration
16327
16328      if No (Prev) then
16329         Enter_Name (Id);
16330         return Id;
16331
16332      --  Previous declaration exists
16333
16334      else
16335         Prev_Par := Parent (Prev);
16336
16337         --  Error if not incomplete/private case except if previous
16338         --  declaration is implicit, etc. Enter_Name will emit error if
16339         --  appropriate.
16340
16341         if not Is_Incomplete_Or_Private_Type (Prev) then
16342            Enter_Name (Id);
16343            New_Id := Id;
16344
16345         --  Check invalid completion of private or incomplete type
16346
16347         elsif not Nkind_In (N, N_Full_Type_Declaration,
16348                                N_Task_Type_Declaration,
16349                                N_Protected_Type_Declaration)
16350           and then
16351             (Ada_Version < Ada_2012
16352               or else not Is_Incomplete_Type (Prev)
16353               or else not Nkind_In (N, N_Private_Type_Declaration,
16354                                        N_Private_Extension_Declaration))
16355         then
16356            --  Completion must be a full type declarations (RM 7.3(4))
16357
16358            Error_Msg_Sloc := Sloc (Prev);
16359            Error_Msg_NE ("invalid completion of }", Id, Prev);
16360
16361            --  Set scope of Id to avoid cascaded errors. Entity is never
16362            --  examined again, except when saving globals in generics.
16363
16364            Set_Scope (Id, Current_Scope);
16365            New_Id := Id;
16366
16367            --  If this is a repeated incomplete declaration, no further
16368            --  checks are possible.
16369
16370            if Nkind (N) = N_Incomplete_Type_Declaration then
16371               return Prev;
16372            end if;
16373
16374         --  Case of full declaration of incomplete type
16375
16376         elsif Ekind (Prev) = E_Incomplete_Type
16377           and then (Ada_Version < Ada_2012
16378                      or else No (Full_View (Prev))
16379                      or else not Is_Private_Type (Full_View (Prev)))
16380         then
16381            --  Indicate that the incomplete declaration has a matching full
16382            --  declaration. The defining occurrence of the incomplete
16383            --  declaration remains the visible one, and the procedure
16384            --  Get_Full_View dereferences it whenever the type is used.
16385
16386            if Present (Full_View (Prev)) then
16387               Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
16388            end if;
16389
16390            Set_Full_View (Prev, Id);
16391            Append_Entity (Id, Current_Scope);
16392            Set_Is_Public (Id, Is_Public (Prev));
16393            Set_Is_Internal (Id);
16394            New_Id := Prev;
16395
16396            --  If the incomplete view is tagged, a class_wide type has been
16397            --  created already. Use it for the private type as well, in order
16398            --  to prevent multiple incompatible class-wide types that may be
16399            --  created for self-referential anonymous access components.
16400
16401            if Is_Tagged_Type (Prev)
16402              and then Present (Class_Wide_Type (Prev))
16403            then
16404               Set_Ekind (Id, Ekind (Prev));         --  will be reset later
16405               Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
16406
16407               --  The type of the classwide type is the current Id. Previously
16408               --  this was not done for private declarations because of order-
16409               --  of elaboration issues in the back-end, but gigi now handles
16410               --  this properly.
16411
16412               Set_Etype (Class_Wide_Type (Id), Id);
16413            end if;
16414
16415         --  Case of full declaration of private type
16416
16417         else
16418            --  If the private type was a completion of an incomplete type then
16419            --  update Prev to reference the private type
16420
16421            if Ada_Version >= Ada_2012
16422              and then Ekind (Prev) = E_Incomplete_Type
16423              and then Present (Full_View (Prev))
16424              and then Is_Private_Type (Full_View (Prev))
16425            then
16426               Prev := Full_View (Prev);
16427               Prev_Par := Parent (Prev);
16428            end if;
16429
16430            if Nkind (N) = N_Full_Type_Declaration
16431              and then Nkind_In
16432                         (Type_Definition (N), N_Record_Definition,
16433                                               N_Derived_Type_Definition)
16434              and then Interface_Present (Type_Definition (N))
16435            then
16436               Error_Msg_N
16437                 ("completion of private type cannot be an interface", N);
16438            end if;
16439
16440            if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
16441               if Etype (Prev) /= Prev then
16442
16443                  --  Prev is a private subtype or a derived type, and needs
16444                  --  no completion.
16445
16446                  Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
16447                  New_Id := Id;
16448
16449               elsif Ekind (Prev) = E_Private_Type
16450                 and then Nkind_In (N, N_Task_Type_Declaration,
16451                                       N_Protected_Type_Declaration)
16452               then
16453                  Error_Msg_N
16454                   ("completion of nonlimited type cannot be limited", N);
16455
16456               elsif Ekind (Prev) = E_Record_Type_With_Private
16457                 and then Nkind_In (N, N_Task_Type_Declaration,
16458                                       N_Protected_Type_Declaration)
16459               then
16460                  if not Is_Limited_Record (Prev) then
16461                     Error_Msg_N
16462                        ("completion of nonlimited type cannot be limited", N);
16463
16464                  elsif No (Interface_List (N)) then
16465                     Error_Msg_N
16466                        ("completion of tagged private type must be tagged",
16467                         N);
16468                  end if;
16469               end if;
16470
16471            --  Ada 2005 (AI-251): Private extension declaration of a task
16472            --  type or a protected type. This case arises when covering
16473            --  interface types.
16474
16475            elsif Nkind_In (N, N_Task_Type_Declaration,
16476                               N_Protected_Type_Declaration)
16477            then
16478               null;
16479
16480            elsif Nkind (N) /= N_Full_Type_Declaration
16481              or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
16482            then
16483               Error_Msg_N
16484                 ("full view of private extension must be an extension", N);
16485
16486            elsif not (Abstract_Present (Parent (Prev)))
16487              and then Abstract_Present (Type_Definition (N))
16488            then
16489               Error_Msg_N
16490                 ("full view of non-abstract extension cannot be abstract", N);
16491            end if;
16492
16493            if not In_Private_Part (Current_Scope) then
16494               Error_Msg_N
16495                 ("declaration of full view must appear in private part", N);
16496            end if;
16497
16498            if Ada_Version >= Ada_2012 then
16499               Check_Duplicate_Aspects;
16500            end if;
16501
16502            Copy_And_Swap (Prev, Id);
16503            Set_Has_Private_Declaration (Prev);
16504            Set_Has_Private_Declaration (Id);
16505
16506            --  AI12-0133: Indicate whether we have a partial view with
16507            --  unknown discriminants, in which case initialization of objects
16508            --  of the type do not receive an invariant check.
16509
16510            Set_Partial_View_Has_Unknown_Discr
16511              (Prev, Has_Unknown_Discriminants (Id));
16512
16513            --  Preserve aspect and iterator flags that may have been set on
16514            --  the partial view.
16515
16516            Set_Has_Delayed_Aspects (Prev, Has_Delayed_Aspects (Id));
16517            Set_Has_Implicit_Dereference (Prev, Has_Implicit_Dereference (Id));
16518
16519            --  If no error, propagate freeze_node from private to full view.
16520            --  It may have been generated for an early operational item.
16521
16522            if Present (Freeze_Node (Id))
16523              and then Serious_Errors_Detected = 0
16524              and then No (Full_View (Id))
16525            then
16526               Set_Freeze_Node (Prev, Freeze_Node (Id));
16527               Set_Freeze_Node (Id, Empty);
16528               Set_First_Rep_Item (Prev, First_Rep_Item (Id));
16529            end if;
16530
16531            Set_Full_View (Id, Prev);
16532            New_Id := Prev;
16533         end if;
16534
16535         --  Verify that full declaration conforms to partial one
16536
16537         if Is_Incomplete_Or_Private_Type (Prev)
16538           and then Present (Discriminant_Specifications (Prev_Par))
16539         then
16540            if Present (Discriminant_Specifications (N)) then
16541               if Ekind (Prev) = E_Incomplete_Type then
16542                  Check_Discriminant_Conformance (N, Prev, Prev);
16543               else
16544                  Check_Discriminant_Conformance (N, Prev, Id);
16545               end if;
16546
16547            else
16548               Error_Msg_N
16549                 ("missing discriminants in full type declaration", N);
16550
16551               --  To avoid cascaded errors on subsequent use, share the
16552               --  discriminants of the partial view.
16553
16554               Set_Discriminant_Specifications (N,
16555                 Discriminant_Specifications (Prev_Par));
16556            end if;
16557         end if;
16558
16559         --  A prior untagged partial view can have an associated class-wide
16560         --  type due to use of the class attribute, and in this case the full
16561         --  type must also be tagged. This Ada 95 usage is deprecated in favor
16562         --  of incomplete tagged declarations, but we check for it.
16563
16564         if Is_Type (Prev)
16565           and then (Is_Tagged_Type (Prev)
16566                      or else Present (Class_Wide_Type (Prev)))
16567         then
16568            --  Ada 2012 (AI05-0162): A private type may be the completion of
16569            --  an incomplete type.
16570
16571            if Ada_Version >= Ada_2012
16572              and then Is_Incomplete_Type (Prev)
16573              and then Nkind_In (N, N_Private_Type_Declaration,
16574                                    N_Private_Extension_Declaration)
16575            then
16576               --  No need to check private extensions since they are tagged
16577
16578               if Nkind (N) = N_Private_Type_Declaration
16579                 and then not Tagged_Present (N)
16580               then
16581                  Tag_Mismatch;
16582               end if;
16583
16584            --  The full declaration is either a tagged type (including
16585            --  a synchronized type that implements interfaces) or a
16586            --  type extension, otherwise this is an error.
16587
16588            elsif Nkind_In (N, N_Task_Type_Declaration,
16589                               N_Protected_Type_Declaration)
16590            then
16591               if No (Interface_List (N)) and then not Error_Posted (N) then
16592                  Tag_Mismatch;
16593               end if;
16594
16595            elsif Nkind (Type_Definition (N)) = N_Record_Definition then
16596
16597               --  Indicate that the previous declaration (tagged incomplete
16598               --  or private declaration) requires the same on the full one.
16599
16600               if not Tagged_Present (Type_Definition (N)) then
16601                  Tag_Mismatch;
16602                  Set_Is_Tagged_Type (Id);
16603               end if;
16604
16605            elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
16606               if No (Record_Extension_Part (Type_Definition (N))) then
16607                  Error_Msg_NE
16608                    ("full declaration of } must be a record extension",
16609                     Prev, Id);
16610
16611                  --  Set some attributes to produce a usable full view
16612
16613                  Set_Is_Tagged_Type (Id);
16614               end if;
16615
16616            else
16617               Tag_Mismatch;
16618            end if;
16619         end if;
16620
16621         if Present (Prev)
16622           and then Nkind (Parent (Prev)) = N_Incomplete_Type_Declaration
16623           and then Present (Premature_Use (Parent (Prev)))
16624         then
16625            Error_Msg_Sloc := Sloc (N);
16626            Error_Msg_N
16627              ("\full declaration #", Premature_Use (Parent (Prev)));
16628         end if;
16629
16630         return New_Id;
16631      end if;
16632   end Find_Type_Name;
16633
16634   -------------------------
16635   -- Find_Type_Of_Object --
16636   -------------------------
16637
16638   function Find_Type_Of_Object
16639     (Obj_Def     : Node_Id;
16640      Related_Nod : Node_Id) return Entity_Id
16641   is
16642      Def_Kind : constant Node_Kind := Nkind (Obj_Def);
16643      P        : Node_Id := Parent (Obj_Def);
16644      T        : Entity_Id;
16645      Nam      : Name_Id;
16646
16647   begin
16648      --  If the parent is a component_definition node we climb to the
16649      --  component_declaration node
16650
16651      if Nkind (P) = N_Component_Definition then
16652         P := Parent (P);
16653      end if;
16654
16655      --  Case of an anonymous array subtype
16656
16657      if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
16658                             N_Unconstrained_Array_Definition)
16659      then
16660         T := Empty;
16661         Array_Type_Declaration (T, Obj_Def);
16662
16663      --  Create an explicit subtype whenever possible
16664
16665      elsif Nkind (P) /= N_Component_Declaration
16666        and then Def_Kind = N_Subtype_Indication
16667      then
16668         --  Base name of subtype on object name, which will be unique in
16669         --  the current scope.
16670
16671         --  If this is a duplicate declaration, return base type, to avoid
16672         --  generating duplicate anonymous types.
16673
16674         if Error_Posted (P) then
16675            Analyze (Subtype_Mark (Obj_Def));
16676            return Entity (Subtype_Mark (Obj_Def));
16677         end if;
16678
16679         Nam :=
16680            New_External_Name
16681             (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
16682
16683         T := Make_Defining_Identifier (Sloc (P), Nam);
16684
16685         Insert_Action (Obj_Def,
16686           Make_Subtype_Declaration (Sloc (P),
16687             Defining_Identifier => T,
16688             Subtype_Indication  => Relocate_Node (Obj_Def)));
16689
16690         --  This subtype may need freezing, and this will not be done
16691         --  automatically if the object declaration is not in declarative
16692         --  part. Since this is an object declaration, the type cannot always
16693         --  be frozen here. Deferred constants do not freeze their type
16694         --  (which often enough will be private).
16695
16696         if Nkind (P) = N_Object_Declaration
16697           and then Constant_Present (P)
16698           and then No (Expression (P))
16699         then
16700            null;
16701
16702         --  Here we freeze the base type of object type to catch premature use
16703         --  of discriminated private type without a full view.
16704
16705         else
16706            Insert_Actions (Obj_Def, Freeze_Entity (Base_Type (T), P));
16707         end if;
16708
16709      --  Ada 2005 AI-406: the object definition in an object declaration
16710      --  can be an access definition.
16711
16712      elsif Def_Kind = N_Access_Definition then
16713         T := Access_Definition (Related_Nod, Obj_Def);
16714
16715         Set_Is_Local_Anonymous_Access
16716           (T,
16717            V => (Ada_Version < Ada_2012)
16718                   or else (Nkind (P) /= N_Object_Declaration)
16719                   or else Is_Library_Level_Entity (Defining_Identifier (P)));
16720
16721      --  Otherwise, the object definition is just a subtype_mark
16722
16723      else
16724         T := Process_Subtype (Obj_Def, Related_Nod);
16725
16726         --  If expansion is disabled an object definition that is an aggregate
16727         --  will not get expanded and may lead to scoping problems in the back
16728         --  end, if the object is referenced in an inner scope. In that case
16729         --  create an itype reference for the object definition now. This
16730         --  may be redundant in some cases, but harmless.
16731
16732         if Is_Itype (T)
16733           and then Nkind (Related_Nod) = N_Object_Declaration
16734           and then ASIS_Mode
16735         then
16736            Build_Itype_Reference (T, Related_Nod);
16737         end if;
16738      end if;
16739
16740      return T;
16741   end Find_Type_Of_Object;
16742
16743   --------------------------------
16744   -- Find_Type_Of_Subtype_Indic --
16745   --------------------------------
16746
16747   function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
16748      Typ : Entity_Id;
16749
16750   begin
16751      --  Case of subtype mark with a constraint
16752
16753      if Nkind (S) = N_Subtype_Indication then
16754         Find_Type (Subtype_Mark (S));
16755         Typ := Entity (Subtype_Mark (S));
16756
16757         if not
16758           Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
16759         then
16760            Error_Msg_N
16761              ("incorrect constraint for this kind of type", Constraint (S));
16762            Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
16763         end if;
16764
16765      --  Otherwise we have a subtype mark without a constraint
16766
16767      elsif Error_Posted (S) then
16768         Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
16769         return Any_Type;
16770
16771      else
16772         Find_Type (S);
16773         Typ := Entity (S);
16774      end if;
16775
16776      --  Check No_Wide_Characters restriction
16777
16778      Check_Wide_Character_Restriction (Typ, S);
16779
16780      return Typ;
16781   end Find_Type_Of_Subtype_Indic;
16782
16783   -------------------------------------
16784   -- Floating_Point_Type_Declaration --
16785   -------------------------------------
16786
16787   procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16788      Digs          : constant Node_Id := Digits_Expression (Def);
16789      Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
16790      Digs_Val      : Uint;
16791      Base_Typ      : Entity_Id;
16792      Implicit_Base : Entity_Id;
16793      Bound         : Node_Id;
16794
16795      function Can_Derive_From (E : Entity_Id) return Boolean;
16796      --  Find if given digits value, and possibly a specified range, allows
16797      --  derivation from specified type
16798
16799      function Find_Base_Type return Entity_Id;
16800      --  Find a predefined base type that Def can derive from, or generate
16801      --  an error and substitute Long_Long_Float if none exists.
16802
16803      ---------------------
16804      -- Can_Derive_From --
16805      ---------------------
16806
16807      function Can_Derive_From (E : Entity_Id) return Boolean is
16808         Spec : constant Entity_Id := Real_Range_Specification (Def);
16809
16810      begin
16811         --  Check specified "digits" constraint
16812
16813         if Digs_Val > Digits_Value (E) then
16814            return False;
16815         end if;
16816
16817         --  Check for matching range, if specified
16818
16819         if Present (Spec) then
16820            if Expr_Value_R (Type_Low_Bound (E)) >
16821               Expr_Value_R (Low_Bound (Spec))
16822            then
16823               return False;
16824            end if;
16825
16826            if Expr_Value_R (Type_High_Bound (E)) <
16827               Expr_Value_R (High_Bound (Spec))
16828            then
16829               return False;
16830            end if;
16831         end if;
16832
16833         return True;
16834      end Can_Derive_From;
16835
16836      --------------------
16837      -- Find_Base_Type --
16838      --------------------
16839
16840      function Find_Base_Type return Entity_Id is
16841         Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
16842
16843      begin
16844         --  Iterate over the predefined types in order, returning the first
16845         --  one that Def can derive from.
16846
16847         while Present (Choice) loop
16848            if Can_Derive_From (Node (Choice)) then
16849               return Node (Choice);
16850            end if;
16851
16852            Next_Elmt (Choice);
16853         end loop;
16854
16855         --  If we can't derive from any existing type, use Long_Long_Float
16856         --  and give appropriate message explaining the problem.
16857
16858         if Digs_Val > Max_Digs_Val then
16859            --  It might be the case that there is a type with the requested
16860            --  range, just not the combination of digits and range.
16861
16862            Error_Msg_N
16863              ("no predefined type has requested range and precision",
16864               Real_Range_Specification (Def));
16865
16866         else
16867            Error_Msg_N
16868              ("range too large for any predefined type",
16869               Real_Range_Specification (Def));
16870         end if;
16871
16872         return Standard_Long_Long_Float;
16873      end Find_Base_Type;
16874
16875   --  Start of processing for Floating_Point_Type_Declaration
16876
16877   begin
16878      Check_Restriction (No_Floating_Point, Def);
16879
16880      --  Create an implicit base type
16881
16882      Implicit_Base :=
16883        Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
16884
16885      --  Analyze and verify digits value
16886
16887      Analyze_And_Resolve (Digs, Any_Integer);
16888      Check_Digits_Expression (Digs);
16889      Digs_Val := Expr_Value (Digs);
16890
16891      --  Process possible range spec and find correct type to derive from
16892
16893      Process_Real_Range_Specification (Def);
16894
16895      --  Check that requested number of digits is not too high.
16896
16897      if Digs_Val > Max_Digs_Val then
16898
16899         --  The check for Max_Base_Digits may be somewhat expensive, as it
16900         --  requires reading System, so only do it when necessary.
16901
16902         declare
16903            Max_Base_Digits : constant Uint :=
16904                                Expr_Value
16905                                  (Expression
16906                                     (Parent (RTE (RE_Max_Base_Digits))));
16907
16908         begin
16909            if Digs_Val > Max_Base_Digits then
16910               Error_Msg_Uint_1 := Max_Base_Digits;
16911               Error_Msg_N ("digits value out of range, maximum is ^", Digs);
16912
16913            elsif No (Real_Range_Specification (Def)) then
16914               Error_Msg_Uint_1 := Max_Digs_Val;
16915               Error_Msg_N ("types with more than ^ digits need range spec "
16916                 & "(RM 3.5.7(6))", Digs);
16917            end if;
16918         end;
16919      end if;
16920
16921      --  Find a suitable type to derive from or complain and use a substitute
16922
16923      Base_Typ := Find_Base_Type;
16924
16925      --  If there are bounds given in the declaration use them as the bounds
16926      --  of the type, otherwise use the bounds of the predefined base type
16927      --  that was chosen based on the Digits value.
16928
16929      if Present (Real_Range_Specification (Def)) then
16930         Set_Scalar_Range (T, Real_Range_Specification (Def));
16931         Set_Is_Constrained (T);
16932
16933         --  The bounds of this range must be converted to machine numbers
16934         --  in accordance with RM 4.9(38).
16935
16936         Bound := Type_Low_Bound (T);
16937
16938         if Nkind (Bound) = N_Real_Literal then
16939            Set_Realval
16940              (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
16941            Set_Is_Machine_Number (Bound);
16942         end if;
16943
16944         Bound := Type_High_Bound (T);
16945
16946         if Nkind (Bound) = N_Real_Literal then
16947            Set_Realval
16948              (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
16949            Set_Is_Machine_Number (Bound);
16950         end if;
16951
16952      else
16953         Set_Scalar_Range (T, Scalar_Range (Base_Typ));
16954      end if;
16955
16956      --  Complete definition of implicit base and declared first subtype. The
16957      --  inheritance of the rep item chain ensures that SPARK-related pragmas
16958      --  are not clobbered when the floating point type acts as a full view of
16959      --  a private type.
16960
16961      Set_Etype              (Implicit_Base,                 Base_Typ);
16962      Set_Scalar_Range       (Implicit_Base, Scalar_Range   (Base_Typ));
16963      Set_Size_Info          (Implicit_Base,                 Base_Typ);
16964      Set_RM_Size            (Implicit_Base, RM_Size        (Base_Typ));
16965      Set_First_Rep_Item     (Implicit_Base, First_Rep_Item (Base_Typ));
16966      Set_Digits_Value       (Implicit_Base, Digits_Value   (Base_Typ));
16967      Set_Float_Rep          (Implicit_Base, Float_Rep      (Base_Typ));
16968
16969      Set_Ekind              (T, E_Floating_Point_Subtype);
16970      Set_Etype              (T,          Implicit_Base);
16971      Set_Size_Info          (T,          Implicit_Base);
16972      Set_RM_Size            (T, RM_Size (Implicit_Base));
16973      Inherit_Rep_Item_Chain (T,          Implicit_Base);
16974      Set_Digits_Value       (T, Digs_Val);
16975   end Floating_Point_Type_Declaration;
16976
16977   ----------------------------
16978   -- Get_Discriminant_Value --
16979   ----------------------------
16980
16981   --  This is the situation:
16982
16983   --  There is a non-derived type
16984
16985   --       type T0 (Dx, Dy, Dz...)
16986
16987   --  There are zero or more levels of derivation, with each derivation
16988   --  either purely inheriting the discriminants, or defining its own.
16989
16990   --       type Ti      is new Ti-1
16991   --  or
16992   --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
16993   --  or
16994   --       subtype Ti is ...
16995
16996   --  The subtype issue is avoided by the use of Original_Record_Component,
16997   --  and the fact that derived subtypes also derive the constraints.
16998
16999   --  This chain leads back from
17000
17001   --       Typ_For_Constraint
17002
17003   --  Typ_For_Constraint has discriminants, and the value for each
17004   --  discriminant is given by its corresponding Elmt of Constraints.
17005
17006   --  Discriminant is some discriminant in this hierarchy
17007
17008   --  We need to return its value
17009
17010   --  We do this by recursively searching each level, and looking for
17011   --  Discriminant. Once we get to the bottom, we start backing up
17012   --  returning the value for it which may in turn be a discriminant
17013   --  further up, so on the backup we continue the substitution.
17014
17015   function Get_Discriminant_Value
17016     (Discriminant       : Entity_Id;
17017      Typ_For_Constraint : Entity_Id;
17018      Constraint         : Elist_Id) return Node_Id
17019   is
17020      function Root_Corresponding_Discriminant
17021        (Discr : Entity_Id) return Entity_Id;
17022      --  Given a discriminant, traverse the chain of inherited discriminants
17023      --  and return the topmost discriminant.
17024
17025      function Search_Derivation_Levels
17026        (Ti                    : Entity_Id;
17027         Discrim_Values        : Elist_Id;
17028         Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
17029      --  This is the routine that performs the recursive search of levels
17030      --  as described above.
17031
17032      -------------------------------------
17033      -- Root_Corresponding_Discriminant --
17034      -------------------------------------
17035
17036      function Root_Corresponding_Discriminant
17037        (Discr : Entity_Id) return Entity_Id
17038      is
17039         D : Entity_Id;
17040
17041      begin
17042         D := Discr;
17043         while Present (Corresponding_Discriminant (D)) loop
17044            D := Corresponding_Discriminant (D);
17045         end loop;
17046
17047         return D;
17048      end Root_Corresponding_Discriminant;
17049
17050      ------------------------------
17051      -- Search_Derivation_Levels --
17052      ------------------------------
17053
17054      function Search_Derivation_Levels
17055        (Ti                    : Entity_Id;
17056         Discrim_Values        : Elist_Id;
17057         Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
17058      is
17059         Assoc          : Elmt_Id;
17060         Disc           : Entity_Id;
17061         Result         : Node_Or_Entity_Id;
17062         Result_Entity  : Node_Id;
17063
17064      begin
17065         --  If inappropriate type, return Error, this happens only in
17066         --  cascaded error situations, and we want to avoid a blow up.
17067
17068         if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
17069            return Error;
17070         end if;
17071
17072         --  Look deeper if possible. Use Stored_Constraints only for
17073         --  untagged types. For tagged types use the given constraint.
17074         --  This asymmetry needs explanation???
17075
17076         if not Stored_Discrim_Values
17077           and then Present (Stored_Constraint (Ti))
17078           and then not Is_Tagged_Type (Ti)
17079         then
17080            Result :=
17081              Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
17082         else
17083            declare
17084               Td : constant Entity_Id := Etype (Ti);
17085
17086            begin
17087               if Td = Ti then
17088                  Result := Discriminant;
17089
17090               else
17091                  if Present (Stored_Constraint (Ti)) then
17092                     Result :=
17093                        Search_Derivation_Levels
17094                          (Td, Stored_Constraint (Ti), True);
17095                  else
17096                     Result :=
17097                        Search_Derivation_Levels
17098                          (Td, Discrim_Values, Stored_Discrim_Values);
17099                  end if;
17100               end if;
17101            end;
17102         end if;
17103
17104         --  Extra underlying places to search, if not found above. For
17105         --  concurrent types, the relevant discriminant appears in the
17106         --  corresponding record. For a type derived from a private type
17107         --  without discriminant, the full view inherits the discriminants
17108         --  of the full view of the parent.
17109
17110         if Result = Discriminant then
17111            if Is_Concurrent_Type (Ti)
17112              and then Present (Corresponding_Record_Type (Ti))
17113            then
17114               Result :=
17115                 Search_Derivation_Levels (
17116                   Corresponding_Record_Type (Ti),
17117                   Discrim_Values,
17118                   Stored_Discrim_Values);
17119
17120            elsif Is_Private_Type (Ti)
17121              and then not Has_Discriminants (Ti)
17122              and then Present (Full_View (Ti))
17123              and then Etype (Full_View (Ti)) /= Ti
17124            then
17125               Result :=
17126                 Search_Derivation_Levels (
17127                   Full_View (Ti),
17128                   Discrim_Values,
17129                   Stored_Discrim_Values);
17130            end if;
17131         end if;
17132
17133         --  If Result is not a (reference to a) discriminant, return it,
17134         --  otherwise set Result_Entity to the discriminant.
17135
17136         if Nkind (Result) = N_Defining_Identifier then
17137            pragma Assert (Result = Discriminant);
17138            Result_Entity := Result;
17139
17140         else
17141            if not Denotes_Discriminant (Result) then
17142               return Result;
17143            end if;
17144
17145            Result_Entity := Entity (Result);
17146         end if;
17147
17148         --  See if this level of derivation actually has discriminants because
17149         --  tagged derivations can add them, hence the lower levels need not
17150         --  have any.
17151
17152         if not Has_Discriminants (Ti) then
17153            return Result;
17154         end if;
17155
17156         --  Scan Ti's discriminants for Result_Entity, and return its
17157         --  corresponding value, if any.
17158
17159         Result_Entity := Original_Record_Component (Result_Entity);
17160
17161         Assoc := First_Elmt (Discrim_Values);
17162
17163         if Stored_Discrim_Values then
17164            Disc := First_Stored_Discriminant (Ti);
17165         else
17166            Disc := First_Discriminant (Ti);
17167         end if;
17168
17169         while Present (Disc) loop
17170            pragma Assert (Present (Assoc));
17171
17172            if Original_Record_Component (Disc) = Result_Entity then
17173               return Node (Assoc);
17174            end if;
17175
17176            Next_Elmt (Assoc);
17177
17178            if Stored_Discrim_Values then
17179               Next_Stored_Discriminant (Disc);
17180            else
17181               Next_Discriminant (Disc);
17182            end if;
17183         end loop;
17184
17185         --  Could not find it
17186
17187         return Result;
17188      end Search_Derivation_Levels;
17189
17190      --  Local Variables
17191
17192      Result : Node_Or_Entity_Id;
17193
17194   --  Start of processing for Get_Discriminant_Value
17195
17196   begin
17197      --  ??? This routine is a gigantic mess and will be deleted. For the
17198      --  time being just test for the trivial case before calling recurse.
17199
17200      if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
17201         declare
17202            D : Entity_Id;
17203            E : Elmt_Id;
17204
17205         begin
17206            D := First_Discriminant (Typ_For_Constraint);
17207            E := First_Elmt (Constraint);
17208            while Present (D) loop
17209               if Chars (D) = Chars (Discriminant) then
17210                  return Node (E);
17211               end if;
17212
17213               Next_Discriminant (D);
17214               Next_Elmt (E);
17215            end loop;
17216         end;
17217      end if;
17218
17219      Result := Search_Derivation_Levels
17220        (Typ_For_Constraint, Constraint, False);
17221
17222      --  ??? hack to disappear when this routine is gone
17223
17224      if Nkind (Result) = N_Defining_Identifier then
17225         declare
17226            D : Entity_Id;
17227            E : Elmt_Id;
17228
17229         begin
17230            D := First_Discriminant (Typ_For_Constraint);
17231            E := First_Elmt (Constraint);
17232            while Present (D) loop
17233               if Root_Corresponding_Discriminant (D) = Discriminant then
17234                  return Node (E);
17235               end if;
17236
17237               Next_Discriminant (D);
17238               Next_Elmt (E);
17239            end loop;
17240         end;
17241      end if;
17242
17243      pragma Assert (Nkind (Result) /= N_Defining_Identifier);
17244      return Result;
17245   end Get_Discriminant_Value;
17246
17247   --------------------------
17248   -- Has_Range_Constraint --
17249   --------------------------
17250
17251   function Has_Range_Constraint (N : Node_Id) return Boolean is
17252      C : constant Node_Id := Constraint (N);
17253
17254   begin
17255      if Nkind (C) = N_Range_Constraint then
17256         return True;
17257
17258      elsif Nkind (C) = N_Digits_Constraint then
17259         return
17260            Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
17261              or else Present (Range_Constraint (C));
17262
17263      elsif Nkind (C) = N_Delta_Constraint then
17264         return Present (Range_Constraint (C));
17265
17266      else
17267         return False;
17268      end if;
17269   end Has_Range_Constraint;
17270
17271   ------------------------
17272   -- Inherit_Components --
17273   ------------------------
17274
17275   function Inherit_Components
17276     (N             : Node_Id;
17277      Parent_Base   : Entity_Id;
17278      Derived_Base  : Entity_Id;
17279      Is_Tagged     : Boolean;
17280      Inherit_Discr : Boolean;
17281      Discs         : Elist_Id) return Elist_Id
17282   is
17283      Assoc_List : constant Elist_Id := New_Elmt_List;
17284
17285      procedure Inherit_Component
17286        (Old_C          : Entity_Id;
17287         Plain_Discrim  : Boolean := False;
17288         Stored_Discrim : Boolean := False);
17289      --  Inherits component Old_C from Parent_Base to the Derived_Base. If
17290      --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
17291      --  True, Old_C is a stored discriminant. If they are both false then
17292      --  Old_C is a regular component.
17293
17294      -----------------------
17295      -- Inherit_Component --
17296      -----------------------
17297
17298      procedure Inherit_Component
17299        (Old_C          : Entity_Id;
17300         Plain_Discrim  : Boolean := False;
17301         Stored_Discrim : Boolean := False)
17302      is
17303         procedure Set_Anonymous_Type (Id : Entity_Id);
17304         --  Id denotes the entity of an access discriminant or anonymous
17305         --  access component. Set the type of Id to either the same type of
17306         --  Old_C or create a new one depending on whether the parent and
17307         --  the child types are in the same scope.
17308
17309         ------------------------
17310         -- Set_Anonymous_Type --
17311         ------------------------
17312
17313         procedure Set_Anonymous_Type (Id : Entity_Id) is
17314            Old_Typ : constant Entity_Id := Etype (Old_C);
17315
17316         begin
17317            if Scope (Parent_Base) = Scope (Derived_Base) then
17318               Set_Etype (Id, Old_Typ);
17319
17320            --  The parent and the derived type are in two different scopes.
17321            --  Reuse the type of the original discriminant / component by
17322            --  copying it in order to preserve all attributes.
17323
17324            else
17325               declare
17326                  Typ : constant Entity_Id := New_Copy (Old_Typ);
17327
17328               begin
17329                  Set_Etype (Id, Typ);
17330
17331                  --  Since we do not generate component declarations for
17332                  --  inherited components, associate the itype with the
17333                  --  derived type.
17334
17335                  Set_Associated_Node_For_Itype (Typ, Parent (Derived_Base));
17336                  Set_Scope                     (Typ, Derived_Base);
17337               end;
17338            end if;
17339         end Set_Anonymous_Type;
17340
17341         --  Local variables and constants
17342
17343         New_C : constant Entity_Id := New_Copy (Old_C);
17344
17345         Corr_Discrim : Entity_Id;
17346         Discrim      : Entity_Id;
17347
17348      --  Start of processing for Inherit_Component
17349
17350      begin
17351         pragma Assert (not Is_Tagged or not Stored_Discrim);
17352
17353         Set_Parent (New_C, Parent (Old_C));
17354
17355         --  Regular discriminants and components must be inserted in the scope
17356         --  of the Derived_Base. Do it here.
17357
17358         if not Stored_Discrim then
17359            Enter_Name (New_C);
17360         end if;
17361
17362         --  For tagged types the Original_Record_Component must point to
17363         --  whatever this field was pointing to in the parent type. This has
17364         --  already been achieved by the call to New_Copy above.
17365
17366         if not Is_Tagged then
17367            Set_Original_Record_Component (New_C, New_C);
17368         end if;
17369
17370         --  Set the proper type of an access discriminant
17371
17372         if Ekind (New_C) = E_Discriminant
17373           and then Ekind (Etype (New_C)) = E_Anonymous_Access_Type
17374         then
17375            Set_Anonymous_Type (New_C);
17376         end if;
17377
17378         --  If we have inherited a component then see if its Etype contains
17379         --  references to Parent_Base discriminants. In this case, replace
17380         --  these references with the constraints given in Discs. We do not
17381         --  do this for the partial view of private types because this is
17382         --  not needed (only the components of the full view will be used
17383         --  for code generation) and cause problem. We also avoid this
17384         --  transformation in some error situations.
17385
17386         if Ekind (New_C) = E_Component then
17387
17388            --  Set the proper type of an anonymous access component
17389
17390            if Ekind (Etype (New_C)) = E_Anonymous_Access_Type then
17391               Set_Anonymous_Type (New_C);
17392
17393            elsif (Is_Private_Type (Derived_Base)
17394                    and then not Is_Generic_Type (Derived_Base))
17395              or else (Is_Empty_Elmt_List (Discs)
17396                        and then not Expander_Active)
17397            then
17398               Set_Etype (New_C, Etype (Old_C));
17399
17400            else
17401               --  The current component introduces a circularity of the
17402               --  following kind:
17403
17404               --     limited with Pack_2;
17405               --     package Pack_1 is
17406               --        type T_1 is tagged record
17407               --           Comp : access Pack_2.T_2;
17408               --           ...
17409               --        end record;
17410               --     end Pack_1;
17411
17412               --     with Pack_1;
17413               --     package Pack_2 is
17414               --        type T_2 is new Pack_1.T_1 with ...;
17415               --     end Pack_2;
17416
17417               Set_Etype
17418                 (New_C,
17419                  Constrain_Component_Type
17420                    (Old_C, Derived_Base, N, Parent_Base, Discs));
17421            end if;
17422         end if;
17423
17424         --  In derived tagged types it is illegal to reference a non
17425         --  discriminant component in the parent type. To catch this, mark
17426         --  these components with an Ekind of E_Void. This will be reset in
17427         --  Record_Type_Definition after processing the record extension of
17428         --  the derived type.
17429
17430         --  If the declaration is a private extension, there is no further
17431         --  record extension to process, and the components retain their
17432         --  current kind, because they are visible at this point.
17433
17434         if Is_Tagged and then Ekind (New_C) = E_Component
17435           and then Nkind (N) /= N_Private_Extension_Declaration
17436         then
17437            Set_Ekind (New_C, E_Void);
17438         end if;
17439
17440         if Plain_Discrim then
17441            Set_Corresponding_Discriminant (New_C, Old_C);
17442            Build_Discriminal (New_C);
17443
17444         --  If we are explicitly inheriting a stored discriminant it will be
17445         --  completely hidden.
17446
17447         elsif Stored_Discrim then
17448            Set_Corresponding_Discriminant (New_C, Empty);
17449            Set_Discriminal (New_C, Empty);
17450            Set_Is_Completely_Hidden (New_C);
17451
17452            --  Set the Original_Record_Component of each discriminant in the
17453            --  derived base to point to the corresponding stored that we just
17454            --  created.
17455
17456            Discrim := First_Discriminant (Derived_Base);
17457            while Present (Discrim) loop
17458               Corr_Discrim := Corresponding_Discriminant (Discrim);
17459
17460               --  Corr_Discrim could be missing in an error situation
17461
17462               if Present (Corr_Discrim)
17463                 and then Original_Record_Component (Corr_Discrim) = Old_C
17464               then
17465                  Set_Original_Record_Component (Discrim, New_C);
17466               end if;
17467
17468               Next_Discriminant (Discrim);
17469            end loop;
17470
17471            Append_Entity (New_C, Derived_Base);
17472         end if;
17473
17474         if not Is_Tagged then
17475            Append_Elmt (Old_C, Assoc_List);
17476            Append_Elmt (New_C, Assoc_List);
17477         end if;
17478      end Inherit_Component;
17479
17480      --  Variables local to Inherit_Component
17481
17482      Loc : constant Source_Ptr := Sloc (N);
17483
17484      Parent_Discrim : Entity_Id;
17485      Stored_Discrim : Entity_Id;
17486      D              : Entity_Id;
17487      Component      : Entity_Id;
17488
17489   --  Start of processing for Inherit_Components
17490
17491   begin
17492      if not Is_Tagged then
17493         Append_Elmt (Parent_Base,  Assoc_List);
17494         Append_Elmt (Derived_Base, Assoc_List);
17495      end if;
17496
17497      --  Inherit parent discriminants if needed
17498
17499      if Inherit_Discr then
17500         Parent_Discrim := First_Discriminant (Parent_Base);
17501         while Present (Parent_Discrim) loop
17502            Inherit_Component (Parent_Discrim, Plain_Discrim => True);
17503            Next_Discriminant (Parent_Discrim);
17504         end loop;
17505      end if;
17506
17507      --  Create explicit stored discrims for untagged types when necessary
17508
17509      if not Has_Unknown_Discriminants (Derived_Base)
17510        and then Has_Discriminants (Parent_Base)
17511        and then not Is_Tagged
17512        and then
17513          (not Inherit_Discr
17514            or else First_Discriminant (Parent_Base) /=
17515                    First_Stored_Discriminant (Parent_Base))
17516      then
17517         Stored_Discrim := First_Stored_Discriminant (Parent_Base);
17518         while Present (Stored_Discrim) loop
17519            Inherit_Component (Stored_Discrim, Stored_Discrim => True);
17520            Next_Stored_Discriminant (Stored_Discrim);
17521         end loop;
17522      end if;
17523
17524      --  See if we can apply the second transformation for derived types, as
17525      --  explained in point 6. in the comments above Build_Derived_Record_Type
17526      --  This is achieved by appending Derived_Base discriminants into Discs,
17527      --  which has the side effect of returning a non empty Discs list to the
17528      --  caller of Inherit_Components, which is what we want. This must be
17529      --  done for private derived types if there are explicit stored
17530      --  discriminants, to ensure that we can retrieve the values of the
17531      --  constraints provided in the ancestors.
17532
17533      if Inherit_Discr
17534        and then Is_Empty_Elmt_List (Discs)
17535        and then Present (First_Discriminant (Derived_Base))
17536        and then
17537          (not Is_Private_Type (Derived_Base)
17538            or else Is_Completely_Hidden
17539                      (First_Stored_Discriminant (Derived_Base))
17540            or else Is_Generic_Type (Derived_Base))
17541      then
17542         D := First_Discriminant (Derived_Base);
17543         while Present (D) loop
17544            Append_Elmt (New_Occurrence_Of (D, Loc), Discs);
17545            Next_Discriminant (D);
17546         end loop;
17547      end if;
17548
17549      --  Finally, inherit non-discriminant components unless they are not
17550      --  visible because defined or inherited from the full view of the
17551      --  parent. Don't inherit the _parent field of the parent type.
17552
17553      Component := First_Entity (Parent_Base);
17554      while Present (Component) loop
17555
17556         --  Ada 2005 (AI-251): Do not inherit components associated with
17557         --  secondary tags of the parent.
17558
17559         if Ekind (Component) = E_Component
17560           and then Present (Related_Type (Component))
17561         then
17562            null;
17563
17564         elsif Ekind (Component) /= E_Component
17565           or else Chars (Component) = Name_uParent
17566         then
17567            null;
17568
17569         --  If the derived type is within the parent type's declarative
17570         --  region, then the components can still be inherited even though
17571         --  they aren't visible at this point. This can occur for cases
17572         --  such as within public child units where the components must
17573         --  become visible upon entering the child unit's private part.
17574
17575         elsif not Is_Visible_Component (Component)
17576           and then not In_Open_Scopes (Scope (Parent_Base))
17577         then
17578            null;
17579
17580         elsif Ekind_In (Derived_Base, E_Private_Type,
17581                                       E_Limited_Private_Type)
17582         then
17583            null;
17584
17585         else
17586            Inherit_Component (Component);
17587         end if;
17588
17589         Next_Entity (Component);
17590      end loop;
17591
17592      --  For tagged derived types, inherited discriminants cannot be used in
17593      --  component declarations of the record extension part. To achieve this
17594      --  we mark the inherited discriminants as not visible.
17595
17596      if Is_Tagged and then Inherit_Discr then
17597         D := First_Discriminant (Derived_Base);
17598         while Present (D) loop
17599            Set_Is_Immediately_Visible (D, False);
17600            Next_Discriminant (D);
17601         end loop;
17602      end if;
17603
17604      return Assoc_List;
17605   end Inherit_Components;
17606
17607   -----------------------------
17608   -- Inherit_Predicate_Flags --
17609   -----------------------------
17610
17611   procedure Inherit_Predicate_Flags (Subt, Par : Entity_Id) is
17612   begin
17613      Set_Has_Predicates (Subt, Has_Predicates (Par));
17614      Set_Has_Static_Predicate_Aspect
17615        (Subt, Has_Static_Predicate_Aspect (Par));
17616      Set_Has_Dynamic_Predicate_Aspect
17617        (Subt, Has_Dynamic_Predicate_Aspect (Par));
17618   end Inherit_Predicate_Flags;
17619
17620   ----------------------
17621   -- Is_EVF_Procedure --
17622   ----------------------
17623
17624   function Is_EVF_Procedure (Subp : Entity_Id) return Boolean is
17625      Formal : Entity_Id;
17626
17627   begin
17628      --  Examine the formals of an Extensions_Visible False procedure looking
17629      --  for a controlling OUT parameter.
17630
17631      if Ekind (Subp) = E_Procedure
17632        and then Extensions_Visible_Status (Subp) = Extensions_Visible_False
17633      then
17634         Formal := First_Formal (Subp);
17635         while Present (Formal) loop
17636            if Ekind (Formal) = E_Out_Parameter
17637              and then Is_Controlling_Formal (Formal)
17638            then
17639               return True;
17640            end if;
17641
17642            Next_Formal (Formal);
17643         end loop;
17644      end if;
17645
17646      return False;
17647   end Is_EVF_Procedure;
17648
17649   -----------------------
17650   -- Is_Null_Extension --
17651   -----------------------
17652
17653   function Is_Null_Extension (T : Entity_Id) return Boolean is
17654      Type_Decl : constant Node_Id := Parent (Base_Type (T));
17655      Comp_List : Node_Id;
17656      Comp      : Node_Id;
17657
17658   begin
17659      if Nkind (Type_Decl) /= N_Full_Type_Declaration
17660        or else not Is_Tagged_Type (T)
17661        or else Nkind (Type_Definition (Type_Decl)) /=
17662                                              N_Derived_Type_Definition
17663        or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
17664      then
17665         return False;
17666      end if;
17667
17668      Comp_List :=
17669        Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
17670
17671      if Present (Discriminant_Specifications (Type_Decl)) then
17672         return False;
17673
17674      elsif Present (Comp_List)
17675        and then Is_Non_Empty_List (Component_Items (Comp_List))
17676      then
17677         Comp := First (Component_Items (Comp_List));
17678
17679         --  Only user-defined components are relevant. The component list
17680         --  may also contain a parent component and internal components
17681         --  corresponding to secondary tags, but these do not determine
17682         --  whether this is a null extension.
17683
17684         while Present (Comp) loop
17685            if Comes_From_Source (Comp) then
17686               return False;
17687            end if;
17688
17689            Next (Comp);
17690         end loop;
17691
17692         return True;
17693
17694      else
17695         return True;
17696      end if;
17697   end Is_Null_Extension;
17698
17699   ------------------------------
17700   -- Is_Valid_Constraint_Kind --
17701   ------------------------------
17702
17703   function Is_Valid_Constraint_Kind
17704     (T_Kind          : Type_Kind;
17705      Constraint_Kind : Node_Kind) return Boolean
17706   is
17707   begin
17708      case T_Kind is
17709         when Enumeration_Kind |
17710              Integer_Kind =>
17711            return Constraint_Kind = N_Range_Constraint;
17712
17713         when Decimal_Fixed_Point_Kind =>
17714            return Nkind_In (Constraint_Kind, N_Digits_Constraint,
17715                                              N_Range_Constraint);
17716
17717         when Ordinary_Fixed_Point_Kind =>
17718            return Nkind_In (Constraint_Kind, N_Delta_Constraint,
17719                                              N_Range_Constraint);
17720
17721         when Float_Kind =>
17722            return Nkind_In (Constraint_Kind, N_Digits_Constraint,
17723                                              N_Range_Constraint);
17724
17725         when Access_Kind       |
17726              Array_Kind        |
17727              E_Record_Type     |
17728              E_Record_Subtype  |
17729              Class_Wide_Kind   |
17730              E_Incomplete_Type |
17731              Private_Kind      |
17732              Concurrent_Kind  =>
17733            return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
17734
17735         when others =>
17736            return True; -- Error will be detected later
17737      end case;
17738   end Is_Valid_Constraint_Kind;
17739
17740   --------------------------
17741   -- Is_Visible_Component --
17742   --------------------------
17743
17744   function Is_Visible_Component
17745     (C : Entity_Id;
17746      N : Node_Id := Empty) return Boolean
17747   is
17748      Original_Comp  : Entity_Id := Empty;
17749      Original_Scope : Entity_Id;
17750      Type_Scope     : Entity_Id;
17751
17752      function Is_Local_Type (Typ : Entity_Id) return Boolean;
17753      --  Check whether parent type of inherited component is declared locally,
17754      --  possibly within a nested package or instance. The current scope is
17755      --  the derived record itself.
17756
17757      -------------------
17758      -- Is_Local_Type --
17759      -------------------
17760
17761      function Is_Local_Type (Typ : Entity_Id) return Boolean is
17762         Scop : Entity_Id;
17763
17764      begin
17765         Scop := Scope (Typ);
17766         while Present (Scop)
17767           and then Scop /= Standard_Standard
17768         loop
17769            if Scop = Scope (Current_Scope) then
17770               return True;
17771            end if;
17772
17773            Scop := Scope (Scop);
17774         end loop;
17775
17776         return False;
17777      end Is_Local_Type;
17778
17779   --  Start of processing for Is_Visible_Component
17780
17781   begin
17782      if Ekind_In (C, E_Component, E_Discriminant) then
17783         Original_Comp := Original_Record_Component (C);
17784      end if;
17785
17786      if No (Original_Comp) then
17787
17788         --  Premature usage, or previous error
17789
17790         return False;
17791
17792      else
17793         Original_Scope := Scope (Original_Comp);
17794         Type_Scope     := Scope (Base_Type (Scope (C)));
17795      end if;
17796
17797      --  This test only concerns tagged types
17798
17799      if not Is_Tagged_Type (Original_Scope) then
17800         return True;
17801
17802      --  If it is _Parent or _Tag, there is no visibility issue
17803
17804      elsif not Comes_From_Source (Original_Comp) then
17805         return True;
17806
17807      --  Discriminants are visible unless the (private) type has unknown
17808      --  discriminants. If the discriminant reference is inserted for a
17809      --  discriminant check on a full view it is also visible.
17810
17811      elsif Ekind (Original_Comp) = E_Discriminant
17812        and then
17813          (not Has_Unknown_Discriminants (Original_Scope)
17814            or else (Present (N)
17815                      and then Nkind (N) = N_Selected_Component
17816                      and then Nkind (Prefix (N)) = N_Type_Conversion
17817                      and then not Comes_From_Source (Prefix (N))))
17818      then
17819         return True;
17820
17821      --  In the body of an instantiation, no need to check for the visibility
17822      --  of a component.
17823
17824      elsif In_Instance_Body then
17825         return True;
17826
17827      --  If the component has been declared in an ancestor which is currently
17828      --  a private type, then it is not visible. The same applies if the
17829      --  component's containing type is not in an open scope and the original
17830      --  component's enclosing type is a visible full view of a private type
17831      --  (which can occur in cases where an attempt is being made to reference
17832      --  a component in a sibling package that is inherited from a visible
17833      --  component of a type in an ancestor package; the component in the
17834      --  sibling package should not be visible even though the component it
17835      --  inherited from is visible). This does not apply however in the case
17836      --  where the scope of the type is a private child unit, or when the
17837      --  parent comes from a local package in which the ancestor is currently
17838      --  visible. The latter suppression of visibility is needed for cases
17839      --  that are tested in B730006.
17840
17841      elsif Is_Private_Type (Original_Scope)
17842        or else
17843          (not Is_Private_Descendant (Type_Scope)
17844            and then not In_Open_Scopes (Type_Scope)
17845            and then Has_Private_Declaration (Original_Scope))
17846      then
17847         --  If the type derives from an entity in a formal package, there
17848         --  are no additional visible components.
17849
17850         if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
17851            N_Formal_Package_Declaration
17852         then
17853            return False;
17854
17855         --  if we are not in the private part of the current package, there
17856         --  are no additional visible components.
17857
17858         elsif Ekind (Scope (Current_Scope)) = E_Package
17859           and then not In_Private_Part (Scope (Current_Scope))
17860         then
17861            return False;
17862         else
17863            return
17864              Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
17865                and then In_Open_Scopes (Scope (Original_Scope))
17866                and then Is_Local_Type (Type_Scope);
17867         end if;
17868
17869      --  There is another weird way in which a component may be invisible when
17870      --  the private and the full view are not derived from the same ancestor.
17871      --  Here is an example :
17872
17873      --       type A1 is tagged      record F1 : integer; end record;
17874      --       type A2 is new A1 with record F2 : integer; end record;
17875      --       type T is new A1 with private;
17876      --     private
17877      --       type T is new A2 with null record;
17878
17879      --  In this case, the full view of T inherits F1 and F2 but the private
17880      --  view inherits only F1
17881
17882      else
17883         declare
17884            Ancestor : Entity_Id := Scope (C);
17885
17886         begin
17887            loop
17888               if Ancestor = Original_Scope then
17889                  return True;
17890               elsif Ancestor = Etype (Ancestor) then
17891                  return False;
17892               end if;
17893
17894               Ancestor := Etype (Ancestor);
17895            end loop;
17896         end;
17897      end if;
17898   end Is_Visible_Component;
17899
17900   --------------------------
17901   -- Make_Class_Wide_Type --
17902   --------------------------
17903
17904   procedure Make_Class_Wide_Type (T : Entity_Id) is
17905      CW_Type : Entity_Id;
17906      CW_Name : Name_Id;
17907      Next_E  : Entity_Id;
17908
17909   begin
17910      if Present (Class_Wide_Type (T)) then
17911
17912         --  The class-wide type is a partially decorated entity created for a
17913         --  unanalyzed tagged type referenced through a limited with clause.
17914         --  When the tagged type is analyzed, its class-wide type needs to be
17915         --  redecorated. Note that we reuse the entity created by Decorate_
17916         --  Tagged_Type in order to preserve all links.
17917
17918         if Materialize_Entity (Class_Wide_Type (T)) then
17919            CW_Type := Class_Wide_Type (T);
17920            Set_Materialize_Entity (CW_Type, False);
17921
17922         --  The class wide type can have been defined by the partial view, in
17923         --  which case everything is already done.
17924
17925         else
17926            return;
17927         end if;
17928
17929      --  Default case, we need to create a new class-wide type
17930
17931      else
17932         CW_Type :=
17933           New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
17934      end if;
17935
17936      --  Inherit root type characteristics
17937
17938      CW_Name := Chars (CW_Type);
17939      Next_E  := Next_Entity (CW_Type);
17940      Copy_Node (T, CW_Type);
17941      Set_Comes_From_Source (CW_Type, False);
17942      Set_Chars (CW_Type, CW_Name);
17943      Set_Parent (CW_Type, Parent (T));
17944      Set_Next_Entity (CW_Type, Next_E);
17945
17946      --  Ensure we have a new freeze node for the class-wide type. The partial
17947      --  view may have freeze action of its own, requiring a proper freeze
17948      --  node, and the same freeze node cannot be shared between the two
17949      --  types.
17950
17951      Set_Has_Delayed_Freeze (CW_Type);
17952      Set_Freeze_Node (CW_Type, Empty);
17953
17954      --  Customize the class-wide type: It has no prim. op., it cannot be
17955      --  abstract and its Etype points back to the specific root type.
17956
17957      Set_Ekind                       (CW_Type, E_Class_Wide_Type);
17958      Set_Is_Tagged_Type              (CW_Type, True);
17959      Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
17960      Set_Is_Abstract_Type            (CW_Type, False);
17961      Set_Is_Constrained              (CW_Type, False);
17962      Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
17963      Set_Default_SSO                 (CW_Type);
17964
17965      if Ekind (T) = E_Class_Wide_Subtype then
17966         Set_Etype (CW_Type, Etype (Base_Type (T)));
17967      else
17968         Set_Etype (CW_Type, T);
17969      end if;
17970
17971      Set_No_Tagged_Streams_Pragma (CW_Type, No_Tagged_Streams);
17972
17973      --  If this is the class_wide type of a constrained subtype, it does
17974      --  not have discriminants.
17975
17976      Set_Has_Discriminants (CW_Type,
17977        Has_Discriminants (T) and then not Is_Constrained (T));
17978
17979      Set_Has_Unknown_Discriminants (CW_Type, True);
17980      Set_Class_Wide_Type (T, CW_Type);
17981      Set_Equivalent_Type (CW_Type, Empty);
17982
17983      --  The class-wide type of a class-wide type is itself (RM 3.9(14))
17984
17985      Set_Class_Wide_Type (CW_Type, CW_Type);
17986   end Make_Class_Wide_Type;
17987
17988   ----------------
17989   -- Make_Index --
17990   ----------------
17991
17992   procedure Make_Index
17993     (N            : Node_Id;
17994      Related_Nod  : Node_Id;
17995      Related_Id   : Entity_Id := Empty;
17996      Suffix_Index : Nat       := 1;
17997      In_Iter_Schm : Boolean   := False)
17998   is
17999      R      : Node_Id;
18000      T      : Entity_Id;
18001      Def_Id : Entity_Id := Empty;
18002      Found  : Boolean := False;
18003
18004   begin
18005      --  For a discrete range used in a constrained array definition and
18006      --  defined by a range, an implicit conversion to the predefined type
18007      --  INTEGER is assumed if each bound is either a numeric literal, a named
18008      --  number, or an attribute, and the type of both bounds (prior to the
18009      --  implicit conversion) is the type universal_integer. Otherwise, both
18010      --  bounds must be of the same discrete type, other than universal
18011      --  integer; this type must be determinable independently of the
18012      --  context, but using the fact that the type must be discrete and that
18013      --  both bounds must have the same type.
18014
18015      --  Character literals also have a universal type in the absence of
18016      --  of additional context,  and are resolved to Standard_Character.
18017
18018      if Nkind (N) = N_Range then
18019
18020         --  The index is given by a range constraint. The bounds are known
18021         --  to be of a consistent type.
18022
18023         if not Is_Overloaded (N) then
18024            T := Etype (N);
18025
18026            --  For universal bounds, choose the specific predefined type
18027
18028            if T = Universal_Integer then
18029               T := Standard_Integer;
18030
18031            elsif T = Any_Character then
18032               Ambiguous_Character (Low_Bound (N));
18033
18034               T := Standard_Character;
18035            end if;
18036
18037         --  The node may be overloaded because some user-defined operators
18038         --  are available, but if a universal interpretation exists it is
18039         --  also the selected one.
18040
18041         elsif Universal_Interpretation (N) = Universal_Integer then
18042            T := Standard_Integer;
18043
18044         else
18045            T := Any_Type;
18046
18047            declare
18048               Ind : Interp_Index;
18049               It  : Interp;
18050
18051            begin
18052               Get_First_Interp (N, Ind, It);
18053               while Present (It.Typ) loop
18054                  if Is_Discrete_Type (It.Typ) then
18055
18056                     if Found
18057                       and then not Covers (It.Typ, T)
18058                       and then not Covers (T, It.Typ)
18059                     then
18060                        Error_Msg_N ("ambiguous bounds in discrete range", N);
18061                        exit;
18062                     else
18063                        T := It.Typ;
18064                        Found := True;
18065                     end if;
18066                  end if;
18067
18068                  Get_Next_Interp (Ind, It);
18069               end loop;
18070
18071               if T = Any_Type then
18072                  Error_Msg_N ("discrete type required for range", N);
18073                  Set_Etype (N, Any_Type);
18074                  return;
18075
18076               elsif T = Universal_Integer then
18077                  T := Standard_Integer;
18078               end if;
18079            end;
18080         end if;
18081
18082         if not Is_Discrete_Type (T) then
18083            Error_Msg_N ("discrete type required for range", N);
18084            Set_Etype (N, Any_Type);
18085            return;
18086         end if;
18087
18088         if Nkind (Low_Bound (N)) = N_Attribute_Reference
18089           and then Attribute_Name (Low_Bound (N)) = Name_First
18090           and then Is_Entity_Name (Prefix (Low_Bound (N)))
18091           and then Is_Type (Entity (Prefix (Low_Bound (N))))
18092           and then Is_Discrete_Type (Entity (Prefix (Low_Bound (N))))
18093         then
18094            --  The type of the index will be the type of the prefix, as long
18095            --  as the upper bound is 'Last of the same type.
18096
18097            Def_Id := Entity (Prefix (Low_Bound (N)));
18098
18099            if Nkind (High_Bound (N)) /= N_Attribute_Reference
18100              or else Attribute_Name (High_Bound (N)) /= Name_Last
18101              or else not Is_Entity_Name (Prefix (High_Bound (N)))
18102              or else Entity (Prefix (High_Bound (N))) /= Def_Id
18103            then
18104               Def_Id := Empty;
18105            end if;
18106         end if;
18107
18108         R := N;
18109         Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
18110
18111      elsif Nkind (N) = N_Subtype_Indication then
18112
18113         --  The index is given by a subtype with a range constraint
18114
18115         T :=  Base_Type (Entity (Subtype_Mark (N)));
18116
18117         if not Is_Discrete_Type (T) then
18118            Error_Msg_N ("discrete type required for range", N);
18119            Set_Etype (N, Any_Type);
18120            return;
18121         end if;
18122
18123         R := Range_Expression (Constraint (N));
18124
18125         Resolve (R, T);
18126         Process_Range_Expr_In_Decl
18127           (R, Entity (Subtype_Mark (N)), In_Iter_Schm => In_Iter_Schm);
18128
18129      elsif Nkind (N) = N_Attribute_Reference then
18130
18131         --  Catch beginner's error (use of attribute other than 'Range)
18132
18133         if Attribute_Name (N) /= Name_Range then
18134            Error_Msg_N ("expect attribute ''Range", N);
18135            Set_Etype (N, Any_Type);
18136            return;
18137         end if;
18138
18139         --  If the node denotes the range of a type mark, that is also the
18140         --  resulting type, and we do not need to create an Itype for it.
18141
18142         if Is_Entity_Name (Prefix (N))
18143           and then Comes_From_Source (N)
18144           and then Is_Type (Entity (Prefix (N)))
18145           and then Is_Discrete_Type (Entity (Prefix (N)))
18146         then
18147            Def_Id := Entity (Prefix (N));
18148         end if;
18149
18150         Analyze_And_Resolve (N);
18151         T := Etype (N);
18152         R := N;
18153
18154      --  If none of the above, must be a subtype. We convert this to a
18155      --  range attribute reference because in the case of declared first
18156      --  named subtypes, the types in the range reference can be different
18157      --  from the type of the entity. A range attribute normalizes the
18158      --  reference and obtains the correct types for the bounds.
18159
18160      --  This transformation is in the nature of an expansion, is only
18161      --  done if expansion is active. In particular, it is not done on
18162      --  formal generic types,  because we need to retain the name of the
18163      --  original index for instantiation purposes.
18164
18165      else
18166         if not Is_Entity_Name (N) or else not Is_Type (Entity (N)) then
18167            Error_Msg_N ("invalid subtype mark in discrete range ", N);
18168            Set_Etype (N, Any_Integer);
18169            return;
18170
18171         else
18172            --  The type mark may be that of an incomplete type. It is only
18173            --  now that we can get the full view, previous analysis does
18174            --  not look specifically for a type mark.
18175
18176            Set_Entity (N, Get_Full_View (Entity (N)));
18177            Set_Etype  (N, Entity (N));
18178            Def_Id := Entity (N);
18179
18180            if not Is_Discrete_Type (Def_Id) then
18181               Error_Msg_N ("discrete type required for index", N);
18182               Set_Etype (N, Any_Type);
18183               return;
18184            end if;
18185         end if;
18186
18187         if Expander_Active then
18188            Rewrite (N,
18189              Make_Attribute_Reference (Sloc (N),
18190                Attribute_Name => Name_Range,
18191                Prefix         => Relocate_Node (N)));
18192
18193            --  The original was a subtype mark that does not freeze. This
18194            --  means that the rewritten version must not freeze either.
18195
18196            Set_Must_Not_Freeze (N);
18197            Set_Must_Not_Freeze (Prefix (N));
18198            Analyze_And_Resolve (N);
18199            T := Etype (N);
18200            R := N;
18201
18202         --  If expander is inactive, type is legal, nothing else to construct
18203
18204         else
18205            return;
18206         end if;
18207      end if;
18208
18209      if not Is_Discrete_Type (T) then
18210         Error_Msg_N ("discrete type required for range", N);
18211         Set_Etype (N, Any_Type);
18212         return;
18213
18214      elsif T = Any_Type then
18215         Set_Etype (N, Any_Type);
18216         return;
18217      end if;
18218
18219      --  We will now create the appropriate Itype to describe the range, but
18220      --  first a check. If we originally had a subtype, then we just label
18221      --  the range with this subtype. Not only is there no need to construct
18222      --  a new subtype, but it is wrong to do so for two reasons:
18223
18224      --    1. A legality concern, if we have a subtype, it must not freeze,
18225      --       and the Itype would cause freezing incorrectly
18226
18227      --    2. An efficiency concern, if we created an Itype, it would not be
18228      --       recognized as the same type for the purposes of eliminating
18229      --       checks in some circumstances.
18230
18231      --  We signal this case by setting the subtype entity in Def_Id
18232
18233      if No (Def_Id) then
18234         Def_Id :=
18235           Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
18236         Set_Etype (Def_Id, Base_Type (T));
18237
18238         if Is_Signed_Integer_Type (T) then
18239            Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
18240
18241         elsif Is_Modular_Integer_Type (T) then
18242            Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
18243
18244         else
18245            Set_Ekind             (Def_Id, E_Enumeration_Subtype);
18246            Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
18247            Set_First_Literal     (Def_Id, First_Literal (T));
18248         end if;
18249
18250         Set_Size_Info      (Def_Id,                  (T));
18251         Set_RM_Size        (Def_Id, RM_Size          (T));
18252         Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
18253
18254         Set_Scalar_Range   (Def_Id, R);
18255         Conditional_Delay  (Def_Id, T);
18256
18257         if Nkind (N) = N_Subtype_Indication then
18258            Inherit_Predicate_Flags (Def_Id, Entity (Subtype_Mark (N)));
18259         end if;
18260
18261         --  In the subtype indication case, if the immediate parent of the
18262         --  new subtype is non-static, then the subtype we create is non-
18263         --  static, even if its bounds are static.
18264
18265         if Nkind (N) = N_Subtype_Indication
18266           and then not Is_OK_Static_Subtype (Entity (Subtype_Mark (N)))
18267         then
18268            Set_Is_Non_Static_Subtype (Def_Id);
18269         end if;
18270      end if;
18271
18272      --  Final step is to label the index with this constructed type
18273
18274      Set_Etype (N, Def_Id);
18275   end Make_Index;
18276
18277   ------------------------------
18278   -- Modular_Type_Declaration --
18279   ------------------------------
18280
18281   procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
18282      Mod_Expr : constant Node_Id := Expression (Def);
18283      M_Val    : Uint;
18284
18285      procedure Set_Modular_Size (Bits : Int);
18286      --  Sets RM_Size to Bits, and Esize to normal word size above this
18287
18288      ----------------------
18289      -- Set_Modular_Size --
18290      ----------------------
18291
18292      procedure Set_Modular_Size (Bits : Int) is
18293      begin
18294         Set_RM_Size (T, UI_From_Int (Bits));
18295
18296         if Bits <= 8 then
18297            Init_Esize (T, 8);
18298
18299         elsif Bits <= 16 then
18300            Init_Esize (T, 16);
18301
18302         elsif Bits <= 32 then
18303            Init_Esize (T, 32);
18304
18305         else
18306            Init_Esize (T, System_Max_Binary_Modulus_Power);
18307         end if;
18308
18309         if not Non_Binary_Modulus (T) and then Esize (T) = RM_Size (T) then
18310            Set_Is_Known_Valid (T);
18311         end if;
18312      end Set_Modular_Size;
18313
18314   --  Start of processing for Modular_Type_Declaration
18315
18316   begin
18317      --  If the mod expression is (exactly) 2 * literal, where literal is
18318      --  64 or less,then almost certainly the * was meant to be **. Warn.
18319
18320      if Warn_On_Suspicious_Modulus_Value
18321        and then Nkind (Mod_Expr) = N_Op_Multiply
18322        and then Nkind (Left_Opnd (Mod_Expr)) = N_Integer_Literal
18323        and then Intval (Left_Opnd (Mod_Expr)) = Uint_2
18324        and then Nkind (Right_Opnd (Mod_Expr)) = N_Integer_Literal
18325        and then Intval (Right_Opnd (Mod_Expr)) <= Uint_64
18326      then
18327         Error_Msg_N
18328           ("suspicious MOD value, was '*'* intended'??M?", Mod_Expr);
18329      end if;
18330
18331      --  Proceed with analysis of mod expression
18332
18333      Analyze_And_Resolve (Mod_Expr, Any_Integer);
18334      Set_Etype (T, T);
18335      Set_Ekind (T, E_Modular_Integer_Type);
18336      Init_Alignment (T);
18337      Set_Is_Constrained (T);
18338
18339      if not Is_OK_Static_Expression (Mod_Expr) then
18340         Flag_Non_Static_Expr
18341           ("non-static expression used for modular type bound!", Mod_Expr);
18342         M_Val := 2 ** System_Max_Binary_Modulus_Power;
18343      else
18344         M_Val := Expr_Value (Mod_Expr);
18345      end if;
18346
18347      if M_Val < 1 then
18348         Error_Msg_N ("modulus value must be positive", Mod_Expr);
18349         M_Val := 2 ** System_Max_Binary_Modulus_Power;
18350      end if;
18351
18352      if M_Val > 2 ** Standard_Long_Integer_Size then
18353         Check_Restriction (No_Long_Long_Integers, Mod_Expr);
18354      end if;
18355
18356      Set_Modulus (T, M_Val);
18357
18358      --   Create bounds for the modular type based on the modulus given in
18359      --   the type declaration and then analyze and resolve those bounds.
18360
18361      Set_Scalar_Range (T,
18362        Make_Range (Sloc (Mod_Expr),
18363          Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
18364          High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
18365
18366      --  Properly analyze the literals for the range. We do this manually
18367      --  because we can't go calling Resolve, since we are resolving these
18368      --  bounds with the type, and this type is certainly not complete yet.
18369
18370      Set_Etype (Low_Bound  (Scalar_Range (T)), T);
18371      Set_Etype (High_Bound (Scalar_Range (T)), T);
18372      Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
18373      Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
18374
18375      --  Loop through powers of two to find number of bits required
18376
18377      for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
18378
18379         --  Binary case
18380
18381         if M_Val = 2 ** Bits then
18382            Set_Modular_Size (Bits);
18383            return;
18384
18385         --  Non-binary case
18386
18387         elsif M_Val < 2 ** Bits then
18388            Check_SPARK_05_Restriction ("modulus should be a power of 2", T);
18389            Set_Non_Binary_Modulus (T);
18390
18391            if Bits > System_Max_Nonbinary_Modulus_Power then
18392               Error_Msg_Uint_1 :=
18393                 UI_From_Int (System_Max_Nonbinary_Modulus_Power);
18394               Error_Msg_F
18395                 ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
18396               Set_Modular_Size (System_Max_Binary_Modulus_Power);
18397               return;
18398
18399            else
18400               --  In the non-binary case, set size as per RM 13.3(55)
18401
18402               Set_Modular_Size (Bits);
18403               return;
18404            end if;
18405         end if;
18406
18407      end loop;
18408
18409      --  If we fall through, then the size exceed System.Max_Binary_Modulus
18410      --  so we just signal an error and set the maximum size.
18411
18412      Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
18413      Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
18414
18415      Set_Modular_Size (System_Max_Binary_Modulus_Power);
18416      Init_Alignment (T);
18417
18418   end Modular_Type_Declaration;
18419
18420   --------------------------
18421   -- New_Concatenation_Op --
18422   --------------------------
18423
18424   procedure New_Concatenation_Op (Typ : Entity_Id) is
18425      Loc : constant Source_Ptr := Sloc (Typ);
18426      Op  : Entity_Id;
18427
18428      function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
18429      --  Create abbreviated declaration for the formal of a predefined
18430      --  Operator 'Op' of type 'Typ'
18431
18432      --------------------
18433      -- Make_Op_Formal --
18434      --------------------
18435
18436      function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
18437         Formal : Entity_Id;
18438      begin
18439         Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
18440         Set_Etype (Formal, Typ);
18441         Set_Mechanism (Formal, Default_Mechanism);
18442         return Formal;
18443      end Make_Op_Formal;
18444
18445   --  Start of processing for New_Concatenation_Op
18446
18447   begin
18448      Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
18449
18450      Set_Ekind                   (Op, E_Operator);
18451      Set_Scope                   (Op, Current_Scope);
18452      Set_Etype                   (Op, Typ);
18453      Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
18454      Set_Is_Immediately_Visible  (Op);
18455      Set_Is_Intrinsic_Subprogram (Op);
18456      Set_Has_Completion          (Op);
18457      Append_Entity               (Op, Current_Scope);
18458
18459      Set_Name_Entity_Id (Name_Op_Concat, Op);
18460
18461      Append_Entity (Make_Op_Formal (Typ, Op), Op);
18462      Append_Entity (Make_Op_Formal (Typ, Op), Op);
18463   end New_Concatenation_Op;
18464
18465   -------------------------
18466   -- OK_For_Limited_Init --
18467   -------------------------
18468
18469   --  ???Check all calls of this, and compare the conditions under which it's
18470   --  called.
18471
18472   function OK_For_Limited_Init
18473     (Typ : Entity_Id;
18474      Exp : Node_Id) return Boolean
18475   is
18476   begin
18477      return Is_CPP_Constructor_Call (Exp)
18478        or else (Ada_Version >= Ada_2005
18479                  and then not Debug_Flag_Dot_L
18480                  and then OK_For_Limited_Init_In_05 (Typ, Exp));
18481   end OK_For_Limited_Init;
18482
18483   -------------------------------
18484   -- OK_For_Limited_Init_In_05 --
18485   -------------------------------
18486
18487   function OK_For_Limited_Init_In_05
18488     (Typ : Entity_Id;
18489      Exp : Node_Id) return Boolean
18490   is
18491   begin
18492      --  An object of a limited interface type can be initialized with any
18493      --  expression of a nonlimited descendant type.
18494
18495      if Is_Class_Wide_Type (Typ)
18496        and then Is_Limited_Interface (Typ)
18497        and then not Is_Limited_Type (Etype (Exp))
18498      then
18499         return True;
18500      end if;
18501
18502      --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
18503      --  case of limited aggregates (including extension aggregates), and
18504      --  function calls. The function call may have been given in prefixed
18505      --  notation, in which case the original node is an indexed component.
18506      --  If the function is parameterless, the original node was an explicit
18507      --  dereference. The function may also be parameterless, in which case
18508      --  the source node is just an identifier.
18509
18510      case Nkind (Original_Node (Exp)) is
18511         when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
18512            return True;
18513
18514         when N_Identifier =>
18515            return Present (Entity (Original_Node (Exp)))
18516              and then Ekind (Entity (Original_Node (Exp))) = E_Function;
18517
18518         when N_Qualified_Expression =>
18519            return
18520              OK_For_Limited_Init_In_05
18521                (Typ, Expression (Original_Node (Exp)));
18522
18523         --  Ada 2005 (AI-251): If a class-wide interface object is initialized
18524         --  with a function call, the expander has rewritten the call into an
18525         --  N_Type_Conversion node to force displacement of the pointer to
18526         --  reference the component containing the secondary dispatch table.
18527         --  Otherwise a type conversion is not a legal context.
18528         --  A return statement for a build-in-place function returning a
18529         --  synchronized type also introduces an unchecked conversion.
18530
18531         when N_Type_Conversion           |
18532              N_Unchecked_Type_Conversion =>
18533            return not Comes_From_Source (Exp)
18534              and then
18535                OK_For_Limited_Init_In_05
18536                  (Typ, Expression (Original_Node (Exp)));
18537
18538         when N_Indexed_Component     |
18539              N_Selected_Component    |
18540              N_Explicit_Dereference  =>
18541            return Nkind (Exp) = N_Function_Call;
18542
18543         --  A use of 'Input is a function call, hence allowed. Normally the
18544         --  attribute will be changed to a call, but the attribute by itself
18545         --  can occur with -gnatc.
18546
18547         when N_Attribute_Reference =>
18548            return Attribute_Name (Original_Node (Exp)) = Name_Input;
18549
18550         --  For a case expression, all dependent expressions must be legal
18551
18552         when N_Case_Expression =>
18553            declare
18554               Alt : Node_Id;
18555
18556            begin
18557               Alt := First (Alternatives (Original_Node (Exp)));
18558               while Present (Alt) loop
18559                  if not OK_For_Limited_Init_In_05 (Typ, Expression (Alt)) then
18560                     return False;
18561                  end if;
18562
18563                  Next (Alt);
18564               end loop;
18565
18566               return True;
18567            end;
18568
18569         --  For an if expression, all dependent expressions must be legal
18570
18571         when N_If_Expression =>
18572            declare
18573               Then_Expr : constant Node_Id :=
18574                             Next (First (Expressions (Original_Node (Exp))));
18575               Else_Expr : constant Node_Id := Next (Then_Expr);
18576            begin
18577               return OK_For_Limited_Init_In_05 (Typ, Then_Expr)
18578                        and then
18579                      OK_For_Limited_Init_In_05 (Typ, Else_Expr);
18580            end;
18581
18582         when others =>
18583            return False;
18584      end case;
18585   end OK_For_Limited_Init_In_05;
18586
18587   -------------------------------------------
18588   -- Ordinary_Fixed_Point_Type_Declaration --
18589   -------------------------------------------
18590
18591   procedure Ordinary_Fixed_Point_Type_Declaration
18592     (T   : Entity_Id;
18593      Def : Node_Id)
18594   is
18595      Loc           : constant Source_Ptr := Sloc (Def);
18596      Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
18597      RRS           : constant Node_Id    := Real_Range_Specification (Def);
18598      Implicit_Base : Entity_Id;
18599      Delta_Val     : Ureal;
18600      Small_Val     : Ureal;
18601      Low_Val       : Ureal;
18602      High_Val      : Ureal;
18603
18604   begin
18605      Check_Restriction (No_Fixed_Point, Def);
18606
18607      --  Create implicit base type
18608
18609      Implicit_Base :=
18610        Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
18611      Set_Etype (Implicit_Base, Implicit_Base);
18612
18613      --  Analyze and process delta expression
18614
18615      Analyze_And_Resolve (Delta_Expr, Any_Real);
18616
18617      Check_Delta_Expression (Delta_Expr);
18618      Delta_Val := Expr_Value_R (Delta_Expr);
18619
18620      Set_Delta_Value (Implicit_Base, Delta_Val);
18621
18622      --  Compute default small from given delta, which is the largest power
18623      --  of two that does not exceed the given delta value.
18624
18625      declare
18626         Tmp   : Ureal;
18627         Scale : Int;
18628
18629      begin
18630         Tmp := Ureal_1;
18631         Scale := 0;
18632
18633         if Delta_Val < Ureal_1 then
18634            while Delta_Val < Tmp loop
18635               Tmp := Tmp / Ureal_2;
18636               Scale := Scale + 1;
18637            end loop;
18638
18639         else
18640            loop
18641               Tmp := Tmp * Ureal_2;
18642               exit when Tmp > Delta_Val;
18643               Scale := Scale - 1;
18644            end loop;
18645         end if;
18646
18647         Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
18648      end;
18649
18650      Set_Small_Value (Implicit_Base, Small_Val);
18651
18652      --  If no range was given, set a dummy range
18653
18654      if RRS <= Empty_Or_Error then
18655         Low_Val  := -Small_Val;
18656         High_Val := Small_Val;
18657
18658      --  Otherwise analyze and process given range
18659
18660      else
18661         declare
18662            Low  : constant Node_Id := Low_Bound  (RRS);
18663            High : constant Node_Id := High_Bound (RRS);
18664
18665         begin
18666            Analyze_And_Resolve (Low, Any_Real);
18667            Analyze_And_Resolve (High, Any_Real);
18668            Check_Real_Bound (Low);
18669            Check_Real_Bound (High);
18670
18671            --  Obtain and set the range
18672
18673            Low_Val  := Expr_Value_R (Low);
18674            High_Val := Expr_Value_R (High);
18675
18676            if Low_Val > High_Val then
18677               Error_Msg_NE ("??fixed point type& has null range", Def, T);
18678            end if;
18679         end;
18680      end if;
18681
18682      --  The range for both the implicit base and the declared first subtype
18683      --  cannot be set yet, so we use the special routine Set_Fixed_Range to
18684      --  set a temporary range in place. Note that the bounds of the base
18685      --  type will be widened to be symmetrical and to fill the available
18686      --  bits when the type is frozen.
18687
18688      --  We could do this with all discrete types, and probably should, but
18689      --  we absolutely have to do it for fixed-point, since the end-points
18690      --  of the range and the size are determined by the small value, which
18691      --  could be reset before the freeze point.
18692
18693      Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
18694      Set_Fixed_Range (T, Loc, Low_Val, High_Val);
18695
18696      --  Complete definition of first subtype. The inheritance of the rep item
18697      --  chain ensures that SPARK-related pragmas are not clobbered when the
18698      --  ordinary fixed point type acts as a full view of a private type.
18699
18700      Set_Ekind              (T, E_Ordinary_Fixed_Point_Subtype);
18701      Set_Etype              (T, Implicit_Base);
18702      Init_Size_Align        (T);
18703      Inherit_Rep_Item_Chain (T, Implicit_Base);
18704      Set_Small_Value        (T, Small_Val);
18705      Set_Delta_Value        (T, Delta_Val);
18706      Set_Is_Constrained     (T);
18707   end Ordinary_Fixed_Point_Type_Declaration;
18708
18709   ----------------------------------
18710   -- Preanalyze_Assert_Expression --
18711   ----------------------------------
18712
18713   procedure Preanalyze_Assert_Expression (N : Node_Id; T : Entity_Id) is
18714   begin
18715      In_Assertion_Expr := In_Assertion_Expr + 1;
18716      Preanalyze_Spec_Expression (N, T);
18717      In_Assertion_Expr := In_Assertion_Expr - 1;
18718   end Preanalyze_Assert_Expression;
18719
18720   -----------------------------------
18721   -- Preanalyze_Default_Expression --
18722   -----------------------------------
18723
18724   procedure Preanalyze_Default_Expression (N : Node_Id; T : Entity_Id) is
18725      Save_In_Default_Expr : constant Boolean := In_Default_Expr;
18726   begin
18727      In_Default_Expr := True;
18728      Preanalyze_Spec_Expression (N, T);
18729      In_Default_Expr := Save_In_Default_Expr;
18730   end Preanalyze_Default_Expression;
18731
18732   --------------------------------
18733   -- Preanalyze_Spec_Expression --
18734   --------------------------------
18735
18736   procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
18737      Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
18738   begin
18739      In_Spec_Expression := True;
18740      Preanalyze_And_Resolve (N, T);
18741      In_Spec_Expression := Save_In_Spec_Expression;
18742   end Preanalyze_Spec_Expression;
18743
18744   ----------------------------------------
18745   -- Prepare_Private_Subtype_Completion --
18746   ----------------------------------------
18747
18748   procedure Prepare_Private_Subtype_Completion
18749     (Id          : Entity_Id;
18750      Related_Nod : Node_Id)
18751   is
18752      Id_B   : constant Entity_Id := Base_Type (Id);
18753      Full_B : Entity_Id := Full_View (Id_B);
18754      Full   : Entity_Id;
18755
18756   begin
18757      if Present (Full_B) then
18758
18759         --  Get to the underlying full view if necessary
18760
18761         if Is_Private_Type (Full_B)
18762           and then Present (Underlying_Full_View (Full_B))
18763         then
18764            Full_B := Underlying_Full_View (Full_B);
18765         end if;
18766
18767         --  The Base_Type is already completed, we can complete the subtype
18768         --  now. We have to create a new entity with the same name, Thus we
18769         --  can't use Create_Itype.
18770
18771         Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
18772         Set_Is_Itype (Full);
18773         Set_Associated_Node_For_Itype (Full, Related_Nod);
18774         Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
18775      end if;
18776
18777      --  The parent subtype may be private, but the base might not, in some
18778      --  nested instances. In that case, the subtype does not need to be
18779      --  exchanged. It would still be nice to make private subtypes and their
18780      --  bases consistent at all times ???
18781
18782      if Is_Private_Type (Id_B) then
18783         Append_Elmt (Id, Private_Dependents (Id_B));
18784      end if;
18785   end Prepare_Private_Subtype_Completion;
18786
18787   ---------------------------
18788   -- Process_Discriminants --
18789   ---------------------------
18790
18791   procedure Process_Discriminants
18792     (N    : Node_Id;
18793      Prev : Entity_Id := Empty)
18794   is
18795      Elist               : constant Elist_Id := New_Elmt_List;
18796      Id                  : Node_Id;
18797      Discr               : Node_Id;
18798      Discr_Number        : Uint;
18799      Discr_Type          : Entity_Id;
18800      Default_Present     : Boolean := False;
18801      Default_Not_Present : Boolean := False;
18802
18803   begin
18804      --  A composite type other than an array type can have discriminants.
18805      --  On entry, the current scope is the composite type.
18806
18807      --  The discriminants are initially entered into the scope of the type
18808      --  via Enter_Name with the default Ekind of E_Void to prevent premature
18809      --  use, as explained at the end of this procedure.
18810
18811      Discr := First (Discriminant_Specifications (N));
18812      while Present (Discr) loop
18813         Enter_Name (Defining_Identifier (Discr));
18814
18815         --  For navigation purposes we add a reference to the discriminant
18816         --  in the entity for the type. If the current declaration is a
18817         --  completion, place references on the partial view. Otherwise the
18818         --  type is the current scope.
18819
18820         if Present (Prev) then
18821
18822            --  The references go on the partial view, if present. If the
18823            --  partial view has discriminants, the references have been
18824            --  generated already.
18825
18826            if not Has_Discriminants (Prev) then
18827               Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
18828            end if;
18829         else
18830            Generate_Reference
18831              (Current_Scope, Defining_Identifier (Discr), 'd');
18832         end if;
18833
18834         if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
18835            Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
18836
18837            --  Ada 2005 (AI-254)
18838
18839            if Present (Access_To_Subprogram_Definition
18840                         (Discriminant_Type (Discr)))
18841              and then Protected_Present (Access_To_Subprogram_Definition
18842                                           (Discriminant_Type (Discr)))
18843            then
18844               Discr_Type :=
18845                 Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
18846            end if;
18847
18848         else
18849            Find_Type (Discriminant_Type (Discr));
18850            Discr_Type := Etype (Discriminant_Type (Discr));
18851
18852            if Error_Posted (Discriminant_Type (Discr)) then
18853               Discr_Type := Any_Type;
18854            end if;
18855         end if;
18856
18857         --  Handling of discriminants that are access types
18858
18859         if Is_Access_Type (Discr_Type) then
18860
18861            --  Ada 2005 (AI-230): Access discriminant allowed in non-
18862            --  limited record types
18863
18864            if Ada_Version < Ada_2005 then
18865               Check_Access_Discriminant_Requires_Limited
18866                 (Discr, Discriminant_Type (Discr));
18867            end if;
18868
18869            if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
18870               Error_Msg_N
18871                 ("(Ada 83) access discriminant not allowed", Discr);
18872            end if;
18873
18874         --  If not access type, must be a discrete type
18875
18876         elsif not Is_Discrete_Type (Discr_Type) then
18877            Error_Msg_N
18878              ("discriminants must have a discrete or access type",
18879               Discriminant_Type (Discr));
18880         end if;
18881
18882         Set_Etype (Defining_Identifier (Discr), Discr_Type);
18883
18884         --  If a discriminant specification includes the assignment compound
18885         --  delimiter followed by an expression, the expression is the default
18886         --  expression of the discriminant; the default expression must be of
18887         --  the type of the discriminant. (RM 3.7.1) Since this expression is
18888         --  a default expression, we do the special preanalysis, since this
18889         --  expression does not freeze (see section "Handling of Default and
18890         --  Per-Object Expressions" in spec of package Sem).
18891
18892         if Present (Expression (Discr)) then
18893            Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
18894
18895            --  Legaity checks
18896
18897            if Nkind (N) = N_Formal_Type_Declaration then
18898               Error_Msg_N
18899                 ("discriminant defaults not allowed for formal type",
18900                  Expression (Discr));
18901
18902            --  Flag an error for a tagged type with defaulted discriminants,
18903            --  excluding limited tagged types when compiling for Ada 2012
18904            --  (see AI05-0214).
18905
18906            elsif Is_Tagged_Type (Current_Scope)
18907              and then (not Is_Limited_Type (Current_Scope)
18908                         or else Ada_Version < Ada_2012)
18909              and then Comes_From_Source (N)
18910            then
18911               --  Note: see similar test in Check_Or_Process_Discriminants, to
18912               --  handle the (illegal) case of the completion of an untagged
18913               --  view with discriminants with defaults by a tagged full view.
18914               --  We skip the check if Discr does not come from source, to
18915               --  account for the case of an untagged derived type providing
18916               --  defaults for a renamed discriminant from a private untagged
18917               --  ancestor with a tagged full view (ACATS B460006).
18918
18919               if Ada_Version >= Ada_2012 then
18920                  Error_Msg_N
18921                    ("discriminants of nonlimited tagged type cannot have"
18922                       & " defaults",
18923                     Expression (Discr));
18924               else
18925                  Error_Msg_N
18926                    ("discriminants of tagged type cannot have defaults",
18927                     Expression (Discr));
18928               end if;
18929
18930            else
18931               Default_Present := True;
18932               Append_Elmt (Expression (Discr), Elist);
18933
18934               --  Tag the defining identifiers for the discriminants with
18935               --  their corresponding default expressions from the tree.
18936
18937               Set_Discriminant_Default_Value
18938                 (Defining_Identifier (Discr), Expression (Discr));
18939            end if;
18940
18941            --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag
18942            --  gets set unless we can be sure that no range check is required.
18943
18944            if (GNATprove_Mode or not Expander_Active)
18945              and then not
18946                Is_In_Range
18947                  (Expression (Discr), Discr_Type, Assume_Valid => True)
18948            then
18949               Set_Do_Range_Check (Expression (Discr));
18950            end if;
18951
18952         --  No default discriminant value given
18953
18954         else
18955            Default_Not_Present := True;
18956         end if;
18957
18958         --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
18959         --  Discr_Type but with the null-exclusion attribute
18960
18961         if Ada_Version >= Ada_2005 then
18962
18963            --  Ada 2005 (AI-231): Static checks
18964
18965            if Can_Never_Be_Null (Discr_Type) then
18966               Null_Exclusion_Static_Checks (Discr);
18967
18968            elsif Is_Access_Type (Discr_Type)
18969              and then Null_Exclusion_Present (Discr)
18970
18971               --  No need to check itypes because in their case this check
18972               --  was done at their point of creation
18973
18974              and then not Is_Itype (Discr_Type)
18975            then
18976               if Can_Never_Be_Null (Discr_Type) then
18977                  Error_Msg_NE
18978                    ("`NOT NULL` not allowed (& already excludes null)",
18979                     Discr,
18980                     Discr_Type);
18981               end if;
18982
18983               Set_Etype (Defining_Identifier (Discr),
18984                 Create_Null_Excluding_Itype
18985                   (T           => Discr_Type,
18986                    Related_Nod => Discr));
18987
18988            --  Check for improper null exclusion if the type is otherwise
18989            --  legal for a discriminant.
18990
18991            elsif Null_Exclusion_Present (Discr)
18992              and then Is_Discrete_Type (Discr_Type)
18993            then
18994               Error_Msg_N
18995                 ("null exclusion can only apply to an access type", Discr);
18996            end if;
18997
18998            --  Ada 2005 (AI-402): access discriminants of nonlimited types
18999            --  can't have defaults. Synchronized types, or types that are
19000            --  explicitly limited are fine, but special tests apply to derived
19001            --  types in generics: in a generic body we have to assume the
19002            --  worst, and therefore defaults are not allowed if the parent is
19003            --  a generic formal private type (see ACATS B370001).
19004
19005            if Is_Access_Type (Discr_Type) and then Default_Present then
19006               if Ekind (Discr_Type) /= E_Anonymous_Access_Type
19007                 or else Is_Limited_Record (Current_Scope)
19008                 or else Is_Concurrent_Type (Current_Scope)
19009                 or else Is_Concurrent_Record_Type (Current_Scope)
19010                 or else Ekind (Current_Scope) = E_Limited_Private_Type
19011               then
19012                  if not Is_Derived_Type (Current_Scope)
19013                    or else not Is_Generic_Type (Etype (Current_Scope))
19014                    or else not In_Package_Body (Scope (Etype (Current_Scope)))
19015                    or else Limited_Present
19016                              (Type_Definition (Parent (Current_Scope)))
19017                  then
19018                     null;
19019
19020                  else
19021                     Error_Msg_N
19022                       ("access discriminants of nonlimited types cannot "
19023                        & "have defaults", Expression (Discr));
19024                  end if;
19025
19026               elsif Present (Expression (Discr)) then
19027                  Error_Msg_N
19028                    ("(Ada 2005) access discriminants of nonlimited types "
19029                     & "cannot have defaults", Expression (Discr));
19030               end if;
19031            end if;
19032         end if;
19033
19034         --  A discriminant cannot be effectively volatile. This check is only
19035         --  relevant when SPARK_Mode is on as it is not standard Ada legality
19036         --  rule (SPARK RM 7.1.3(6)).
19037
19038         if SPARK_Mode = On
19039           and then Is_Effectively_Volatile (Defining_Identifier (Discr))
19040         then
19041            Error_Msg_N ("discriminant cannot be volatile", Discr);
19042         end if;
19043
19044         Next (Discr);
19045      end loop;
19046
19047      --  An element list consisting of the default expressions of the
19048      --  discriminants is constructed in the above loop and used to set
19049      --  the Discriminant_Constraint attribute for the type. If an object
19050      --  is declared of this (record or task) type without any explicit
19051      --  discriminant constraint given, this element list will form the
19052      --  actual parameters for the corresponding initialization procedure
19053      --  for the type.
19054
19055      Set_Discriminant_Constraint (Current_Scope, Elist);
19056      Set_Stored_Constraint (Current_Scope, No_Elist);
19057
19058      --  Default expressions must be provided either for all or for none
19059      --  of the discriminants of a discriminant part. (RM 3.7.1)
19060
19061      if Default_Present and then Default_Not_Present then
19062         Error_Msg_N
19063           ("incomplete specification of defaults for discriminants", N);
19064      end if;
19065
19066      --  The use of the name of a discriminant is not allowed in default
19067      --  expressions of a discriminant part if the specification of the
19068      --  discriminant is itself given in the discriminant part. (RM 3.7.1)
19069
19070      --  To detect this, the discriminant names are entered initially with an
19071      --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
19072      --  attempt to use a void entity (for example in an expression that is
19073      --  type-checked) produces the error message: premature usage. Now after
19074      --  completing the semantic analysis of the discriminant part, we can set
19075      --  the Ekind of all the discriminants appropriately.
19076
19077      Discr := First (Discriminant_Specifications (N));
19078      Discr_Number := Uint_1;
19079      while Present (Discr) loop
19080         Id := Defining_Identifier (Discr);
19081         Set_Ekind (Id, E_Discriminant);
19082         Init_Component_Location (Id);
19083         Init_Esize (Id);
19084         Set_Discriminant_Number (Id, Discr_Number);
19085
19086         --  Make sure this is always set, even in illegal programs
19087
19088         Set_Corresponding_Discriminant (Id, Empty);
19089
19090         --  Initialize the Original_Record_Component to the entity itself.
19091         --  Inherit_Components will propagate the right value to
19092         --  discriminants in derived record types.
19093
19094         Set_Original_Record_Component (Id, Id);
19095
19096         --  Create the discriminal for the discriminant
19097
19098         Build_Discriminal (Id);
19099
19100         Next (Discr);
19101         Discr_Number := Discr_Number + 1;
19102      end loop;
19103
19104      Set_Has_Discriminants (Current_Scope);
19105   end Process_Discriminants;
19106
19107   -----------------------
19108   -- Process_Full_View --
19109   -----------------------
19110
19111   procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
19112      procedure Collect_Implemented_Interfaces
19113        (Typ    : Entity_Id;
19114         Ifaces : Elist_Id);
19115      --  Ada 2005: Gather all the interfaces that Typ directly or
19116      --  inherently implements. Duplicate entries are not added to
19117      --  the list Ifaces.
19118
19119      ------------------------------------
19120      -- Collect_Implemented_Interfaces --
19121      ------------------------------------
19122
19123      procedure Collect_Implemented_Interfaces
19124        (Typ    : Entity_Id;
19125         Ifaces : Elist_Id)
19126      is
19127         Iface      : Entity_Id;
19128         Iface_Elmt : Elmt_Id;
19129
19130      begin
19131         --  Abstract interfaces are only associated with tagged record types
19132
19133         if not Is_Tagged_Type (Typ) or else not Is_Record_Type (Typ) then
19134            return;
19135         end if;
19136
19137         --  Recursively climb to the ancestors
19138
19139         if Etype (Typ) /= Typ
19140
19141            --  Protect the frontend against wrong cyclic declarations like:
19142
19143            --     type B is new A with private;
19144            --     type C is new A with private;
19145            --  private
19146            --     type B is new C with null record;
19147            --     type C is new B with null record;
19148
19149           and then Etype (Typ) /= Priv_T
19150           and then Etype (Typ) /= Full_T
19151         then
19152            --  Keep separate the management of private type declarations
19153
19154            if Ekind (Typ) = E_Record_Type_With_Private then
19155
19156               --  Handle the following illegal usage:
19157               --      type Private_Type is tagged private;
19158               --   private
19159               --      type Private_Type is new Type_Implementing_Iface;
19160
19161               if Present (Full_View (Typ))
19162                 and then Etype (Typ) /= Full_View (Typ)
19163               then
19164                  if Is_Interface (Etype (Typ)) then
19165                     Append_Unique_Elmt (Etype (Typ), Ifaces);
19166                  end if;
19167
19168                  Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
19169               end if;
19170
19171            --  Non-private types
19172
19173            else
19174               if Is_Interface (Etype (Typ)) then
19175                  Append_Unique_Elmt (Etype (Typ), Ifaces);
19176               end if;
19177
19178               Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
19179            end if;
19180         end if;
19181
19182         --  Handle entities in the list of abstract interfaces
19183
19184         if Present (Interfaces (Typ)) then
19185            Iface_Elmt := First_Elmt (Interfaces (Typ));
19186            while Present (Iface_Elmt) loop
19187               Iface := Node (Iface_Elmt);
19188
19189               pragma Assert (Is_Interface (Iface));
19190
19191               if not Contain_Interface (Iface, Ifaces) then
19192                  Append_Elmt (Iface, Ifaces);
19193                  Collect_Implemented_Interfaces (Iface, Ifaces);
19194               end if;
19195
19196               Next_Elmt (Iface_Elmt);
19197            end loop;
19198         end if;
19199      end Collect_Implemented_Interfaces;
19200
19201      --  Local variables
19202
19203      Full_Indic  : Node_Id;
19204      Full_Parent : Entity_Id;
19205      Priv_Parent : Entity_Id;
19206
19207   --  Start of processing for Process_Full_View
19208
19209   begin
19210      --  First some sanity checks that must be done after semantic
19211      --  decoration of the full view and thus cannot be placed with other
19212      --  similar checks in Find_Type_Name
19213
19214      if not Is_Limited_Type (Priv_T)
19215        and then (Is_Limited_Type (Full_T)
19216                   or else Is_Limited_Composite (Full_T))
19217      then
19218         if In_Instance then
19219            null;
19220         else
19221            Error_Msg_N
19222              ("completion of nonlimited type cannot be limited", Full_T);
19223            Explain_Limited_Type (Full_T, Full_T);
19224         end if;
19225
19226      elsif Is_Abstract_Type (Full_T)
19227        and then not Is_Abstract_Type (Priv_T)
19228      then
19229         Error_Msg_N
19230           ("completion of nonabstract type cannot be abstract", Full_T);
19231
19232      elsif Is_Tagged_Type (Priv_T)
19233        and then Is_Limited_Type (Priv_T)
19234        and then not Is_Limited_Type (Full_T)
19235      then
19236         --  If pragma CPP_Class was applied to the private declaration
19237         --  propagate the limitedness to the full-view
19238
19239         if Is_CPP_Class (Priv_T) then
19240            Set_Is_Limited_Record (Full_T);
19241
19242         --  GNAT allow its own definition of Limited_Controlled to disobey
19243         --  this rule in order in ease the implementation. This test is safe
19244         --  because Root_Controlled is defined in a child of System that
19245         --  normal programs are not supposed to use.
19246
19247         elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
19248            Set_Is_Limited_Composite (Full_T);
19249         else
19250            Error_Msg_N
19251              ("completion of limited tagged type must be limited", Full_T);
19252         end if;
19253
19254      elsif Is_Generic_Type (Priv_T) then
19255         Error_Msg_N ("generic type cannot have a completion", Full_T);
19256      end if;
19257
19258      --  Check that ancestor interfaces of private and full views are
19259      --  consistent. We omit this check for synchronized types because
19260      --  they are performed on the corresponding record type when frozen.
19261
19262      if Ada_Version >= Ada_2005
19263        and then Is_Tagged_Type (Priv_T)
19264        and then Is_Tagged_Type (Full_T)
19265        and then not Is_Concurrent_Type (Full_T)
19266      then
19267         declare
19268            Iface         : Entity_Id;
19269            Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
19270            Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
19271
19272         begin
19273            Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
19274            Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
19275
19276            --  Ada 2005 (AI-251): The partial view shall be a descendant of
19277            --  an interface type if and only if the full type is descendant
19278            --  of the interface type (AARM 7.3 (7.3/2)).
19279
19280            Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
19281
19282            if Present (Iface) then
19283               Error_Msg_NE
19284                 ("interface in partial view& not implemented by full type "
19285                  & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
19286            end if;
19287
19288            Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
19289
19290            if Present (Iface) then
19291               Error_Msg_NE
19292                 ("interface & not implemented by partial view "
19293                  & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
19294            end if;
19295         end;
19296      end if;
19297
19298      if Is_Tagged_Type (Priv_T)
19299        and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
19300        and then Is_Derived_Type (Full_T)
19301      then
19302         Priv_Parent := Etype (Priv_T);
19303
19304         --  The full view of a private extension may have been transformed
19305         --  into an unconstrained derived type declaration and a subtype
19306         --  declaration (see build_derived_record_type for details).
19307
19308         if Nkind (N) = N_Subtype_Declaration then
19309            Full_Indic  := Subtype_Indication (N);
19310            Full_Parent := Etype (Base_Type (Full_T));
19311         else
19312            Full_Indic  := Subtype_Indication (Type_Definition (N));
19313            Full_Parent := Etype (Full_T);
19314         end if;
19315
19316         --  Check that the parent type of the full type is a descendant of
19317         --  the ancestor subtype given in the private extension. If either
19318         --  entity has an Etype equal to Any_Type then we had some previous
19319         --  error situation [7.3(8)].
19320
19321         if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
19322            return;
19323
19324         --  Ada 2005 (AI-251): Interfaces in the full type can be given in
19325         --  any order. Therefore we don't have to check that its parent must
19326         --  be a descendant of the parent of the private type declaration.
19327
19328         elsif Is_Interface (Priv_Parent)
19329           and then Is_Interface (Full_Parent)
19330         then
19331            null;
19332
19333         --  Ada 2005 (AI-251): If the parent of the private type declaration
19334         --  is an interface there is no need to check that it is an ancestor
19335         --  of the associated full type declaration. The required tests for
19336         --  this case are performed by Build_Derived_Record_Type.
19337
19338         elsif not Is_Interface (Base_Type (Priv_Parent))
19339           and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
19340         then
19341            Error_Msg_N
19342              ("parent of full type must descend from parent"
19343                  & " of private extension", Full_Indic);
19344
19345         --  First check a formal restriction, and then proceed with checking
19346         --  Ada rules. Since the formal restriction is not a serious error, we
19347         --  don't prevent further error detection for this check, hence the
19348         --  ELSE.
19349
19350         else
19351            --  In formal mode, when completing a private extension the type
19352            --  named in the private part must be exactly the same as that
19353            --  named in the visible part.
19354
19355            if Priv_Parent /= Full_Parent then
19356               Error_Msg_Name_1 := Chars (Priv_Parent);
19357               Check_SPARK_05_Restriction ("% expected", Full_Indic);
19358            end if;
19359
19360            --  Check the rules of 7.3(10): if the private extension inherits
19361            --  known discriminants, then the full type must also inherit those
19362            --  discriminants from the same (ancestor) type, and the parent
19363            --  subtype of the full type must be constrained if and only if
19364            --  the ancestor subtype of the private extension is constrained.
19365
19366            if No (Discriminant_Specifications (Parent (Priv_T)))
19367              and then not Has_Unknown_Discriminants (Priv_T)
19368              and then Has_Discriminants (Base_Type (Priv_Parent))
19369            then
19370               declare
19371                  Priv_Indic  : constant Node_Id :=
19372                                  Subtype_Indication (Parent (Priv_T));
19373
19374                  Priv_Constr : constant Boolean :=
19375                                  Is_Constrained (Priv_Parent)
19376                                    or else
19377                                      Nkind (Priv_Indic) = N_Subtype_Indication
19378                                    or else
19379                                      Is_Constrained (Entity (Priv_Indic));
19380
19381                  Full_Constr : constant Boolean :=
19382                                  Is_Constrained (Full_Parent)
19383                                    or else
19384                                      Nkind (Full_Indic) = N_Subtype_Indication
19385                                    or else
19386                                      Is_Constrained (Entity (Full_Indic));
19387
19388                  Priv_Discr : Entity_Id;
19389                  Full_Discr : Entity_Id;
19390
19391               begin
19392                  Priv_Discr := First_Discriminant (Priv_Parent);
19393                  Full_Discr := First_Discriminant (Full_Parent);
19394                  while Present (Priv_Discr) and then Present (Full_Discr) loop
19395                     if Original_Record_Component (Priv_Discr) =
19396                        Original_Record_Component (Full_Discr)
19397                       or else
19398                         Corresponding_Discriminant (Priv_Discr) =
19399                         Corresponding_Discriminant (Full_Discr)
19400                     then
19401                        null;
19402                     else
19403                        exit;
19404                     end if;
19405
19406                     Next_Discriminant (Priv_Discr);
19407                     Next_Discriminant (Full_Discr);
19408                  end loop;
19409
19410                  if Present (Priv_Discr) or else Present (Full_Discr) then
19411                     Error_Msg_N
19412                       ("full view must inherit discriminants of the parent"
19413                        & " type used in the private extension", Full_Indic);
19414
19415                  elsif Priv_Constr and then not Full_Constr then
19416                     Error_Msg_N
19417                       ("parent subtype of full type must be constrained",
19418                        Full_Indic);
19419
19420                  elsif Full_Constr and then not Priv_Constr then
19421                     Error_Msg_N
19422                       ("parent subtype of full type must be unconstrained",
19423                        Full_Indic);
19424                  end if;
19425               end;
19426
19427               --  Check the rules of 7.3(12): if a partial view has neither
19428               --  known or unknown discriminants, then the full type
19429               --  declaration shall define a definite subtype.
19430
19431            elsif      not Has_Unknown_Discriminants (Priv_T)
19432              and then not Has_Discriminants (Priv_T)
19433              and then not Is_Constrained (Full_T)
19434            then
19435               Error_Msg_N
19436                 ("full view must define a constrained type if partial view"
19437                  & " has no discriminants", Full_T);
19438            end if;
19439
19440            --  ??????? Do we implement the following properly ?????
19441            --  If the ancestor subtype of a private extension has constrained
19442            --  discriminants, then the parent subtype of the full view shall
19443            --  impose a statically matching constraint on those discriminants
19444            --  [7.3(13)].
19445         end if;
19446
19447      else
19448         --  For untagged types, verify that a type without discriminants is
19449         --  not completed with an unconstrained type. A separate error message
19450         --  is produced if the full type has defaulted discriminants.
19451
19452         if not Is_Indefinite_Subtype (Priv_T)
19453           and then Is_Indefinite_Subtype (Full_T)
19454         then
19455            Error_Msg_Sloc := Sloc (Parent (Priv_T));
19456            Error_Msg_NE
19457              ("full view of& not compatible with declaration#",
19458               Full_T, Priv_T);
19459
19460            if not Is_Tagged_Type (Full_T) then
19461               Error_Msg_N
19462                 ("\one is constrained, the other unconstrained", Full_T);
19463            end if;
19464         end if;
19465      end if;
19466
19467      --  AI-419: verify that the use of "limited" is consistent
19468
19469      declare
19470         Orig_Decl : constant Node_Id := Original_Node (N);
19471
19472      begin
19473         if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
19474           and then Nkind (Orig_Decl) = N_Full_Type_Declaration
19475           and then Nkind
19476             (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
19477         then
19478            if not Limited_Present (Parent (Priv_T))
19479              and then not Synchronized_Present (Parent (Priv_T))
19480              and then Limited_Present (Type_Definition (Orig_Decl))
19481            then
19482               Error_Msg_N
19483                 ("full view of non-limited extension cannot be limited", N);
19484
19485            --  Conversely, if the partial view carries the limited keyword,
19486            --  the full view must as well, even if it may be redundant.
19487
19488            elsif Limited_Present (Parent (Priv_T))
19489              and then not Limited_Present (Type_Definition (Orig_Decl))
19490            then
19491               Error_Msg_N
19492                 ("full view of limited extension must be explicitly limited",
19493                  N);
19494            end if;
19495         end if;
19496      end;
19497
19498      --  Ada 2005 (AI-443): A synchronized private extension must be
19499      --  completed by a task or protected type.
19500
19501      if Ada_Version >= Ada_2005
19502        and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
19503        and then Synchronized_Present (Parent (Priv_T))
19504        and then not Is_Concurrent_Type (Full_T)
19505      then
19506         Error_Msg_N ("full view of synchronized extension must " &
19507                      "be synchronized type", N);
19508      end if;
19509
19510      --  Ada 2005 AI-363: if the full view has discriminants with
19511      --  defaults, it is illegal to declare constrained access subtypes
19512      --  whose designated type is the current type. This allows objects
19513      --  of the type that are declared in the heap to be unconstrained.
19514
19515      if not Has_Unknown_Discriminants (Priv_T)
19516        and then not Has_Discriminants (Priv_T)
19517        and then Has_Discriminants (Full_T)
19518        and then
19519          Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
19520      then
19521         Set_Has_Constrained_Partial_View (Full_T);
19522         Set_Has_Constrained_Partial_View (Priv_T);
19523      end if;
19524
19525      --  Create a full declaration for all its subtypes recorded in
19526      --  Private_Dependents and swap them similarly to the base type. These
19527      --  are subtypes that have been define before the full declaration of
19528      --  the private type. We also swap the entry in Private_Dependents list
19529      --  so we can properly restore the private view on exit from the scope.
19530
19531      declare
19532         Priv_Elmt : Elmt_Id;
19533         Priv_Scop : Entity_Id;
19534         Priv      : Entity_Id;
19535         Full      : Entity_Id;
19536
19537      begin
19538         Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
19539         while Present (Priv_Elmt) loop
19540            Priv := Node (Priv_Elmt);
19541            Priv_Scop := Scope (Priv);
19542
19543            if Ekind_In (Priv, E_Private_Subtype,
19544                               E_Limited_Private_Subtype,
19545                               E_Record_Subtype_With_Private)
19546            then
19547               Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
19548               Set_Is_Itype (Full);
19549               Set_Parent (Full, Parent (Priv));
19550               Set_Associated_Node_For_Itype (Full, N);
19551
19552               --  Now we need to complete the private subtype, but since the
19553               --  base type has already been swapped, we must also swap the
19554               --  subtypes (and thus, reverse the arguments in the call to
19555               --  Complete_Private_Subtype). Also note that we may need to
19556               --  re-establish the scope of the private subtype.
19557
19558               Copy_And_Swap (Priv, Full);
19559
19560               if not In_Open_Scopes (Priv_Scop) then
19561                  Push_Scope (Priv_Scop);
19562
19563               else
19564                  --  Reset Priv_Scop to Empty to indicate no scope was pushed
19565
19566                  Priv_Scop := Empty;
19567               end if;
19568
19569               Complete_Private_Subtype (Full, Priv, Full_T, N);
19570
19571               if Present (Priv_Scop) then
19572                  Pop_Scope;
19573               end if;
19574
19575               Replace_Elmt (Priv_Elmt, Full);
19576            end if;
19577
19578            Next_Elmt (Priv_Elmt);
19579         end loop;
19580      end;
19581
19582      --  If the private view was tagged, copy the new primitive operations
19583      --  from the private view to the full view.
19584
19585      if Is_Tagged_Type (Full_T) then
19586         declare
19587            Disp_Typ  : Entity_Id;
19588            Full_List : Elist_Id;
19589            Prim      : Entity_Id;
19590            Prim_Elmt : Elmt_Id;
19591            Priv_List : Elist_Id;
19592
19593            function Contains
19594              (E : Entity_Id;
19595               L : Elist_Id) return Boolean;
19596            --  Determine whether list L contains element E
19597
19598            --------------
19599            -- Contains --
19600            --------------
19601
19602            function Contains
19603              (E : Entity_Id;
19604               L : Elist_Id) return Boolean
19605            is
19606               List_Elmt : Elmt_Id;
19607
19608            begin
19609               List_Elmt := First_Elmt (L);
19610               while Present (List_Elmt) loop
19611                  if Node (List_Elmt) = E then
19612                     return True;
19613                  end if;
19614
19615                  Next_Elmt (List_Elmt);
19616               end loop;
19617
19618               return False;
19619            end Contains;
19620
19621         --  Start of processing
19622
19623         begin
19624            if Is_Tagged_Type (Priv_T) then
19625               Priv_List := Primitive_Operations (Priv_T);
19626               Prim_Elmt := First_Elmt (Priv_List);
19627
19628               --  In the case of a concurrent type completing a private tagged
19629               --  type, primitives may have been declared in between the two
19630               --  views. These subprograms need to be wrapped the same way
19631               --  entries and protected procedures are handled because they
19632               --  cannot be directly shared by the two views.
19633
19634               if Is_Concurrent_Type (Full_T) then
19635                  declare
19636                     Conc_Typ  : constant Entity_Id :=
19637                                   Corresponding_Record_Type (Full_T);
19638                     Curr_Nod  : Node_Id := Parent (Conc_Typ);
19639                     Wrap_Spec : Node_Id;
19640
19641                  begin
19642                     while Present (Prim_Elmt) loop
19643                        Prim := Node (Prim_Elmt);
19644
19645                        if Comes_From_Source (Prim)
19646                          and then not Is_Abstract_Subprogram (Prim)
19647                        then
19648                           Wrap_Spec :=
19649                             Make_Subprogram_Declaration (Sloc (Prim),
19650                               Specification =>
19651                                 Build_Wrapper_Spec
19652                                   (Subp_Id => Prim,
19653                                    Obj_Typ => Conc_Typ,
19654                                    Formals =>
19655                                      Parameter_Specifications (
19656                                        Parent (Prim))));
19657
19658                           Insert_After (Curr_Nod, Wrap_Spec);
19659                           Curr_Nod := Wrap_Spec;
19660
19661                           Analyze (Wrap_Spec);
19662                        end if;
19663
19664                        Next_Elmt (Prim_Elmt);
19665                     end loop;
19666
19667                     return;
19668                  end;
19669
19670               --  For non-concurrent types, transfer explicit primitives, but
19671               --  omit those inherited from the parent of the private view
19672               --  since they will be re-inherited later on.
19673
19674               else
19675                  Full_List := Primitive_Operations (Full_T);
19676
19677                  while Present (Prim_Elmt) loop
19678                     Prim := Node (Prim_Elmt);
19679
19680                     if Comes_From_Source (Prim)
19681                       and then not Contains (Prim, Full_List)
19682                     then
19683                        Append_Elmt (Prim, Full_List);
19684                     end if;
19685
19686                     Next_Elmt (Prim_Elmt);
19687                  end loop;
19688               end if;
19689
19690            --  Untagged private view
19691
19692            else
19693               Full_List := Primitive_Operations (Full_T);
19694
19695               --  In this case the partial view is untagged, so here we locate
19696               --  all of the earlier primitives that need to be treated as
19697               --  dispatching (those that appear between the two views). Note
19698               --  that these additional operations must all be new operations
19699               --  (any earlier operations that override inherited operations
19700               --  of the full view will already have been inserted in the
19701               --  primitives list, marked by Check_Operation_From_Private_View
19702               --  as dispatching. Note that implicit "/=" operators are
19703               --  excluded from being added to the primitives list since they
19704               --  shouldn't be treated as dispatching (tagged "/=" is handled
19705               --  specially).
19706
19707               Prim := Next_Entity (Full_T);
19708               while Present (Prim) and then Prim /= Priv_T loop
19709                  if Ekind_In (Prim, E_Procedure, E_Function) then
19710                     Disp_Typ := Find_Dispatching_Type (Prim);
19711
19712                     if Disp_Typ = Full_T
19713                       and then (Chars (Prim) /= Name_Op_Ne
19714                                  or else Comes_From_Source (Prim))
19715                     then
19716                        Check_Controlling_Formals (Full_T, Prim);
19717
19718                        if not Is_Dispatching_Operation (Prim) then
19719                           Append_Elmt (Prim, Full_List);
19720                           Set_Is_Dispatching_Operation (Prim, True);
19721                           Set_DT_Position_Value (Prim, No_Uint);
19722                        end if;
19723
19724                     elsif Is_Dispatching_Operation (Prim)
19725                       and then Disp_Typ  /= Full_T
19726                     then
19727
19728                        --  Verify that it is not otherwise controlled by a
19729                        --  formal or a return value of type T.
19730
19731                        Check_Controlling_Formals (Disp_Typ, Prim);
19732                     end if;
19733                  end if;
19734
19735                  Next_Entity (Prim);
19736               end loop;
19737            end if;
19738
19739            --  For the tagged case, the two views can share the same primitive
19740            --  operations list and the same class-wide type. Update attributes
19741            --  of the class-wide type which depend on the full declaration.
19742
19743            if Is_Tagged_Type (Priv_T) then
19744               Set_Direct_Primitive_Operations (Priv_T, Full_List);
19745               Set_Class_Wide_Type
19746                 (Base_Type (Full_T), Class_Wide_Type (Priv_T));
19747
19748               Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task      (Full_T));
19749               Set_Has_Protected
19750                            (Class_Wide_Type (Priv_T), Has_Protected (Full_T));
19751            end if;
19752         end;
19753      end if;
19754
19755      --  Ada 2005 AI 161: Check preelaborable initialization consistency
19756
19757      if Known_To_Have_Preelab_Init (Priv_T) then
19758
19759         --  Case where there is a pragma Preelaborable_Initialization. We
19760         --  always allow this in predefined units, which is cheating a bit,
19761         --  but it means we don't have to struggle to meet the requirements in
19762         --  the RM for having Preelaborable Initialization. Otherwise we
19763         --  require that the type meets the RM rules. But we can't check that
19764         --  yet, because of the rule about overriding Initialize, so we simply
19765         --  set a flag that will be checked at freeze time.
19766
19767         if not In_Predefined_Unit (Full_T) then
19768            Set_Must_Have_Preelab_Init (Full_T);
19769         end if;
19770      end if;
19771
19772      --  If pragma CPP_Class was applied to the private type declaration,
19773      --  propagate it now to the full type declaration.
19774
19775      if Is_CPP_Class (Priv_T) then
19776         Set_Is_CPP_Class (Full_T);
19777         Set_Convention   (Full_T, Convention_CPP);
19778
19779         --  Check that components of imported CPP types do not have default
19780         --  expressions.
19781
19782         Check_CPP_Type_Has_No_Defaults (Full_T);
19783      end if;
19784
19785      --  If the private view has user specified stream attributes, then so has
19786      --  the full view.
19787
19788      --  Why the test, how could these flags be already set in Full_T ???
19789
19790      if Has_Specified_Stream_Read (Priv_T) then
19791         Set_Has_Specified_Stream_Read (Full_T);
19792      end if;
19793
19794      if Has_Specified_Stream_Write (Priv_T) then
19795         Set_Has_Specified_Stream_Write (Full_T);
19796      end if;
19797
19798      if Has_Specified_Stream_Input (Priv_T) then
19799         Set_Has_Specified_Stream_Input (Full_T);
19800      end if;
19801
19802      if Has_Specified_Stream_Output (Priv_T) then
19803         Set_Has_Specified_Stream_Output (Full_T);
19804      end if;
19805
19806      --  Propagate the attributes related to pragma Default_Initial_Condition
19807      --  from the private to the full view. Note that both flags are mutually
19808      --  exclusive.
19809
19810      if Has_Default_Init_Cond (Priv_T)
19811        or else Has_Inherited_Default_Init_Cond (Priv_T)
19812      then
19813         Propagate_Default_Init_Cond_Attributes
19814           (From_Typ             => Priv_T,
19815            To_Typ               => Full_T,
19816            Private_To_Full_View => True);
19817
19818      --  In the case where the full view is derived from another private type,
19819      --  the attributes related to pragma Default_Initial_Condition must be
19820      --  propagated from the full to the private view to maintain consistency
19821      --  of views.
19822
19823      --    package Pack is
19824      --       type Parent_Typ is private
19825      --         with Default_Initial_Condition ...;
19826      --    private
19827      --       type Parent_Typ is ...;
19828      --    end Pack;
19829
19830      --    with Pack; use Pack;
19831      --    package Pack_2 is
19832      --       type Deriv_Typ is private;         --  must inherit
19833      --    private
19834      --       type Deriv_Typ is new Parent_Typ;  --  must inherit
19835      --    end Pack_2;
19836
19837      elsif Has_Default_Init_Cond (Full_T)
19838        or else Has_Inherited_Default_Init_Cond (Full_T)
19839      then
19840         Propagate_Default_Init_Cond_Attributes
19841           (From_Typ             => Full_T,
19842            To_Typ               => Priv_T,
19843            Private_To_Full_View => True);
19844      end if;
19845
19846      --  Propagate the attributes related to pragma Ghost from the private to
19847      --  the full view.
19848
19849      if Is_Ghost_Entity (Priv_T) then
19850         Set_Is_Ghost_Entity (Full_T);
19851
19852         --  The Ghost policy in effect at the point of declaration and at the
19853         --  point of completion must match (SPARK RM 6.9(15)).
19854
19855         Check_Ghost_Completion (Priv_T, Full_T);
19856
19857         --  In the case where the private view of a tagged type lacks a parent
19858         --  type and is subject to pragma Ghost, ensure that the parent type
19859         --  specified by the full view is also Ghost (SPARK RM 6.9(9)).
19860
19861         if Is_Derived_Type (Full_T) then
19862            Check_Ghost_Derivation (Full_T);
19863         end if;
19864      end if;
19865
19866      --  Propagate invariants to full type
19867
19868      if Has_Invariants (Priv_T) then
19869         Set_Has_Invariants (Full_T);
19870         Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
19871      end if;
19872
19873      if Has_Inheritable_Invariants (Priv_T) then
19874         Set_Has_Inheritable_Invariants (Full_T);
19875      end if;
19876
19877      --  Check hidden inheritance of class-wide type invariants
19878
19879      if Ada_Version >= Ada_2012
19880        and then not Has_Inheritable_Invariants (Full_T)
19881        and then In_Private_Part (Current_Scope)
19882        and then Has_Interfaces (Full_T)
19883      then
19884         declare
19885            Ifaces : Elist_Id;
19886            AI     : Elmt_Id;
19887
19888         begin
19889            Collect_Interfaces (Full_T, Ifaces, Exclude_Parents => True);
19890
19891            AI := First_Elmt (Ifaces);
19892            while Present (AI) loop
19893               if Has_Inheritable_Invariants (Node (AI)) then
19894                  Error_Msg_N
19895                    ("hidden inheritance of class-wide type invariants " &
19896                     "not allowed", N);
19897                  exit;
19898               end if;
19899
19900               Next_Elmt (AI);
19901            end loop;
19902         end;
19903      end if;
19904
19905      --  Propagate predicates to full type, and predicate function if already
19906      --  defined. It is not clear that this can actually happen? the partial
19907      --  view cannot be frozen yet, and the predicate function has not been
19908      --  built. Still it is a cheap check and seems safer to make it.
19909
19910      if Has_Predicates (Priv_T) then
19911         if Present (Predicate_Function (Priv_T)) then
19912            Set_Predicate_Function (Full_T, Predicate_Function (Priv_T));
19913         end if;
19914
19915         Set_Has_Predicates (Full_T);
19916      end if;
19917   end Process_Full_View;
19918
19919   -----------------------------------
19920   -- Process_Incomplete_Dependents --
19921   -----------------------------------
19922
19923   procedure Process_Incomplete_Dependents
19924     (N      : Node_Id;
19925      Full_T : Entity_Id;
19926      Inc_T  : Entity_Id)
19927   is
19928      Inc_Elmt : Elmt_Id;
19929      Priv_Dep : Entity_Id;
19930      New_Subt : Entity_Id;
19931
19932      Disc_Constraint : Elist_Id;
19933
19934   begin
19935      if No (Private_Dependents (Inc_T)) then
19936         return;
19937      end if;
19938
19939      --  Itypes that may be generated by the completion of an incomplete
19940      --  subtype are not used by the back-end and not attached to the tree.
19941      --  They are created only for constraint-checking purposes.
19942
19943      Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
19944      while Present (Inc_Elmt) loop
19945         Priv_Dep := Node (Inc_Elmt);
19946
19947         if Ekind (Priv_Dep) = E_Subprogram_Type then
19948
19949            --  An Access_To_Subprogram type may have a return type or a
19950            --  parameter type that is incomplete. Replace with the full view.
19951
19952            if Etype (Priv_Dep) = Inc_T then
19953               Set_Etype (Priv_Dep, Full_T);
19954            end if;
19955
19956            declare
19957               Formal : Entity_Id;
19958
19959            begin
19960               Formal := First_Formal (Priv_Dep);
19961               while Present (Formal) loop
19962                  if Etype (Formal) = Inc_T then
19963                     Set_Etype (Formal, Full_T);
19964                  end if;
19965
19966                  Next_Formal (Formal);
19967               end loop;
19968            end;
19969
19970         elsif Is_Overloadable (Priv_Dep) then
19971
19972            --  If a subprogram in the incomplete dependents list is primitive
19973            --  for a tagged full type then mark it as a dispatching operation,
19974            --  check whether it overrides an inherited subprogram, and check
19975            --  restrictions on its controlling formals. Note that a protected
19976            --  operation is never dispatching: only its wrapper operation
19977            --  (which has convention Ada) is.
19978
19979            if Is_Tagged_Type (Full_T)
19980              and then Is_Primitive (Priv_Dep)
19981              and then Convention (Priv_Dep) /= Convention_Protected
19982            then
19983               Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
19984               Set_Is_Dispatching_Operation (Priv_Dep);
19985               Check_Controlling_Formals (Full_T, Priv_Dep);
19986            end if;
19987
19988         elsif Ekind (Priv_Dep) = E_Subprogram_Body then
19989
19990            --  Can happen during processing of a body before the completion
19991            --  of a TA type. Ignore, because spec is also on dependent list.
19992
19993            return;
19994
19995         --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
19996         --  corresponding subtype of the full view.
19997
19998         elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
19999            Set_Subtype_Indication
20000              (Parent (Priv_Dep), New_Occurrence_Of (Full_T, Sloc (Priv_Dep)));
20001            Set_Etype (Priv_Dep, Full_T);
20002            Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
20003            Set_Analyzed (Parent (Priv_Dep), False);
20004
20005            --  Reanalyze the declaration, suppressing the call to
20006            --  Enter_Name to avoid duplicate names.
20007
20008            Analyze_Subtype_Declaration
20009              (N    => Parent (Priv_Dep),
20010               Skip => True);
20011
20012         --  Dependent is a subtype
20013
20014         else
20015            --  We build a new subtype indication using the full view of the
20016            --  incomplete parent. The discriminant constraints have been
20017            --  elaborated already at the point of the subtype declaration.
20018
20019            New_Subt := Create_Itype (E_Void, N);
20020
20021            if Has_Discriminants (Full_T) then
20022               Disc_Constraint := Discriminant_Constraint (Priv_Dep);
20023            else
20024               Disc_Constraint := No_Elist;
20025            end if;
20026
20027            Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
20028            Set_Full_View (Priv_Dep, New_Subt);
20029         end if;
20030
20031         Next_Elmt (Inc_Elmt);
20032      end loop;
20033   end Process_Incomplete_Dependents;
20034
20035   --------------------------------
20036   -- Process_Range_Expr_In_Decl --
20037   --------------------------------
20038
20039   procedure Process_Range_Expr_In_Decl
20040     (R            : Node_Id;
20041      T            : Entity_Id;
20042      Subtyp       : Entity_Id := Empty;
20043      Check_List   : List_Id   := Empty_List;
20044      R_Check_Off  : Boolean   := False;
20045      In_Iter_Schm : Boolean   := False)
20046   is
20047      Lo, Hi      : Node_Id;
20048      R_Checks    : Check_Result;
20049      Insert_Node : Node_Id;
20050      Def_Id      : Entity_Id;
20051
20052   begin
20053      Analyze_And_Resolve (R, Base_Type (T));
20054
20055      if Nkind (R) = N_Range then
20056
20057         --  In SPARK, all ranges should be static, with the exception of the
20058         --  discrete type definition of a loop parameter specification.
20059
20060         if not In_Iter_Schm
20061           and then not Is_OK_Static_Range (R)
20062         then
20063            Check_SPARK_05_Restriction ("range should be static", R);
20064         end if;
20065
20066         Lo := Low_Bound (R);
20067         Hi := High_Bound (R);
20068
20069         --  Validity checks on the range of a quantified expression are
20070         --  delayed until the construct is transformed into a loop.
20071
20072         if Nkind (Parent (R)) = N_Loop_Parameter_Specification
20073           and then Nkind (Parent (Parent (R))) = N_Quantified_Expression
20074         then
20075            null;
20076
20077         --  We need to ensure validity of the bounds here, because if we
20078         --  go ahead and do the expansion, then the expanded code will get
20079         --  analyzed with range checks suppressed and we miss the check.
20080
20081         --  WARNING: The capture of the range bounds with xxx_FIRST/_LAST and
20082         --  the temporaries generated by routine Remove_Side_Effects by means
20083         --  of validity checks must use the same names. When a range appears
20084         --  in the parent of a generic, the range is processed with checks
20085         --  disabled as part of the generic context and with checks enabled
20086         --  for code generation purposes. This leads to link issues as the
20087         --  generic contains references to xxx_FIRST/_LAST, but the inlined
20088         --  template sees the temporaries generated by Remove_Side_Effects.
20089
20090         else
20091            Validity_Check_Range (R, Subtyp);
20092         end if;
20093
20094         --  If there were errors in the declaration, try and patch up some
20095         --  common mistakes in the bounds. The cases handled are literals
20096         --  which are Integer where the expected type is Real and vice versa.
20097         --  These corrections allow the compilation process to proceed further
20098         --  along since some basic assumptions of the format of the bounds
20099         --  are guaranteed.
20100
20101         if Etype (R) = Any_Type then
20102            if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
20103               Rewrite (Lo,
20104                 Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
20105
20106            elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
20107               Rewrite (Hi,
20108                 Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
20109
20110            elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
20111               Rewrite (Lo,
20112                 Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
20113
20114            elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
20115               Rewrite (Hi,
20116                 Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
20117            end if;
20118
20119            Set_Etype (Lo, T);
20120            Set_Etype (Hi, T);
20121         end if;
20122
20123         --  If the bounds of the range have been mistakenly given as string
20124         --  literals (perhaps in place of character literals), then an error
20125         --  has already been reported, but we rewrite the string literal as a
20126         --  bound of the range's type to avoid blowups in later processing
20127         --  that looks at static values.
20128
20129         if Nkind (Lo) = N_String_Literal then
20130            Rewrite (Lo,
20131              Make_Attribute_Reference (Sloc (Lo),
20132                Prefix         => New_Occurrence_Of (T, Sloc (Lo)),
20133                Attribute_Name => Name_First));
20134            Analyze_And_Resolve (Lo);
20135         end if;
20136
20137         if Nkind (Hi) = N_String_Literal then
20138            Rewrite (Hi,
20139              Make_Attribute_Reference (Sloc (Hi),
20140                Prefix         => New_Occurrence_Of (T, Sloc (Hi)),
20141                Attribute_Name => Name_First));
20142            Analyze_And_Resolve (Hi);
20143         end if;
20144
20145         --  If bounds aren't scalar at this point then exit, avoiding
20146         --  problems with further processing of the range in this procedure.
20147
20148         if not Is_Scalar_Type (Etype (Lo)) then
20149            return;
20150         end if;
20151
20152         --  Resolve (actually Sem_Eval) has checked that the bounds are in
20153         --  then range of the base type. Here we check whether the bounds
20154         --  are in the range of the subtype itself. Note that if the bounds
20155         --  represent the null range the Constraint_Error exception should
20156         --  not be raised.
20157
20158         --  ??? The following code should be cleaned up as follows
20159
20160         --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
20161         --     is done in the call to Range_Check (R, T); below
20162
20163         --  2. The use of R_Check_Off should be investigated and possibly
20164         --     removed, this would clean up things a bit.
20165
20166         if Is_Null_Range (Lo, Hi) then
20167            null;
20168
20169         else
20170            --  Capture values of bounds and generate temporaries for them
20171            --  if needed, before applying checks, since checks may cause
20172            --  duplication of the expression without forcing evaluation.
20173
20174            --  The forced evaluation removes side effects from expressions,
20175            --  which should occur also in GNATprove mode. Otherwise, we end up
20176            --  with unexpected insertions of actions at places where this is
20177            --  not supposed to occur, e.g. on default parameters of a call.
20178
20179            if Expander_Active or GNATprove_Mode then
20180
20181               --  Call Force_Evaluation to create declarations as needed to
20182               --  deal with side effects, and also create typ_FIRST/LAST
20183               --  entities for bounds if we have a subtype name.
20184
20185               --  Note: we do this transformation even if expansion is not
20186               --  active if we are in GNATprove_Mode since the transformation
20187               --  is in general required to ensure that the resulting tree has
20188               --  proper Ada semantics.
20189
20190               Force_Evaluation
20191                 (Lo, Related_Id => Subtyp, Is_Low_Bound  => True);
20192               Force_Evaluation
20193                 (Hi, Related_Id => Subtyp, Is_High_Bound => True);
20194            end if;
20195
20196            --  We use a flag here instead of suppressing checks on the type
20197            --  because the type we check against isn't necessarily the place
20198            --  where we put the check.
20199
20200            if not R_Check_Off then
20201               R_Checks := Get_Range_Checks (R, T);
20202
20203               --  Look up tree to find an appropriate insertion point. We
20204               --  can't just use insert_actions because later processing
20205               --  depends on the insertion node. Prior to Ada 2012 the
20206               --  insertion point could only be a declaration or a loop, but
20207               --  quantified expressions can appear within any context in an
20208               --  expression, and the insertion point can be any statement,
20209               --  pragma, or declaration.
20210
20211               Insert_Node := Parent (R);
20212               while Present (Insert_Node) loop
20213                  exit when
20214                    Nkind (Insert_Node) in N_Declaration
20215                    and then
20216                      not Nkind_In
20217                        (Insert_Node, N_Component_Declaration,
20218                                      N_Loop_Parameter_Specification,
20219                                      N_Function_Specification,
20220                                      N_Procedure_Specification);
20221
20222                  exit when Nkind (Insert_Node) in N_Later_Decl_Item
20223                    or else Nkind (Insert_Node) in
20224                              N_Statement_Other_Than_Procedure_Call
20225                    or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
20226                                                   N_Pragma);
20227
20228                  Insert_Node := Parent (Insert_Node);
20229               end loop;
20230
20231               --  Why would Type_Decl not be present???  Without this test,
20232               --  short regression tests fail.
20233
20234               if Present (Insert_Node) then
20235
20236                  --  Case of loop statement. Verify that the range is part
20237                  --  of the subtype indication of the iteration scheme.
20238
20239                  if Nkind (Insert_Node) = N_Loop_Statement then
20240                     declare
20241                        Indic : Node_Id;
20242
20243                     begin
20244                        Indic := Parent (R);
20245                        while Present (Indic)
20246                          and then Nkind (Indic) /= N_Subtype_Indication
20247                        loop
20248                           Indic := Parent (Indic);
20249                        end loop;
20250
20251                        if Present (Indic) then
20252                           Def_Id := Etype (Subtype_Mark (Indic));
20253
20254                           Insert_Range_Checks
20255                             (R_Checks,
20256                              Insert_Node,
20257                              Def_Id,
20258                              Sloc (Insert_Node),
20259                              R,
20260                              Do_Before => True);
20261                        end if;
20262                     end;
20263
20264                  --  Insertion before a declaration. If the declaration
20265                  --  includes discriminants, the list of applicable checks
20266                  --  is given by the caller.
20267
20268                  elsif Nkind (Insert_Node) in N_Declaration then
20269                     Def_Id := Defining_Identifier (Insert_Node);
20270
20271                     if (Ekind (Def_Id) = E_Record_Type
20272                          and then Depends_On_Discriminant (R))
20273                       or else
20274                        (Ekind (Def_Id) = E_Protected_Type
20275                          and then Has_Discriminants (Def_Id))
20276                     then
20277                        Append_Range_Checks
20278                          (R_Checks,
20279                            Check_List, Def_Id, Sloc (Insert_Node), R);
20280
20281                     else
20282                        Insert_Range_Checks
20283                          (R_Checks,
20284                            Insert_Node, Def_Id, Sloc (Insert_Node), R);
20285
20286                     end if;
20287
20288                  --  Insertion before a statement. Range appears in the
20289                  --  context of a quantified expression. Insertion will
20290                  --  take place when expression is expanded.
20291
20292                  else
20293                     null;
20294                  end if;
20295               end if;
20296            end if;
20297         end if;
20298
20299      --  Case of other than an explicit N_Range node
20300
20301      --  The forced evaluation removes side effects from expressions, which
20302      --  should occur also in GNATprove mode. Otherwise, we end up with
20303      --  unexpected insertions of actions at places where this is not
20304      --  supposed to occur, e.g. on default parameters of a call.
20305
20306      elsif Expander_Active or GNATprove_Mode then
20307         Get_Index_Bounds (R, Lo, Hi);
20308         Force_Evaluation (Lo);
20309         Force_Evaluation (Hi);
20310      end if;
20311   end Process_Range_Expr_In_Decl;
20312
20313   --------------------------------------
20314   -- Process_Real_Range_Specification --
20315   --------------------------------------
20316
20317   procedure Process_Real_Range_Specification (Def : Node_Id) is
20318      Spec : constant Node_Id := Real_Range_Specification (Def);
20319      Lo   : Node_Id;
20320      Hi   : Node_Id;
20321      Err  : Boolean := False;
20322
20323      procedure Analyze_Bound (N : Node_Id);
20324      --  Analyze and check one bound
20325
20326      -------------------
20327      -- Analyze_Bound --
20328      -------------------
20329
20330      procedure Analyze_Bound (N : Node_Id) is
20331      begin
20332         Analyze_And_Resolve (N, Any_Real);
20333
20334         if not Is_OK_Static_Expression (N) then
20335            Flag_Non_Static_Expr
20336              ("bound in real type definition is not static!", N);
20337            Err := True;
20338         end if;
20339      end Analyze_Bound;
20340
20341   --  Start of processing for Process_Real_Range_Specification
20342
20343   begin
20344      if Present (Spec) then
20345         Lo := Low_Bound (Spec);
20346         Hi := High_Bound (Spec);
20347         Analyze_Bound (Lo);
20348         Analyze_Bound (Hi);
20349
20350         --  If error, clear away junk range specification
20351
20352         if Err then
20353            Set_Real_Range_Specification (Def, Empty);
20354         end if;
20355      end if;
20356   end Process_Real_Range_Specification;
20357
20358   ---------------------
20359   -- Process_Subtype --
20360   ---------------------
20361
20362   function Process_Subtype
20363     (S           : Node_Id;
20364      Related_Nod : Node_Id;
20365      Related_Id  : Entity_Id := Empty;
20366      Suffix      : Character := ' ') return Entity_Id
20367   is
20368      P               : Node_Id;
20369      Def_Id          : Entity_Id;
20370      Error_Node      : Node_Id;
20371      Full_View_Id    : Entity_Id;
20372      Subtype_Mark_Id : Entity_Id;
20373
20374      May_Have_Null_Exclusion : Boolean;
20375
20376      procedure Check_Incomplete (T : Entity_Id);
20377      --  Called to verify that an incomplete type is not used prematurely
20378
20379      ----------------------
20380      -- Check_Incomplete --
20381      ----------------------
20382
20383      procedure Check_Incomplete (T : Entity_Id) is
20384      begin
20385         --  Ada 2005 (AI-412): Incomplete subtypes are legal
20386
20387         if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
20388           and then
20389             not (Ada_Version >= Ada_2005
20390                   and then
20391                     (Nkind (Parent (T)) = N_Subtype_Declaration
20392                       or else (Nkind (Parent (T)) = N_Subtype_Indication
20393                                 and then Nkind (Parent (Parent (T))) =
20394                                                   N_Subtype_Declaration)))
20395         then
20396            Error_Msg_N ("invalid use of type before its full declaration", T);
20397         end if;
20398      end Check_Incomplete;
20399
20400   --  Start of processing for Process_Subtype
20401
20402   begin
20403      --  Case of no constraints present
20404
20405      if Nkind (S) /= N_Subtype_Indication then
20406         Find_Type (S);
20407         Check_Incomplete (S);
20408         P := Parent (S);
20409
20410         --  Ada 2005 (AI-231): Static check
20411
20412         if Ada_Version >= Ada_2005
20413           and then Present (P)
20414           and then Null_Exclusion_Present (P)
20415           and then Nkind (P) /= N_Access_To_Object_Definition
20416           and then not Is_Access_Type (Entity (S))
20417         then
20418            Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
20419         end if;
20420
20421         --  The following is ugly, can't we have a range or even a flag???
20422
20423         May_Have_Null_Exclusion :=
20424           Nkind_In (P, N_Access_Definition,
20425                        N_Access_Function_Definition,
20426                        N_Access_Procedure_Definition,
20427                        N_Access_To_Object_Definition,
20428                        N_Allocator,
20429                        N_Component_Definition)
20430             or else
20431           Nkind_In (P, N_Derived_Type_Definition,
20432                        N_Discriminant_Specification,
20433                        N_Formal_Object_Declaration,
20434                        N_Object_Declaration,
20435                        N_Object_Renaming_Declaration,
20436                        N_Parameter_Specification,
20437                        N_Subtype_Declaration);
20438
20439         --  Create an Itype that is a duplicate of Entity (S) but with the
20440         --  null-exclusion attribute.
20441
20442         if May_Have_Null_Exclusion
20443           and then Is_Access_Type (Entity (S))
20444           and then Null_Exclusion_Present (P)
20445
20446            --  No need to check the case of an access to object definition.
20447            --  It is correct to define double not-null pointers.
20448
20449            --  Example:
20450            --     type Not_Null_Int_Ptr is not null access Integer;
20451            --     type Acc is not null access Not_Null_Int_Ptr;
20452
20453           and then Nkind (P) /= N_Access_To_Object_Definition
20454         then
20455            if Can_Never_Be_Null (Entity (S)) then
20456               case Nkind (Related_Nod) is
20457                  when N_Full_Type_Declaration =>
20458                     if Nkind (Type_Definition (Related_Nod))
20459                       in N_Array_Type_Definition
20460                     then
20461                        Error_Node :=
20462                          Subtype_Indication
20463                            (Component_Definition
20464                             (Type_Definition (Related_Nod)));
20465                     else
20466                        Error_Node :=
20467                          Subtype_Indication (Type_Definition (Related_Nod));
20468                     end if;
20469
20470                  when N_Subtype_Declaration =>
20471                     Error_Node := Subtype_Indication (Related_Nod);
20472
20473                  when N_Object_Declaration =>
20474                     Error_Node := Object_Definition (Related_Nod);
20475
20476                  when N_Component_Declaration =>
20477                     Error_Node :=
20478                       Subtype_Indication (Component_Definition (Related_Nod));
20479
20480                  when N_Allocator =>
20481                     Error_Node := Expression (Related_Nod);
20482
20483                  when others =>
20484                     pragma Assert (False);
20485                     Error_Node := Related_Nod;
20486               end case;
20487
20488               Error_Msg_NE
20489                 ("`NOT NULL` not allowed (& already excludes null)",
20490                  Error_Node,
20491                  Entity (S));
20492            end if;
20493
20494            Set_Etype  (S,
20495              Create_Null_Excluding_Itype
20496                (T           => Entity (S),
20497                 Related_Nod => P));
20498            Set_Entity (S, Etype (S));
20499         end if;
20500
20501         return Entity (S);
20502
20503      --  Case of constraint present, so that we have an N_Subtype_Indication
20504      --  node (this node is created only if constraints are present).
20505
20506      else
20507         Find_Type (Subtype_Mark (S));
20508
20509         if Nkind (Parent (S)) /= N_Access_To_Object_Definition
20510           and then not
20511            (Nkind (Parent (S)) = N_Subtype_Declaration
20512              and then Is_Itype (Defining_Identifier (Parent (S))))
20513         then
20514            Check_Incomplete (Subtype_Mark (S));
20515         end if;
20516
20517         P := Parent (S);
20518         Subtype_Mark_Id := Entity (Subtype_Mark (S));
20519
20520         --  Explicit subtype declaration case
20521
20522         if Nkind (P) = N_Subtype_Declaration then
20523            Def_Id := Defining_Identifier (P);
20524
20525         --  Explicit derived type definition case
20526
20527         elsif Nkind (P) = N_Derived_Type_Definition then
20528            Def_Id := Defining_Identifier (Parent (P));
20529
20530         --  Implicit case, the Def_Id must be created as an implicit type.
20531         --  The one exception arises in the case of concurrent types, array
20532         --  and access types, where other subsidiary implicit types may be
20533         --  created and must appear before the main implicit type. In these
20534         --  cases we leave Def_Id set to Empty as a signal that Create_Itype
20535         --  has not yet been called to create Def_Id.
20536
20537         else
20538            if Is_Array_Type (Subtype_Mark_Id)
20539              or else Is_Concurrent_Type (Subtype_Mark_Id)
20540              or else Is_Access_Type (Subtype_Mark_Id)
20541            then
20542               Def_Id := Empty;
20543
20544            --  For the other cases, we create a new unattached Itype,
20545            --  and set the indication to ensure it gets attached later.
20546
20547            else
20548               Def_Id :=
20549                 Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
20550            end if;
20551         end if;
20552
20553         --  If the kind of constraint is invalid for this kind of type,
20554         --  then give an error, and then pretend no constraint was given.
20555
20556         if not Is_Valid_Constraint_Kind
20557                   (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
20558         then
20559            Error_Msg_N
20560              ("incorrect constraint for this kind of type", Constraint (S));
20561
20562            Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
20563
20564            --  Set Ekind of orphan itype, to prevent cascaded errors
20565
20566            if Present (Def_Id) then
20567               Set_Ekind (Def_Id, Ekind (Any_Type));
20568            end if;
20569
20570            --  Make recursive call, having got rid of the bogus constraint
20571
20572            return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
20573         end if;
20574
20575         --  Remaining processing depends on type. Select on Base_Type kind to
20576         --  ensure getting to the concrete type kind in the case of a private
20577         --  subtype (needed when only doing semantic analysis).
20578
20579         case Ekind (Base_Type (Subtype_Mark_Id)) is
20580            when Access_Kind =>
20581
20582               --  If this is a constraint on a class-wide type, discard it.
20583               --  There is currently no way to express a partial discriminant
20584               --  constraint on a type with unknown discriminants. This is
20585               --  a pathology that the ACATS wisely decides not to test.
20586
20587               if Is_Class_Wide_Type (Designated_Type (Subtype_Mark_Id)) then
20588                  if Comes_From_Source (S) then
20589                     Error_Msg_N
20590                       ("constraint on class-wide type ignored??",
20591                        Constraint (S));
20592                  end if;
20593
20594                  if Nkind (P) = N_Subtype_Declaration then
20595                     Set_Subtype_Indication (P,
20596                        New_Occurrence_Of (Subtype_Mark_Id, Sloc (S)));
20597                  end if;
20598
20599                  return Subtype_Mark_Id;
20600               end if;
20601
20602               Constrain_Access (Def_Id, S, Related_Nod);
20603
20604               if Expander_Active
20605                 and then  Is_Itype (Designated_Type (Def_Id))
20606                 and then Nkind (Related_Nod) = N_Subtype_Declaration
20607                 and then not Is_Incomplete_Type (Designated_Type (Def_Id))
20608               then
20609                  Build_Itype_Reference
20610                    (Designated_Type (Def_Id), Related_Nod);
20611               end if;
20612
20613            when Array_Kind =>
20614               Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
20615
20616            when Decimal_Fixed_Point_Kind =>
20617               Constrain_Decimal (Def_Id, S);
20618
20619            when Enumeration_Kind =>
20620               Constrain_Enumeration (Def_Id, S);
20621               Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
20622
20623            when Ordinary_Fixed_Point_Kind =>
20624               Constrain_Ordinary_Fixed (Def_Id, S);
20625
20626            when Float_Kind =>
20627               Constrain_Float (Def_Id, S);
20628
20629            when Integer_Kind =>
20630               Constrain_Integer (Def_Id, S);
20631               Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
20632
20633            when E_Record_Type     |
20634                 E_Record_Subtype  |
20635                 Class_Wide_Kind   |
20636                 E_Incomplete_Type =>
20637               Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
20638
20639               if Ekind (Def_Id) = E_Incomplete_Type then
20640                  Set_Private_Dependents (Def_Id, New_Elmt_List);
20641               end if;
20642
20643            when Private_Kind =>
20644               Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
20645               Set_Private_Dependents (Def_Id, New_Elmt_List);
20646
20647               --  In case of an invalid constraint prevent further processing
20648               --  since the type constructed is missing expected fields.
20649
20650               if Etype (Def_Id) = Any_Type then
20651                  return Def_Id;
20652               end if;
20653
20654               --  If the full view is that of a task with discriminants,
20655               --  we must constrain both the concurrent type and its
20656               --  corresponding record type. Otherwise we will just propagate
20657               --  the constraint to the full view, if available.
20658
20659               if Present (Full_View (Subtype_Mark_Id))
20660                 and then Has_Discriminants (Subtype_Mark_Id)
20661                 and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
20662               then
20663                  Full_View_Id :=
20664                    Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
20665
20666                  Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
20667                  Constrain_Concurrent (Full_View_Id, S,
20668                    Related_Nod, Related_Id, Suffix);
20669                  Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
20670                  Set_Full_View (Def_Id, Full_View_Id);
20671
20672                  --  Introduce an explicit reference to the private subtype,
20673                  --  to prevent scope anomalies in gigi if first use appears
20674                  --  in a nested context, e.g. a later function body.
20675                  --  Should this be generated in other contexts than a full
20676                  --  type declaration?
20677
20678                  if Is_Itype (Def_Id)
20679                    and then
20680                      Nkind (Parent (P)) = N_Full_Type_Declaration
20681                  then
20682                     Build_Itype_Reference (Def_Id, Parent (P));
20683                  end if;
20684
20685               else
20686                  Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
20687               end if;
20688
20689            when Concurrent_Kind  =>
20690               Constrain_Concurrent (Def_Id, S,
20691                 Related_Nod, Related_Id, Suffix);
20692
20693            when others =>
20694               Error_Msg_N ("invalid subtype mark in subtype indication", S);
20695         end case;
20696
20697         --  Size and Convention are always inherited from the base type
20698
20699         Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
20700         Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
20701
20702         return Def_Id;
20703      end if;
20704   end Process_Subtype;
20705
20706   --------------------------------------------
20707   -- Propagate_Default_Init_Cond_Attributes --
20708   --------------------------------------------
20709
20710   procedure Propagate_Default_Init_Cond_Attributes
20711     (From_Typ             : Entity_Id;
20712      To_Typ               : Entity_Id;
20713      Parent_To_Derivation : Boolean := False;
20714      Private_To_Full_View : Boolean := False)
20715   is
20716      procedure Remove_Default_Init_Cond_Procedure (Typ : Entity_Id);
20717      --  Remove the default initial procedure (if any) from the rep chain of
20718      --  type Typ.
20719
20720      ----------------------------------------
20721      -- Remove_Default_Init_Cond_Procedure --
20722      ----------------------------------------
20723
20724      procedure Remove_Default_Init_Cond_Procedure (Typ : Entity_Id) is
20725         Found : Boolean := False;
20726         Prev  : Entity_Id;
20727         Subp  : Entity_Id;
20728
20729      begin
20730         Prev := Typ;
20731         Subp := Subprograms_For_Type (Typ);
20732         while Present (Subp) loop
20733            if Is_Default_Init_Cond_Procedure (Subp) then
20734               Found := True;
20735               exit;
20736            end if;
20737
20738            Prev := Subp;
20739            Subp := Subprograms_For_Type (Subp);
20740         end loop;
20741
20742         if Found then
20743            Set_Subprograms_For_Type (Prev, Subprograms_For_Type (Subp));
20744            Set_Subprograms_For_Type (Subp, Empty);
20745         end if;
20746      end Remove_Default_Init_Cond_Procedure;
20747
20748      --  Local variables
20749
20750      Inherit_Procedure : Boolean := False;
20751
20752   --  Start of processing for Propagate_Default_Init_Cond_Attributes
20753
20754   begin
20755      if Has_Default_Init_Cond (From_Typ) then
20756
20757         --  A derived type inherits the attributes from its parent type
20758
20759         if Parent_To_Derivation then
20760            Set_Has_Inherited_Default_Init_Cond (To_Typ);
20761
20762         --  A full view shares the attributes with its private view
20763
20764         else
20765            Set_Has_Default_Init_Cond (To_Typ);
20766         end if;
20767
20768         Inherit_Procedure := True;
20769
20770         --  Due to the order of expansion, a derived private type is processed
20771         --  by two routines which both attempt to set the attributes related
20772         --  to pragma Default_Initial_Condition - Build_Derived_Type and then
20773         --  Process_Full_View.
20774
20775         --    package Pack is
20776         --       type Parent_Typ is private
20777         --         with Default_Initial_Condition ...;
20778         --    private
20779         --       type Parent_Typ is ...;
20780         --    end Pack;
20781
20782         --    with Pack; use Pack;
20783         --    package Pack_2 is
20784         --       type Deriv_Typ is private
20785         --         with Default_Initial_Condition ...;
20786         --    private
20787         --       type Deriv_Typ is new Parent_Typ;
20788         --    end Pack_2;
20789
20790         --  When Build_Derived_Type operates, it sets the attributes on the
20791         --  full view without taking into account that the private view may
20792         --  define its own default initial condition procedure. This becomes
20793         --  apparent in Process_Full_View which must undo some of the work by
20794         --  Build_Derived_Type and propagate the attributes from the private
20795         --  to the full view.
20796
20797         if Private_To_Full_View then
20798            Set_Has_Inherited_Default_Init_Cond (To_Typ, False);
20799            Remove_Default_Init_Cond_Procedure (To_Typ);
20800         end if;
20801
20802      --  A type must inherit the default initial condition procedure from a
20803      --  parent type when the parent itself is inheriting the procedure or
20804      --  when it is defining one. This circuitry is also used when dealing
20805      --  with the private / full view of a type.
20806
20807      elsif Has_Inherited_Default_Init_Cond (From_Typ)
20808        or (Parent_To_Derivation
20809              and Present (Get_Pragma
20810                    (From_Typ, Pragma_Default_Initial_Condition)))
20811      then
20812         Set_Has_Inherited_Default_Init_Cond (To_Typ);
20813         Inherit_Procedure := True;
20814      end if;
20815
20816      if Inherit_Procedure
20817        and then No (Default_Init_Cond_Procedure (To_Typ))
20818      then
20819         Set_Default_Init_Cond_Procedure
20820           (To_Typ, Default_Init_Cond_Procedure (From_Typ));
20821      end if;
20822   end Propagate_Default_Init_Cond_Attributes;
20823
20824   -----------------------------
20825   -- Record_Type_Declaration --
20826   -----------------------------
20827
20828   procedure Record_Type_Declaration
20829     (T    : Entity_Id;
20830      N    : Node_Id;
20831      Prev : Entity_Id)
20832   is
20833      Def       : constant Node_Id := Type_Definition (N);
20834      Is_Tagged : Boolean;
20835      Tag_Comp  : Entity_Id;
20836
20837   begin
20838      --  These flags must be initialized before calling Process_Discriminants
20839      --  because this routine makes use of them.
20840
20841      Set_Ekind             (T, E_Record_Type);
20842      Set_Etype             (T, T);
20843      Init_Size_Align       (T);
20844      Set_Interfaces        (T, No_Elist);
20845      Set_Stored_Constraint (T, No_Elist);
20846      Set_Default_SSO       (T);
20847
20848      --  Normal case
20849
20850      if Ada_Version < Ada_2005 or else not Interface_Present (Def) then
20851         if Limited_Present (Def) then
20852            Check_SPARK_05_Restriction ("limited is not allowed", N);
20853         end if;
20854
20855         if Abstract_Present (Def) then
20856            Check_SPARK_05_Restriction ("abstract is not allowed", N);
20857         end if;
20858
20859         --  The flag Is_Tagged_Type might have already been set by
20860         --  Find_Type_Name if it detected an error for declaration T. This
20861         --  arises in the case of private tagged types where the full view
20862         --  omits the word tagged.
20863
20864         Is_Tagged :=
20865           Tagged_Present (Def)
20866             or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
20867
20868         Set_Is_Limited_Record (T, Limited_Present (Def));
20869
20870         if Is_Tagged then
20871            Set_Is_Tagged_Type (T, True);
20872            Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
20873         end if;
20874
20875         --  Type is abstract if full declaration carries keyword, or if
20876         --  previous partial view did.
20877
20878         Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
20879                                      or else Abstract_Present (Def));
20880
20881      else
20882         Check_SPARK_05_Restriction ("interface is not allowed", N);
20883
20884         Is_Tagged := True;
20885         Analyze_Interface_Declaration (T, Def);
20886
20887         if Present (Discriminant_Specifications (N)) then
20888            Error_Msg_N
20889              ("interface types cannot have discriminants",
20890                Defining_Identifier
20891                  (First (Discriminant_Specifications (N))));
20892         end if;
20893      end if;
20894
20895      --  First pass: if there are self-referential access components,
20896      --  create the required anonymous access type declarations, and if
20897      --  need be an incomplete type declaration for T itself.
20898
20899      Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
20900
20901      if Ada_Version >= Ada_2005
20902        and then Present (Interface_List (Def))
20903      then
20904         Check_Interfaces (N, Def);
20905
20906         declare
20907            Ifaces_List : Elist_Id;
20908
20909         begin
20910            --  Ada 2005 (AI-251): Collect the list of progenitors that are not
20911            --  already in the parents.
20912
20913            Collect_Interfaces
20914              (T               => T,
20915               Ifaces_List     => Ifaces_List,
20916               Exclude_Parents => True);
20917
20918            Set_Interfaces (T, Ifaces_List);
20919         end;
20920      end if;
20921
20922      --  Records constitute a scope for the component declarations within.
20923      --  The scope is created prior to the processing of these declarations.
20924      --  Discriminants are processed first, so that they are visible when
20925      --  processing the other components. The Ekind of the record type itself
20926      --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
20927
20928      --  Enter record scope
20929
20930      Push_Scope (T);
20931
20932      --  If an incomplete or private type declaration was already given for
20933      --  the type, then this scope already exists, and the discriminants have
20934      --  been declared within. We must verify that the full declaration
20935      --  matches the incomplete one.
20936
20937      Check_Or_Process_Discriminants (N, T, Prev);
20938
20939      Set_Is_Constrained     (T, not Has_Discriminants (T));
20940      Set_Has_Delayed_Freeze (T, True);
20941
20942      --  For tagged types add a manually analyzed component corresponding
20943      --  to the component _tag, the corresponding piece of tree will be
20944      --  expanded as part of the freezing actions if it is not a CPP_Class.
20945
20946      if Is_Tagged then
20947
20948         --  Do not add the tag unless we are in expansion mode
20949
20950         if Expander_Active then
20951            Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
20952            Enter_Name (Tag_Comp);
20953
20954            Set_Ekind                     (Tag_Comp, E_Component);
20955            Set_Is_Tag                    (Tag_Comp);
20956            Set_Is_Aliased                (Tag_Comp);
20957            Set_Etype                     (Tag_Comp, RTE (RE_Tag));
20958            Set_DT_Entry_Count            (Tag_Comp, No_Uint);
20959            Set_Original_Record_Component (Tag_Comp, Tag_Comp);
20960            Init_Component_Location       (Tag_Comp);
20961
20962            --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
20963            --  implemented interfaces.
20964
20965            if Has_Interfaces (T) then
20966               Add_Interface_Tag_Components (N, T);
20967            end if;
20968         end if;
20969
20970         Make_Class_Wide_Type (T);
20971         Set_Direct_Primitive_Operations (T, New_Elmt_List);
20972      end if;
20973
20974      --  We must suppress range checks when processing record components in
20975      --  the presence of discriminants, since we don't want spurious checks to
20976      --  be generated during their analysis, but Suppress_Range_Checks flags
20977      --  must be reset the after processing the record definition.
20978
20979      --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
20980      --  couldn't we just use the normal range check suppression method here.
20981      --  That would seem cleaner ???
20982
20983      if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
20984         Set_Kill_Range_Checks (T, True);
20985         Record_Type_Definition (Def, Prev);
20986         Set_Kill_Range_Checks (T, False);
20987      else
20988         Record_Type_Definition (Def, Prev);
20989      end if;
20990
20991      --  Exit from record scope
20992
20993      End_Scope;
20994
20995      --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
20996      --  the implemented interfaces and associate them an aliased entity.
20997
20998      if Is_Tagged
20999        and then not Is_Empty_List (Interface_List (Def))
21000      then
21001         Derive_Progenitor_Subprograms (T, T);
21002      end if;
21003
21004      Check_Function_Writable_Actuals (N);
21005   end Record_Type_Declaration;
21006
21007   ----------------------------
21008   -- Record_Type_Definition --
21009   ----------------------------
21010
21011   procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
21012      Component          : Entity_Id;
21013      Ctrl_Components    : Boolean := False;
21014      Final_Storage_Only : Boolean;
21015      T                  : Entity_Id;
21016
21017   begin
21018      if Ekind (Prev_T) = E_Incomplete_Type then
21019         T := Full_View (Prev_T);
21020      else
21021         T := Prev_T;
21022      end if;
21023
21024      --  In SPARK, tagged types and type extensions may only be declared in
21025      --  the specification of library unit packages.
21026
21027      if Present (Def) and then Is_Tagged_Type (T) then
21028         declare
21029            Typ  : Node_Id;
21030            Ctxt : Node_Id;
21031
21032         begin
21033            if Nkind (Parent (Def)) = N_Full_Type_Declaration then
21034               Typ := Parent (Def);
21035            else
21036               pragma Assert
21037                 (Nkind (Parent (Def)) = N_Derived_Type_Definition);
21038               Typ := Parent (Parent (Def));
21039            end if;
21040
21041            Ctxt := Parent (Typ);
21042
21043            if Nkind (Ctxt) = N_Package_Body
21044              and then Nkind (Parent (Ctxt)) = N_Compilation_Unit
21045            then
21046               Check_SPARK_05_Restriction
21047                 ("type should be defined in package specification", Typ);
21048
21049            elsif Nkind (Ctxt) /= N_Package_Specification
21050              or else Nkind (Parent (Parent (Ctxt))) /= N_Compilation_Unit
21051            then
21052               Check_SPARK_05_Restriction
21053                 ("type should be defined in library unit package", Typ);
21054            end if;
21055         end;
21056      end if;
21057
21058      Final_Storage_Only := not Is_Controlled (T);
21059
21060      --  Ada 2005: Check whether an explicit Limited is present in a derived
21061      --  type declaration.
21062
21063      if Nkind (Parent (Def)) = N_Derived_Type_Definition
21064        and then Limited_Present (Parent (Def))
21065      then
21066         Set_Is_Limited_Record (T);
21067      end if;
21068
21069      --  If the component list of a record type is defined by the reserved
21070      --  word null and there is no discriminant part, then the record type has
21071      --  no components and all records of the type are null records (RM 3.7)
21072      --  This procedure is also called to process the extension part of a
21073      --  record extension, in which case the current scope may have inherited
21074      --  components.
21075
21076      if No (Def)
21077        or else No (Component_List (Def))
21078        or else Null_Present (Component_List (Def))
21079      then
21080         if not Is_Tagged_Type (T) then
21081            Check_SPARK_05_Restriction ("untagged record cannot be null", Def);
21082         end if;
21083
21084      else
21085         Analyze_Declarations (Component_Items (Component_List (Def)));
21086
21087         if Present (Variant_Part (Component_List (Def))) then
21088            Check_SPARK_05_Restriction ("variant part is not allowed", Def);
21089            Analyze (Variant_Part (Component_List (Def)));
21090         end if;
21091      end if;
21092
21093      --  After completing the semantic analysis of the record definition,
21094      --  record components, both new and inherited, are accessible. Set their
21095      --  kind accordingly. Exclude malformed itypes from illegal declarations,
21096      --  whose Ekind may be void.
21097
21098      Component := First_Entity (Current_Scope);
21099      while Present (Component) loop
21100         if Ekind (Component) = E_Void
21101           and then not Is_Itype (Component)
21102         then
21103            Set_Ekind (Component, E_Component);
21104            Init_Component_Location (Component);
21105         end if;
21106
21107         if Has_Task (Etype (Component)) then
21108            Set_Has_Task (T);
21109         end if;
21110
21111         if Has_Protected (Etype (Component)) then
21112            Set_Has_Protected (T);
21113         end if;
21114
21115         if Ekind (Component) /= E_Component then
21116            null;
21117
21118         --  Do not set Has_Controlled_Component on a class-wide equivalent
21119         --  type. See Make_CW_Equivalent_Type.
21120
21121         elsif not Is_Class_Wide_Equivalent_Type (T)
21122           and then (Has_Controlled_Component (Etype (Component))
21123                      or else (Chars (Component) /= Name_uParent
21124                                and then Is_Controlled (Etype (Component))))
21125         then
21126            Set_Has_Controlled_Component (T, True);
21127            Final_Storage_Only :=
21128              Final_Storage_Only
21129                and then Finalize_Storage_Only (Etype (Component));
21130            Ctrl_Components := True;
21131         end if;
21132
21133         Next_Entity (Component);
21134      end loop;
21135
21136      --  A Type is Finalize_Storage_Only only if all its controlled components
21137      --  are also.
21138
21139      if Ctrl_Components then
21140         Set_Finalize_Storage_Only (T, Final_Storage_Only);
21141      end if;
21142
21143      --  Place reference to end record on the proper entity, which may
21144      --  be a partial view.
21145
21146      if Present (Def) then
21147         Process_End_Label (Def, 'e', Prev_T);
21148      end if;
21149   end Record_Type_Definition;
21150
21151   ------------------------
21152   -- Replace_Components --
21153   ------------------------
21154
21155   procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
21156      function Process (N : Node_Id) return Traverse_Result;
21157
21158      -------------
21159      -- Process --
21160      -------------
21161
21162      function Process (N : Node_Id) return Traverse_Result is
21163         Comp : Entity_Id;
21164
21165      begin
21166         if Nkind (N) = N_Discriminant_Specification then
21167            Comp := First_Discriminant (Typ);
21168            while Present (Comp) loop
21169               if Chars (Comp) = Chars (Defining_Identifier (N)) then
21170                  Set_Defining_Identifier (N, Comp);
21171                  exit;
21172               end if;
21173
21174               Next_Discriminant (Comp);
21175            end loop;
21176
21177         elsif Nkind (N) = N_Component_Declaration then
21178            Comp := First_Component (Typ);
21179            while Present (Comp) loop
21180               if Chars (Comp) = Chars (Defining_Identifier (N)) then
21181                  Set_Defining_Identifier (N, Comp);
21182                  exit;
21183               end if;
21184
21185               Next_Component (Comp);
21186            end loop;
21187         end if;
21188
21189         return OK;
21190      end Process;
21191
21192      procedure Replace is new Traverse_Proc (Process);
21193
21194   --  Start of processing for Replace_Components
21195
21196   begin
21197      Replace (Decl);
21198   end Replace_Components;
21199
21200   -------------------------------
21201   -- Set_Completion_Referenced --
21202   -------------------------------
21203
21204   procedure Set_Completion_Referenced (E : Entity_Id) is
21205   begin
21206      --  If in main unit, mark entity that is a completion as referenced,
21207      --  warnings go on the partial view when needed.
21208
21209      if In_Extended_Main_Source_Unit (E) then
21210         Set_Referenced (E);
21211      end if;
21212   end Set_Completion_Referenced;
21213
21214   ---------------------
21215   -- Set_Default_SSO --
21216   ---------------------
21217
21218   procedure Set_Default_SSO (T : Entity_Id) is
21219   begin
21220      case Opt.Default_SSO is
21221         when ' ' =>
21222            null;
21223         when 'L' =>
21224            Set_SSO_Set_Low_By_Default (T, True);
21225         when 'H' =>
21226            Set_SSO_Set_High_By_Default (T, True);
21227         when others =>
21228            raise Program_Error;
21229      end case;
21230   end Set_Default_SSO;
21231
21232   ---------------------
21233   -- Set_Fixed_Range --
21234   ---------------------
21235
21236   --  The range for fixed-point types is complicated by the fact that we
21237   --  do not know the exact end points at the time of the declaration. This
21238   --  is true for three reasons:
21239
21240   --     A size clause may affect the fudging of the end-points.
21241   --     A small clause may affect the values of the end-points.
21242   --     We try to include the end-points if it does not affect the size.
21243
21244   --  This means that the actual end-points must be established at the
21245   --  point when the type is frozen. Meanwhile, we first narrow the range
21246   --  as permitted (so that it will fit if necessary in a small specified
21247   --  size), and then build a range subtree with these narrowed bounds.
21248   --  Set_Fixed_Range constructs the range from real literal values, and
21249   --  sets the range as the Scalar_Range of the given fixed-point type entity.
21250
21251   --  The parent of this range is set to point to the entity so that it is
21252   --  properly hooked into the tree (unlike normal Scalar_Range entries for
21253   --  other scalar types, which are just pointers to the range in the
21254   --  original tree, this would otherwise be an orphan).
21255
21256   --  The tree is left unanalyzed. When the type is frozen, the processing
21257   --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
21258   --  analyzed, and uses this as an indication that it should complete
21259   --  work on the range (it will know the final small and size values).
21260
21261   procedure Set_Fixed_Range
21262     (E   : Entity_Id;
21263      Loc : Source_Ptr;
21264      Lo  : Ureal;
21265      Hi  : Ureal)
21266   is
21267      S : constant Node_Id :=
21268            Make_Range (Loc,
21269              Low_Bound  => Make_Real_Literal (Loc, Lo),
21270              High_Bound => Make_Real_Literal (Loc, Hi));
21271   begin
21272      Set_Scalar_Range (E, S);
21273      Set_Parent (S, E);
21274
21275      --  Before the freeze point, the bounds of a fixed point are universal
21276      --  and carry the corresponding type.
21277
21278      Set_Etype (Low_Bound (S),  Universal_Real);
21279      Set_Etype (High_Bound (S), Universal_Real);
21280   end Set_Fixed_Range;
21281
21282   ----------------------------------
21283   -- Set_Scalar_Range_For_Subtype --
21284   ----------------------------------
21285
21286   procedure Set_Scalar_Range_For_Subtype
21287     (Def_Id : Entity_Id;
21288      R      : Node_Id;
21289      Subt   : Entity_Id)
21290   is
21291      Kind : constant Entity_Kind :=  Ekind (Def_Id);
21292
21293   begin
21294      --  Defend against previous error
21295
21296      if Nkind (R) = N_Error then
21297         return;
21298      end if;
21299
21300      Set_Scalar_Range (Def_Id, R);
21301
21302      --  We need to link the range into the tree before resolving it so
21303      --  that types that are referenced, including importantly the subtype
21304      --  itself, are properly frozen (Freeze_Expression requires that the
21305      --  expression be properly linked into the tree). Of course if it is
21306      --  already linked in, then we do not disturb the current link.
21307
21308      if No (Parent (R)) then
21309         Set_Parent (R, Def_Id);
21310      end if;
21311
21312      --  Reset the kind of the subtype during analysis of the range, to
21313      --  catch possible premature use in the bounds themselves.
21314
21315      Set_Ekind (Def_Id, E_Void);
21316      Process_Range_Expr_In_Decl (R, Subt, Subtyp => Def_Id);
21317      Set_Ekind (Def_Id, Kind);
21318   end Set_Scalar_Range_For_Subtype;
21319
21320   --------------------------------------------------------
21321   -- Set_Stored_Constraint_From_Discriminant_Constraint --
21322   --------------------------------------------------------
21323
21324   procedure Set_Stored_Constraint_From_Discriminant_Constraint
21325     (E : Entity_Id)
21326   is
21327   begin
21328      --  Make sure set if encountered during Expand_To_Stored_Constraint
21329
21330      Set_Stored_Constraint (E, No_Elist);
21331
21332      --  Give it the right value
21333
21334      if Is_Constrained (E) and then Has_Discriminants (E) then
21335         Set_Stored_Constraint (E,
21336           Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
21337      end if;
21338   end Set_Stored_Constraint_From_Discriminant_Constraint;
21339
21340   -------------------------------------
21341   -- Signed_Integer_Type_Declaration --
21342   -------------------------------------
21343
21344   procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
21345      Implicit_Base : Entity_Id;
21346      Base_Typ      : Entity_Id;
21347      Lo_Val        : Uint;
21348      Hi_Val        : Uint;
21349      Errs          : Boolean := False;
21350      Lo            : Node_Id;
21351      Hi            : Node_Id;
21352
21353      function Can_Derive_From (E : Entity_Id) return Boolean;
21354      --  Determine whether given bounds allow derivation from specified type
21355
21356      procedure Check_Bound (Expr : Node_Id);
21357      --  Check bound to make sure it is integral and static. If not, post
21358      --  appropriate error message and set Errs flag
21359
21360      ---------------------
21361      -- Can_Derive_From --
21362      ---------------------
21363
21364      --  Note we check both bounds against both end values, to deal with
21365      --  strange types like ones with a range of 0 .. -12341234.
21366
21367      function Can_Derive_From (E : Entity_Id) return Boolean is
21368         Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
21369         Hi : constant Uint := Expr_Value (Type_High_Bound (E));
21370      begin
21371         return Lo <= Lo_Val and then Lo_Val <= Hi
21372                  and then
21373                Lo <= Hi_Val and then Hi_Val <= Hi;
21374      end Can_Derive_From;
21375
21376      -----------------
21377      -- Check_Bound --
21378      -----------------
21379
21380      procedure Check_Bound (Expr : Node_Id) is
21381      begin
21382         --  If a range constraint is used as an integer type definition, each
21383         --  bound of the range must be defined by a static expression of some
21384         --  integer type, but the two bounds need not have the same integer
21385         --  type (Negative bounds are allowed.) (RM 3.5.4)
21386
21387         if not Is_Integer_Type (Etype (Expr)) then
21388            Error_Msg_N
21389              ("integer type definition bounds must be of integer type", Expr);
21390            Errs := True;
21391
21392         elsif not Is_OK_Static_Expression (Expr) then
21393            Flag_Non_Static_Expr
21394              ("non-static expression used for integer type bound!", Expr);
21395            Errs := True;
21396
21397         --  The bounds are folded into literals, and we set their type to be
21398         --  universal, to avoid typing difficulties: we cannot set the type
21399         --  of the literal to the new type, because this would be a forward
21400         --  reference for the back end,  and if the original type is user-
21401         --  defined this can lead to spurious semantic errors (e.g. 2928-003).
21402
21403         else
21404            if Is_Entity_Name (Expr) then
21405               Fold_Uint (Expr, Expr_Value (Expr), True);
21406            end if;
21407
21408            Set_Etype (Expr, Universal_Integer);
21409         end if;
21410      end Check_Bound;
21411
21412   --  Start of processing for Signed_Integer_Type_Declaration
21413
21414   begin
21415      --  Create an anonymous base type
21416
21417      Implicit_Base :=
21418        Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
21419
21420      --  Analyze and check the bounds, they can be of any integer type
21421
21422      Lo := Low_Bound (Def);
21423      Hi := High_Bound (Def);
21424
21425      --  Arbitrarily use Integer as the type if either bound had an error
21426
21427      if Hi = Error or else Lo = Error then
21428         Base_Typ := Any_Integer;
21429         Set_Error_Posted (T, True);
21430
21431      --  Here both bounds are OK expressions
21432
21433      else
21434         Analyze_And_Resolve (Lo, Any_Integer);
21435         Analyze_And_Resolve (Hi, Any_Integer);
21436
21437         Check_Bound (Lo);
21438         Check_Bound (Hi);
21439
21440         if Errs then
21441            Hi := Type_High_Bound (Standard_Long_Long_Integer);
21442            Lo := Type_Low_Bound (Standard_Long_Long_Integer);
21443         end if;
21444
21445         --  Find type to derive from
21446
21447         Lo_Val := Expr_Value (Lo);
21448         Hi_Val := Expr_Value (Hi);
21449
21450         if Can_Derive_From (Standard_Short_Short_Integer) then
21451            Base_Typ := Base_Type (Standard_Short_Short_Integer);
21452
21453         elsif Can_Derive_From (Standard_Short_Integer) then
21454            Base_Typ := Base_Type (Standard_Short_Integer);
21455
21456         elsif Can_Derive_From (Standard_Integer) then
21457            Base_Typ := Base_Type (Standard_Integer);
21458
21459         elsif Can_Derive_From (Standard_Long_Integer) then
21460            Base_Typ := Base_Type (Standard_Long_Integer);
21461
21462         elsif Can_Derive_From (Standard_Long_Long_Integer) then
21463            Check_Restriction (No_Long_Long_Integers, Def);
21464            Base_Typ := Base_Type (Standard_Long_Long_Integer);
21465
21466         else
21467            Base_Typ := Base_Type (Standard_Long_Long_Integer);
21468            Error_Msg_N ("integer type definition bounds out of range", Def);
21469            Hi := Type_High_Bound (Standard_Long_Long_Integer);
21470            Lo := Type_Low_Bound (Standard_Long_Long_Integer);
21471         end if;
21472      end if;
21473
21474      --  Complete both implicit base and declared first subtype entities. The
21475      --  inheritance of the rep item chain ensures that SPARK-related pragmas
21476      --  are not clobbered when the signed integer type acts as a full view of
21477      --  a private type.
21478
21479      Set_Etype          (Implicit_Base,                 Base_Typ);
21480      Set_Size_Info      (Implicit_Base,                 Base_Typ);
21481      Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
21482      Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
21483      Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
21484
21485      Set_Ekind              (T, E_Signed_Integer_Subtype);
21486      Set_Etype              (T, Implicit_Base);
21487      Set_Size_Info          (T, Implicit_Base);
21488      Inherit_Rep_Item_Chain (T, Implicit_Base);
21489      Set_Scalar_Range       (T, Def);
21490      Set_RM_Size            (T, UI_From_Int (Minimum_Size (T)));
21491      Set_Is_Constrained     (T);
21492   end Signed_Integer_Type_Declaration;
21493
21494end Sem_Ch3;
21495