sem_aggr.adb (Aggregate_Constraint_Checks): Moved to sem_util.
[platform/upstream/gcc.git] / gcc / ada / sem_aggr.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ A G G R                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2014, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Expander; use Expander;
32 with Exp_Tss;  use Exp_Tss;
33 with Exp_Util; use Exp_Util;
34 with Freeze;   use Freeze;
35 with Itypes;   use Itypes;
36 with Lib;      use Lib;
37 with Lib.Xref; use Lib.Xref;
38 with Namet;    use Namet;
39 with Namet.Sp; use Namet.Sp;
40 with Nmake;    use Nmake;
41 with Nlists;   use Nlists;
42 with Opt;      use Opt;
43 with Restrict; use Restrict;
44 with Sem;      use Sem;
45 with Sem_Aux;  use Sem_Aux;
46 with Sem_Cat;  use Sem_Cat;
47 with Sem_Ch3;  use Sem_Ch3;
48 with Sem_Ch8;  use Sem_Ch8;
49 with Sem_Ch13; use Sem_Ch13;
50 with Sem_Dim;  use Sem_Dim;
51 with Sem_Eval; use Sem_Eval;
52 with Sem_Res;  use Sem_Res;
53 with Sem_Util; use Sem_Util;
54 with Sem_Type; use Sem_Type;
55 with Sem_Warn; use Sem_Warn;
56 with Sinfo;    use Sinfo;
57 with Snames;   use Snames;
58 with Stringt;  use Stringt;
59 with Stand;    use Stand;
60 with Style;    use Style;
61 with Targparm; use Targparm;
62 with Tbuild;   use Tbuild;
63 with Uintp;    use Uintp;
64
65 package body Sem_Aggr is
66
67    type Case_Bounds is record
68       Lo : Node_Id;
69       --  Low bound of choice. Once we sort the Case_Table, then entries
70       --  will be in order of ascending Choice_Lo values.
71
72       Hi : Node_Id;
73       --  High Bound of choice. The sort does not pay any attention to the
74       --  high bound, so choices 1 .. 4 and 1 .. 5 could be in either order.
75
76       Highest : Uint;
77       --  If there are duplicates or missing entries, then in the sorted
78       --  table, this records the highest value among Choice_Hi values
79       --  seen so far, including this entry.
80
81       Choice : Node_Id;
82       --  The node of the choice
83    end record;
84
85    type Case_Table_Type is array (Nat range <>) of Case_Bounds;
86    --  Table type used by Check_Case_Choices procedure. Entry zero is not
87    --  used (reserved for the sort). Real entries start at one.
88
89    -----------------------
90    -- Local Subprograms --
91    -----------------------
92
93    procedure Sort_Case_Table (Case_Table : in out Case_Table_Type);
94    --  Sort the Case Table using the Lower Bound of each Choice as the key. A
95    --  simple insertion sort is used since the choices in a case statement will
96    --  usually be in near sorted order.
97
98    procedure Check_Can_Never_Be_Null (Typ : Entity_Id; Expr : Node_Id);
99    --  Ada 2005 (AI-231): Check bad usage of null for a component for which
100    --  null exclusion (NOT NULL) is specified. Typ can be an E_Array_Type for
101    --  the array case (the component type of the array will be used) or an
102    --  E_Component/E_Discriminant entity in the record case, in which case the
103    --  type of the component will be used for the test. If Typ is any other
104    --  kind of entity, the call is ignored. Expr is the component node in the
105    --  aggregate which is known to have a null value. A warning message will be
106    --  issued if the component is null excluding.
107    --
108    --  It would be better to pass the proper type for Typ ???
109
110    procedure Check_Expr_OK_In_Limited_Aggregate (Expr : Node_Id);
111    --  Check that Expr is either not limited or else is one of the cases of
112    --  expressions allowed for a limited component association (namely, an
113    --  aggregate, function call, or <> notation). Report error for violations.
114
115    procedure Check_Qualified_Aggregate (Level : Nat; Expr : Node_Id);
116    --  Given aggregate Expr, check that sub-aggregates of Expr that are nested
117    --  at Level are qualified. If Level = 0, this applies to Expr directly.
118    --  Only issue errors in formal verification mode.
119
120    function Is_Top_Level_Aggregate (Expr : Node_Id) return Boolean;
121    --  Return True of Expr is an aggregate not contained directly in another
122    --  aggregate.
123
124    ------------------------------------------------------
125    -- Subprograms used for RECORD AGGREGATE Processing --
126    ------------------------------------------------------
127
128    procedure Resolve_Record_Aggregate (N : Node_Id; Typ : Entity_Id);
129    --  This procedure performs all the semantic checks required for record
130    --  aggregates. Note that for aggregates analysis and resolution go
131    --  hand in hand. Aggregate analysis has been delayed up to here and
132    --  it is done while resolving the aggregate.
133    --
134    --    N is the N_Aggregate node.
135    --    Typ is the record type for the aggregate resolution
136    --
137    --  While performing the semantic checks, this procedure builds a new
138    --  Component_Association_List where each record field appears alone in a
139    --  Component_Choice_List along with its corresponding expression. The
140    --  record fields in the Component_Association_List appear in the same order
141    --  in which they appear in the record type Typ.
142    --
143    --  Once this new Component_Association_List is built and all the semantic
144    --  checks performed, the original aggregate subtree is replaced with the
145    --  new named record aggregate just built. Note that subtree substitution is
146    --  performed with Rewrite so as to be able to retrieve the original
147    --  aggregate.
148    --
149    --  The aggregate subtree manipulation performed by Resolve_Record_Aggregate
150    --  yields the aggregate format expected by Gigi. Typically, this kind of
151    --  tree manipulations are done in the expander. However, because the
152    --  semantic checks that need to be performed on record aggregates really go
153    --  hand in hand with the record aggregate normalization, the aggregate
154    --  subtree transformation is performed during resolution rather than
155    --  expansion. Had we decided otherwise we would have had to duplicate most
156    --  of the code in the expansion procedure Expand_Record_Aggregate. Note,
157    --  however, that all the expansion concerning aggregates for tagged records
158    --  is done in Expand_Record_Aggregate.
159    --
160    --  The algorithm of Resolve_Record_Aggregate proceeds as follows:
161    --
162    --  1. Make sure that the record type against which the record aggregate
163    --     has to be resolved is not abstract. Furthermore if the type is a
164    --     null aggregate make sure the input aggregate N is also null.
165    --
166    --  2. Verify that the structure of the aggregate is that of a record
167    --     aggregate. Specifically, look for component associations and ensure
168    --     that each choice list only has identifiers or the N_Others_Choice
169    --     node. Also make sure that if present, the N_Others_Choice occurs
170    --     last and by itself.
171    --
172    --  3. If Typ contains discriminants, the values for each discriminant is
173    --     looked for. If the record type Typ has variants, we check that the
174    --     expressions corresponding to each discriminant ruling the (possibly
175    --     nested) variant parts of Typ, are static. This allows us to determine
176    --     the variant parts to which the rest of the aggregate must conform.
177    --     The names of discriminants with their values are saved in a new
178    --     association list, New_Assoc_List which is later augmented with the
179    --     names and values of the remaining components in the record type.
180    --
181    --     During this phase we also make sure that every discriminant is
182    --     assigned exactly one value. Note that when several values for a given
183    --     discriminant are found, semantic processing continues looking for
184    --     further errors. In this case it's the first discriminant value found
185    --     which we will be recorded.
186    --
187    --     IMPORTANT NOTE: For derived tagged types this procedure expects
188    --     First_Discriminant and Next_Discriminant to give the correct list
189    --     of discriminants, in the correct order.
190    --
191    --  4. After all the discriminant values have been gathered, we can set the
192    --     Etype of the record aggregate. If Typ contains no discriminants this
193    --     is straightforward: the Etype of N is just Typ, otherwise a new
194    --     implicit constrained subtype of Typ is built to be the Etype of N.
195    --
196    --  5. Gather the remaining record components according to the discriminant
197    --     values. This involves recursively traversing the record type
198    --     structure to see what variants are selected by the given discriminant
199    --     values. This processing is a little more convoluted if Typ is a
200    --     derived tagged types since we need to retrieve the record structure
201    --     of all the ancestors of Typ.
202    --
203    --  6. After gathering the record components we look for their values in the
204    --     record aggregate and emit appropriate error messages should we not
205    --     find such values or should they be duplicated.
206    --
207    --  7. We then make sure no illegal component names appear in the record
208    --     aggregate and make sure that the type of the record components
209    --     appearing in a same choice list is the same. Finally we ensure that
210    --     the others choice, if present, is used to provide the value of at
211    --     least a record component.
212    --
213    --  8. The original aggregate node is replaced with the new named aggregate
214    --     built in steps 3 through 6, as explained earlier.
215    --
216    --  Given the complexity of record aggregate resolution, the primary goal of
217    --  this routine is clarity and simplicity rather than execution and storage
218    --  efficiency. If there are only positional components in the aggregate the
219    --  running time is linear. If there are associations the running time is
220    --  still linear as long as the order of the associations is not too far off
221    --  the order of the components in the record type. If this is not the case
222    --  the running time is at worst quadratic in the size of the association
223    --  list.
224
225    procedure Check_Misspelled_Component
226      (Elements  : Elist_Id;
227       Component : Node_Id);
228    --  Give possible misspelling diagnostic if Component is likely to be a
229    --  misspelling of one of the components of the Assoc_List. This is called
230    --  by Resolve_Aggr_Expr after producing an invalid component error message.
231
232    procedure Check_Static_Discriminated_Subtype (T : Entity_Id; V : Node_Id);
233    --  An optimization: determine whether a discriminated subtype has a static
234    --  constraint, and contains array components whose length is also static,
235    --  either because they are constrained by the discriminant, or because the
236    --  original component bounds are static.
237
238    -----------------------------------------------------
239    -- Subprograms used for ARRAY AGGREGATE Processing --
240    -----------------------------------------------------
241
242    function Resolve_Array_Aggregate
243      (N              : Node_Id;
244       Index          : Node_Id;
245       Index_Constr   : Node_Id;
246       Component_Typ  : Entity_Id;
247       Others_Allowed : Boolean) return Boolean;
248    --  This procedure performs the semantic checks for an array aggregate.
249    --  True is returned if the aggregate resolution succeeds.
250    --
251    --  The procedure works by recursively checking each nested aggregate.
252    --  Specifically, after checking a sub-aggregate nested at the i-th level
253    --  we recursively check all the subaggregates at the i+1-st level (if any).
254    --  Note that for aggregates analysis and resolution go hand in hand.
255    --  Aggregate analysis has been delayed up to here and it is done while
256    --  resolving the aggregate.
257    --
258    --    N is the current N_Aggregate node to be checked.
259    --
260    --    Index is the index node corresponding to the array sub-aggregate that
261    --    we are currently checking (RM 4.3.3 (8)). Its Etype is the
262    --    corresponding index type (or subtype).
263    --
264    --    Index_Constr is the node giving the applicable index constraint if
265    --    any (RM 4.3.3 (10)). It "is a constraint provided by certain
266    --    contexts [...] that can be used to determine the bounds of the array
267    --    value specified by the aggregate". If Others_Allowed below is False
268    --    there is no applicable index constraint and this node is set to Index.
269    --
270    --    Component_Typ is the array component type.
271    --
272    --    Others_Allowed indicates whether an others choice is allowed
273    --    in the context where the top-level aggregate appeared.
274    --
275    --  The algorithm of Resolve_Array_Aggregate proceeds as follows:
276    --
277    --  1. Make sure that the others choice, if present, is by itself and
278    --     appears last in the sub-aggregate. Check that we do not have
279    --     positional and named components in the array sub-aggregate (unless
280    --     the named association is an others choice). Finally if an others
281    --     choice is present, make sure it is allowed in the aggregate context.
282    --
283    --  2. If the array sub-aggregate contains discrete_choices:
284    --
285    --     (A) Verify their validity. Specifically verify that:
286    --
287    --        (a) If a null range is present it must be the only possible
288    --            choice in the array aggregate.
289    --
290    --        (b) Ditto for a non static range.
291    --
292    --        (c) Ditto for a non static expression.
293    --
294    --        In addition this step analyzes and resolves each discrete_choice,
295    --        making sure that its type is the type of the corresponding Index.
296    --        If we are not at the lowest array aggregate level (in the case of
297    --        multi-dimensional aggregates) then invoke Resolve_Array_Aggregate
298    --        recursively on each component expression. Otherwise, resolve the
299    --        bottom level component expressions against the expected component
300    --        type ONLY IF the component corresponds to a single discrete choice
301    --        which is not an others choice (to see why read the DELAYED
302    --        COMPONENT RESOLUTION below).
303    --
304    --     (B) Determine the bounds of the sub-aggregate and lowest and
305    --         highest choice values.
306    --
307    --  3. For positional aggregates:
308    --
309    --     (A) Loop over the component expressions either recursively invoking
310    --         Resolve_Array_Aggregate on each of these for multi-dimensional
311    --         array aggregates or resolving the bottom level component
312    --         expressions against the expected component type.
313    --
314    --     (B) Determine the bounds of the positional sub-aggregates.
315    --
316    --  4. Try to determine statically whether the evaluation of the array
317    --     sub-aggregate raises Constraint_Error. If yes emit proper
318    --     warnings. The precise checks are the following:
319    --
320    --     (A) Check that the index range defined by aggregate bounds is
321    --         compatible with corresponding index subtype.
322    --         We also check against the base type. In fact it could be that
323    --         Low/High bounds of the base type are static whereas those of
324    --         the index subtype are not. Thus if we can statically catch
325    --         a problem with respect to the base type we are guaranteed
326    --         that the same problem will arise with the index subtype
327    --
328    --     (B) If we are dealing with a named aggregate containing an others
329    --         choice and at least one discrete choice then make sure the range
330    --         specified by the discrete choices does not overflow the
331    --         aggregate bounds. We also check against the index type and base
332    --         type bounds for the same reasons given in (A).
333    --
334    --     (C) If we are dealing with a positional aggregate with an others
335    --         choice make sure the number of positional elements specified
336    --         does not overflow the aggregate bounds. We also check against
337    --         the index type and base type bounds as mentioned in (A).
338    --
339    --     Finally construct an N_Range node giving the sub-aggregate bounds.
340    --     Set the Aggregate_Bounds field of the sub-aggregate to be this
341    --     N_Range. The routine Array_Aggr_Subtype below uses such N_Ranges
342    --     to build the appropriate aggregate subtype. Aggregate_Bounds
343    --     information is needed during expansion.
344    --
345    --  DELAYED COMPONENT RESOLUTION: The resolution of bottom level component
346    --  expressions in an array aggregate may call Duplicate_Subexpr or some
347    --  other routine that inserts code just outside the outermost aggregate.
348    --  If the array aggregate contains discrete choices or an others choice,
349    --  this may be wrong. Consider for instance the following example.
350    --
351    --    type Rec is record
352    --       V : Integer := 0;
353    --    end record;
354    --
355    --    type Acc_Rec is access Rec;
356    --    Arr : array (1..3) of Acc_Rec := (1 .. 3 => new Rec);
357    --
358    --  Then the transformation of "new Rec" that occurs during resolution
359    --  entails the following code modifications
360    --
361    --    P7b : constant Acc_Rec := new Rec;
362    --    RecIP (P7b.all);
363    --    Arr : array (1..3) of Acc_Rec := (1 .. 3 => P7b);
364    --
365    --  This code transformation is clearly wrong, since we need to call
366    --  "new Rec" for each of the 3 array elements. To avoid this problem we
367    --  delay resolution of the components of non positional array aggregates
368    --  to the expansion phase. As an optimization, if the discrete choice
369    --  specifies a single value we do not delay resolution.
370
371    function Array_Aggr_Subtype (N : Node_Id; Typ : Node_Id) return Entity_Id;
372    --  This routine returns the type or subtype of an array aggregate.
373    --
374    --    N is the array aggregate node whose type we return.
375    --
376    --    Typ is the context type in which N occurs.
377    --
378    --  This routine creates an implicit array subtype whose bounds are
379    --  those defined by the aggregate. When this routine is invoked
380    --  Resolve_Array_Aggregate has already processed aggregate N. Thus the
381    --  Aggregate_Bounds of each sub-aggregate, is an N_Range node giving the
382    --  sub-aggregate bounds. When building the aggregate itype, this function
383    --  traverses the array aggregate N collecting such Aggregate_Bounds and
384    --  constructs the proper array aggregate itype.
385    --
386    --  Note that in the case of multidimensional aggregates each inner
387    --  sub-aggregate corresponding to a given array dimension, may provide a
388    --  different bounds. If it is possible to determine statically that
389    --  some sub-aggregates corresponding to the same index do not have the
390    --  same bounds, then a warning is emitted. If such check is not possible
391    --  statically (because some sub-aggregate bounds are dynamic expressions)
392    --  then this job is left to the expander. In all cases the particular
393    --  bounds that this function will chose for a given dimension is the first
394    --  N_Range node for a sub-aggregate corresponding to that dimension.
395    --
396    --  Note that the Raises_Constraint_Error flag of an array aggregate
397    --  whose evaluation is determined to raise CE by Resolve_Array_Aggregate,
398    --  is set in Resolve_Array_Aggregate but the aggregate is not
399    --  immediately replaced with a raise CE. In fact, Array_Aggr_Subtype must
400    --  first construct the proper itype for the aggregate (Gigi needs
401    --  this). After constructing the proper itype we will eventually  replace
402    --  the top-level aggregate with a raise CE (done in Resolve_Aggregate).
403    --  Of course in cases such as:
404    --
405    --     type Arr is array (integer range <>) of Integer;
406    --     A : Arr := (positive range -1 .. 2 => 0);
407    --
408    --  The bounds of the aggregate itype are cooked up to look reasonable
409    --  (in this particular case the bounds will be 1 .. 2).
410
411    procedure Make_String_Into_Aggregate (N : Node_Id);
412    --  A string literal can appear in  a context in  which a one dimensional
413    --  array of characters is expected. This procedure simply rewrites the
414    --  string as an aggregate, prior to resolution.
415
416    ------------------------
417    -- Array_Aggr_Subtype --
418    ------------------------
419
420    function Array_Aggr_Subtype
421      (N   : Node_Id;
422       Typ : Entity_Id) return Entity_Id
423    is
424       Aggr_Dimension : constant Pos := Number_Dimensions (Typ);
425       --  Number of aggregate index dimensions
426
427       Aggr_Range : array (1 .. Aggr_Dimension) of Node_Id := (others => Empty);
428       --  Constrained N_Range of each index dimension in our aggregate itype
429
430       Aggr_Low   : array (1 .. Aggr_Dimension) of Node_Id := (others => Empty);
431       Aggr_High  : array (1 .. Aggr_Dimension) of Node_Id := (others => Empty);
432       --  Low and High bounds for each index dimension in our aggregate itype
433
434       Is_Fully_Positional : Boolean := True;
435
436       procedure Collect_Aggr_Bounds (N : Node_Id; Dim : Pos);
437       --  N is an array (sub-)aggregate. Dim is the dimension corresponding
438       --  to (sub-)aggregate N. This procedure collects and removes the side
439       --  effects of the constrained N_Range nodes corresponding to each index
440       --  dimension of our aggregate itype. These N_Range nodes are collected
441       --  in Aggr_Range above.
442       --
443       --  Likewise collect in Aggr_Low & Aggr_High above the low and high
444       --  bounds of each index dimension. If, when collecting, two bounds
445       --  corresponding to the same dimension are static and found to differ,
446       --  then emit a warning, and mark N as raising Constraint_Error.
447
448       -------------------------
449       -- Collect_Aggr_Bounds --
450       -------------------------
451
452       procedure Collect_Aggr_Bounds (N : Node_Id; Dim : Pos) is
453          This_Range : constant Node_Id := Aggregate_Bounds (N);
454          --  The aggregate range node of this specific sub-aggregate
455
456          This_Low  : constant Node_Id := Low_Bound (Aggregate_Bounds (N));
457          This_High : constant Node_Id := High_Bound (Aggregate_Bounds (N));
458          --  The aggregate bounds of this specific sub-aggregate
459
460          Assoc : Node_Id;
461          Expr  : Node_Id;
462
463       begin
464          Remove_Side_Effects (This_Low,  Variable_Ref => True);
465          Remove_Side_Effects (This_High, Variable_Ref => True);
466
467          --  Collect the first N_Range for a given dimension that you find.
468          --  For a given dimension they must be all equal anyway.
469
470          if No (Aggr_Range (Dim)) then
471             Aggr_Low (Dim)   := This_Low;
472             Aggr_High (Dim)  := This_High;
473             Aggr_Range (Dim) := This_Range;
474
475          else
476             if Compile_Time_Known_Value (This_Low) then
477                if not Compile_Time_Known_Value (Aggr_Low (Dim)) then
478                   Aggr_Low (Dim)  := This_Low;
479
480                elsif Expr_Value (This_Low) /= Expr_Value (Aggr_Low (Dim)) then
481                   Set_Raises_Constraint_Error (N);
482                   Error_Msg_Warn := SPARK_Mode /= On;
483                   Error_Msg_N ("sub-aggregate low bound mismatch<<", N);
484                   Error_Msg_N ("\Constraint_Error [<<", N);
485                end if;
486             end if;
487
488             if Compile_Time_Known_Value (This_High) then
489                if not Compile_Time_Known_Value (Aggr_High (Dim)) then
490                   Aggr_High (Dim)  := This_High;
491
492                elsif
493                  Expr_Value (This_High) /= Expr_Value (Aggr_High (Dim))
494                then
495                   Set_Raises_Constraint_Error (N);
496                   Error_Msg_Warn := SPARK_Mode /= On;
497                   Error_Msg_N ("sub-aggregate high bound mismatch<<", N);
498                   Error_Msg_N ("\Constraint_Error [<<", N);
499                end if;
500             end if;
501          end if;
502
503          if Dim < Aggr_Dimension then
504
505             --  Process positional components
506
507             if Present (Expressions (N)) then
508                Expr := First (Expressions (N));
509                while Present (Expr) loop
510                   Collect_Aggr_Bounds (Expr, Dim + 1);
511                   Next (Expr);
512                end loop;
513             end if;
514
515             --  Process component associations
516
517             if Present (Component_Associations (N)) then
518                Is_Fully_Positional := False;
519
520                Assoc := First (Component_Associations (N));
521                while Present (Assoc) loop
522                   Expr := Expression (Assoc);
523                   Collect_Aggr_Bounds (Expr, Dim + 1);
524                   Next (Assoc);
525                end loop;
526             end if;
527          end if;
528       end Collect_Aggr_Bounds;
529
530       --  Array_Aggr_Subtype variables
531
532       Itype : Entity_Id;
533       --  The final itype of the overall aggregate
534
535       Index_Constraints : constant List_Id := New_List;
536       --  The list of index constraints of the aggregate itype
537
538    --  Start of processing for Array_Aggr_Subtype
539
540    begin
541       --  Make sure that the list of index constraints is properly attached to
542       --  the tree, and then collect the aggregate bounds.
543
544       Set_Parent (Index_Constraints, N);
545       Collect_Aggr_Bounds (N, 1);
546
547       --  Build the list of constrained indexes of our aggregate itype
548
549       for J in 1 .. Aggr_Dimension loop
550          Create_Index : declare
551             Index_Base : constant Entity_Id :=
552                            Base_Type (Etype (Aggr_Range (J)));
553             Index_Typ  : Entity_Id;
554
555          begin
556             --  Construct the Index subtype, and associate it with the range
557             --  construct that generates it.
558
559             Index_Typ :=
560               Create_Itype (Subtype_Kind (Ekind (Index_Base)), Aggr_Range (J));
561
562             Set_Etype (Index_Typ, Index_Base);
563
564             if Is_Character_Type (Index_Base) then
565                Set_Is_Character_Type (Index_Typ);
566             end if;
567
568             Set_Size_Info      (Index_Typ,                (Index_Base));
569             Set_RM_Size        (Index_Typ, RM_Size        (Index_Base));
570             Set_First_Rep_Item (Index_Typ, First_Rep_Item (Index_Base));
571             Set_Scalar_Range   (Index_Typ, Aggr_Range (J));
572
573             if Is_Discrete_Or_Fixed_Point_Type (Index_Typ) then
574                Set_RM_Size (Index_Typ, UI_From_Int (Minimum_Size (Index_Typ)));
575             end if;
576
577             Set_Etype (Aggr_Range (J), Index_Typ);
578
579             Append (Aggr_Range (J), To => Index_Constraints);
580          end Create_Index;
581       end loop;
582
583       --  Now build the Itype
584
585       Itype := Create_Itype (E_Array_Subtype, N);
586
587       Set_First_Rep_Item         (Itype, First_Rep_Item        (Typ));
588       Set_Convention             (Itype, Convention            (Typ));
589       Set_Depends_On_Private     (Itype, Has_Private_Component (Typ));
590       Set_Etype                  (Itype, Base_Type             (Typ));
591       Set_Has_Alignment_Clause   (Itype, Has_Alignment_Clause  (Typ));
592       Set_Is_Aliased             (Itype, Is_Aliased            (Typ));
593       Set_Depends_On_Private     (Itype, Depends_On_Private    (Typ));
594
595       Copy_Suppress_Status (Index_Check,  Typ, Itype);
596       Copy_Suppress_Status (Length_Check, Typ, Itype);
597
598       Set_First_Index    (Itype, First (Index_Constraints));
599       Set_Is_Constrained (Itype, True);
600       Set_Is_Internal    (Itype, True);
601
602       --  A simple optimization: purely positional aggregates of static
603       --  components should be passed to gigi unexpanded whenever possible, and
604       --  regardless of the staticness of the bounds themselves. Subsequent
605       --  checks in exp_aggr verify that type is not packed, etc.
606
607       Set_Size_Known_At_Compile_Time (Itype,
608          Is_Fully_Positional
609            and then Comes_From_Source (N)
610            and then Size_Known_At_Compile_Time (Component_Type (Typ)));
611
612       --  We always need a freeze node for a packed array subtype, so that we
613       --  can build the Packed_Array_Type corresponding to the subtype. If
614       --  expansion is disabled, the packed array subtype is not built, and we
615       --  must not generate a freeze node for the type, or else it will appear
616       --  incomplete to gigi.
617
618       if Is_Packed (Itype)
619         and then not In_Spec_Expression
620         and then Expander_Active
621       then
622          Freeze_Itype (Itype, N);
623       end if;
624
625       return Itype;
626    end Array_Aggr_Subtype;
627
628    --------------------------------
629    -- Check_Misspelled_Component --
630    --------------------------------
631
632    procedure Check_Misspelled_Component
633      (Elements  : Elist_Id;
634       Component : Node_Id)
635    is
636       Max_Suggestions   : constant := 2;
637
638       Nr_Of_Suggestions : Natural := 0;
639       Suggestion_1      : Entity_Id := Empty;
640       Suggestion_2      : Entity_Id := Empty;
641       Component_Elmt    : Elmt_Id;
642
643    begin
644       --  All the components of List are matched against Component and a count
645       --  is maintained of possible misspellings. When at the end of the the
646       --  analysis there are one or two (not more) possible misspellings,
647       --  these misspellings will be suggested as possible correction.
648
649       Component_Elmt := First_Elmt (Elements);
650       while Nr_Of_Suggestions <= Max_Suggestions
651         and then Present (Component_Elmt)
652       loop
653          if Is_Bad_Spelling_Of
654               (Chars (Node (Component_Elmt)),
655                Chars (Component))
656          then
657             Nr_Of_Suggestions := Nr_Of_Suggestions + 1;
658
659             case Nr_Of_Suggestions is
660                when 1      => Suggestion_1 := Node (Component_Elmt);
661                when 2      => Suggestion_2 := Node (Component_Elmt);
662                when others => exit;
663             end case;
664          end if;
665
666          Next_Elmt (Component_Elmt);
667       end loop;
668
669       --  Report at most two suggestions
670
671       if Nr_Of_Suggestions = 1 then
672          Error_Msg_NE -- CODEFIX
673            ("\possible misspelling of&", Component, Suggestion_1);
674
675       elsif Nr_Of_Suggestions = 2 then
676          Error_Msg_Node_2 := Suggestion_2;
677          Error_Msg_NE -- CODEFIX
678            ("\possible misspelling of& or&", Component, Suggestion_1);
679       end if;
680    end Check_Misspelled_Component;
681
682    ----------------------------------------
683    -- Check_Expr_OK_In_Limited_Aggregate --
684    ----------------------------------------
685
686    procedure Check_Expr_OK_In_Limited_Aggregate (Expr : Node_Id) is
687    begin
688       if Is_Limited_Type (Etype (Expr))
689          and then Comes_From_Source (Expr)
690          and then not In_Instance_Body
691       then
692          if not OK_For_Limited_Init (Etype (Expr), Expr) then
693             Error_Msg_N ("initialization not allowed for limited types", Expr);
694             Explain_Limited_Type (Etype (Expr), Expr);
695          end if;
696       end if;
697    end Check_Expr_OK_In_Limited_Aggregate;
698
699    -------------------------------
700    -- Check_Qualified_Aggregate --
701    -------------------------------
702
703    procedure Check_Qualified_Aggregate (Level : Nat; Expr : Node_Id) is
704       Comp_Expr : Node_Id;
705       Comp_Assn : Node_Id;
706
707    begin
708       if Level = 0 then
709          if Nkind (Parent (Expr)) /= N_Qualified_Expression then
710             Check_SPARK_Restriction ("aggregate should be qualified", Expr);
711          end if;
712
713       else
714          Comp_Expr := First (Expressions (Expr));
715          while Present (Comp_Expr) loop
716             if Nkind (Comp_Expr) = N_Aggregate then
717                Check_Qualified_Aggregate (Level - 1, Comp_Expr);
718             end if;
719
720             Comp_Expr := Next (Comp_Expr);
721          end loop;
722
723          Comp_Assn := First (Component_Associations (Expr));
724          while Present (Comp_Assn) loop
725             Comp_Expr := Expression (Comp_Assn);
726
727             if Nkind (Comp_Expr) = N_Aggregate then
728                Check_Qualified_Aggregate (Level - 1, Comp_Expr);
729             end if;
730
731             Comp_Assn := Next (Comp_Assn);
732          end loop;
733       end if;
734    end Check_Qualified_Aggregate;
735
736    ----------------------------------------
737    -- Check_Static_Discriminated_Subtype --
738    ----------------------------------------
739
740    procedure Check_Static_Discriminated_Subtype (T : Entity_Id; V : Node_Id) is
741       Disc : constant Entity_Id := First_Discriminant (T);
742       Comp : Entity_Id;
743       Ind  : Entity_Id;
744
745    begin
746       if Has_Record_Rep_Clause (T) then
747          return;
748
749       elsif Present (Next_Discriminant (Disc)) then
750          return;
751
752       elsif Nkind (V) /= N_Integer_Literal then
753          return;
754       end if;
755
756       Comp := First_Component (T);
757       while Present (Comp) loop
758          if Is_Scalar_Type (Etype (Comp)) then
759             null;
760
761          elsif Is_Private_Type (Etype (Comp))
762            and then Present (Full_View (Etype (Comp)))
763            and then Is_Scalar_Type (Full_View (Etype (Comp)))
764          then
765             null;
766
767          elsif Is_Array_Type (Etype (Comp)) then
768             if Is_Bit_Packed_Array (Etype (Comp)) then
769                return;
770             end if;
771
772             Ind := First_Index (Etype (Comp));
773             while Present (Ind) loop
774                if Nkind (Ind) /= N_Range
775                  or else Nkind (Low_Bound (Ind)) /= N_Integer_Literal
776                  or else Nkind (High_Bound (Ind)) /= N_Integer_Literal
777                then
778                   return;
779                end if;
780
781                Next_Index (Ind);
782             end loop;
783
784          else
785             return;
786          end if;
787
788          Next_Component (Comp);
789       end loop;
790
791       --  On exit, all components have statically known sizes
792
793       Set_Size_Known_At_Compile_Time (T);
794    end Check_Static_Discriminated_Subtype;
795
796    -------------------------
797    -- Is_Others_Aggregate --
798    -------------------------
799
800    function Is_Others_Aggregate (Aggr : Node_Id) return Boolean is
801    begin
802       return No (Expressions (Aggr))
803         and then
804           Nkind (First (Choices (First (Component_Associations (Aggr)))))
805             = N_Others_Choice;
806    end Is_Others_Aggregate;
807
808    ----------------------------
809    -- Is_Top_Level_Aggregate --
810    ----------------------------
811
812    function Is_Top_Level_Aggregate (Expr : Node_Id) return Boolean is
813    begin
814       return Nkind (Parent (Expr)) /= N_Aggregate
815         and then (Nkind (Parent (Expr)) /= N_Component_Association
816                    or else Nkind (Parent (Parent (Expr))) /= N_Aggregate);
817    end Is_Top_Level_Aggregate;
818
819    --------------------------------
820    -- Make_String_Into_Aggregate --
821    --------------------------------
822
823    procedure Make_String_Into_Aggregate (N : Node_Id) is
824       Exprs  : constant List_Id    := New_List;
825       Loc    : constant Source_Ptr := Sloc (N);
826       Str    : constant String_Id  := Strval (N);
827       Strlen : constant Nat        := String_Length (Str);
828       C      : Char_Code;
829       C_Node : Node_Id;
830       New_N  : Node_Id;
831       P      : Source_Ptr;
832
833    begin
834       P := Loc + 1;
835       for J in  1 .. Strlen loop
836          C := Get_String_Char (Str, J);
837          Set_Character_Literal_Name (C);
838
839          C_Node :=
840            Make_Character_Literal (P,
841              Chars              => Name_Find,
842              Char_Literal_Value => UI_From_CC (C));
843          Set_Etype (C_Node, Any_Character);
844          Append_To (Exprs, C_Node);
845
846          P := P + 1;
847          --  Something special for wide strings???
848       end loop;
849
850       New_N := Make_Aggregate (Loc, Expressions => Exprs);
851       Set_Analyzed (New_N);
852       Set_Etype (New_N, Any_Composite);
853
854       Rewrite (N, New_N);
855    end Make_String_Into_Aggregate;
856
857    -----------------------
858    -- Resolve_Aggregate --
859    -----------------------
860
861    procedure Resolve_Aggregate (N : Node_Id; Typ : Entity_Id) is
862       Loc   : constant Source_Ptr := Sloc (N);
863       Pkind : constant Node_Kind  := Nkind (Parent (N));
864
865       Aggr_Subtyp : Entity_Id;
866       --  The actual aggregate subtype. This is not necessarily the same as Typ
867       --  which is the subtype of the context in which the aggregate was found.
868
869    begin
870       --  Ignore junk empty aggregate resulting from parser error
871
872       if No (Expressions (N))
873         and then No (Component_Associations (N))
874         and then not Null_Record_Present (N)
875       then
876          return;
877       end if;
878
879       --  If the aggregate has box-initialized components, its type must be
880       --  frozen so that initialization procedures can properly be called
881       --  in the resolution that follows.  The replacement of boxes with
882       --  initialization calls is properly an expansion activity but it must
883       --  be done during resolution.
884
885       if Expander_Active
886         and then Present (Component_Associations (N))
887       then
888          declare
889             Comp : Node_Id;
890
891          begin
892             Comp := First (Component_Associations (N));
893             while Present (Comp) loop
894                if Box_Present (Comp) then
895                   Insert_Actions (N, Freeze_Entity (Typ, N));
896                   exit;
897                end if;
898
899                Next (Comp);
900             end loop;
901          end;
902       end if;
903
904       --  An unqualified aggregate is restricted in SPARK to:
905
906       --    An aggregate item inside an aggregate for a multi-dimensional array
907
908       --    An expression being assigned to an unconstrained array, but only if
909       --    the aggregate specifies a value for OTHERS only.
910
911       if Nkind (Parent (N)) = N_Qualified_Expression then
912          if Is_Array_Type (Typ) then
913             Check_Qualified_Aggregate (Number_Dimensions (Typ), N);
914          else
915             Check_Qualified_Aggregate (1, N);
916          end if;
917       else
918          if Is_Array_Type (Typ)
919            and then Nkind (Parent (N)) = N_Assignment_Statement
920            and then not Is_Constrained (Etype (Name (Parent (N))))
921          then
922             if not Is_Others_Aggregate (N) then
923                Check_SPARK_Restriction
924                  ("array aggregate should have only OTHERS", N);
925             end if;
926
927          elsif Is_Top_Level_Aggregate (N) then
928             Check_SPARK_Restriction ("aggregate should be qualified", N);
929
930          --  The legality of this unqualified aggregate is checked by calling
931          --  Check_Qualified_Aggregate from one of its enclosing aggregate,
932          --  unless one of these already causes an error to be issued.
933
934          else
935             null;
936          end if;
937       end if;
938
939       --  Check for aggregates not allowed in configurable run-time mode.
940       --  We allow all cases of aggregates that do not come from source, since
941       --  these are all assumed to be small (e.g. bounds of a string literal).
942       --  We also allow aggregates of types we know to be small.
943
944       if not Support_Aggregates_On_Target
945         and then Comes_From_Source (N)
946         and then (not Known_Static_Esize (Typ) or else Esize (Typ) > 64)
947       then
948          Error_Msg_CRT ("aggregate", N);
949       end if;
950
951       --  Ada 2005 (AI-287): Limited aggregates allowed
952
953       --  In an instance, ignore aggregate subcomponents tnat may be limited,
954       --  because they originate in view conflicts. If the original aggregate
955       --  is legal and the actuals are legal, the aggregate itself is legal.
956
957       if Is_Limited_Type (Typ)
958         and then Ada_Version < Ada_2005
959         and then not In_Instance
960       then
961          Error_Msg_N ("aggregate type cannot be limited", N);
962          Explain_Limited_Type (Typ, N);
963
964       elsif Is_Class_Wide_Type (Typ) then
965          Error_Msg_N ("type of aggregate cannot be class-wide", N);
966
967       elsif Typ = Any_String
968         or else Typ = Any_Composite
969       then
970          Error_Msg_N ("no unique type for aggregate", N);
971          Set_Etype (N, Any_Composite);
972
973       elsif Is_Array_Type (Typ) and then Null_Record_Present (N) then
974          Error_Msg_N ("null record forbidden in array aggregate", N);
975
976       elsif Is_Record_Type (Typ) then
977          Resolve_Record_Aggregate (N, Typ);
978
979       elsif Is_Array_Type (Typ) then
980
981          --  First a special test, for the case of a positional aggregate
982          --  of characters which can be replaced by a string literal.
983
984          --  Do not perform this transformation if this was a string literal to
985          --  start with, whose components needed constraint checks, or if the
986          --  component type is non-static, because it will require those checks
987          --  and be transformed back into an aggregate.
988
989          if Number_Dimensions (Typ) = 1
990            and then Is_Standard_Character_Type (Component_Type (Typ))
991            and then No (Component_Associations (N))
992            and then not Is_Limited_Composite (Typ)
993            and then not Is_Private_Composite (Typ)
994            and then not Is_Bit_Packed_Array (Typ)
995            and then Nkind (Original_Node (Parent (N))) /= N_String_Literal
996            and then Is_Static_Subtype (Component_Type (Typ))
997          then
998             declare
999                Expr : Node_Id;
1000
1001             begin
1002                Expr := First (Expressions (N));
1003                while Present (Expr) loop
1004                   exit when Nkind (Expr) /= N_Character_Literal;
1005                   Next (Expr);
1006                end loop;
1007
1008                if No (Expr) then
1009                   Start_String;
1010
1011                   Expr := First (Expressions (N));
1012                   while Present (Expr) loop
1013                      Store_String_Char (UI_To_CC (Char_Literal_Value (Expr)));
1014                      Next (Expr);
1015                   end loop;
1016
1017                   Rewrite (N, Make_String_Literal (Loc, End_String));
1018
1019                   Analyze_And_Resolve (N, Typ);
1020                   return;
1021                end if;
1022             end;
1023          end if;
1024
1025          --  Here if we have a real aggregate to deal with
1026
1027          Array_Aggregate : declare
1028             Aggr_Resolved : Boolean;
1029
1030             Aggr_Typ : constant Entity_Id := Etype (Typ);
1031             --  This is the unconstrained array type, which is the type against
1032             --  which the aggregate is to be resolved. Typ itself is the array
1033             --  type of the context which may not be the same subtype as the
1034             --  subtype for the final aggregate.
1035
1036          begin
1037             --  In the following we determine whether an OTHERS choice is
1038             --  allowed inside the array aggregate. The test checks the context
1039             --  in which the array aggregate occurs. If the context does not
1040             --  permit it, or the aggregate type is unconstrained, an OTHERS
1041             --  choice is not allowed (except that it is always allowed on the
1042             --  right-hand side of an assignment statement; in this case the
1043             --  constrainedness of the type doesn't matter).
1044
1045             --  If expansion is disabled (generic context, or semantics-only
1046             --  mode) actual subtypes cannot be constructed, and the type of an
1047             --  object may be its unconstrained nominal type. However, if the
1048             --  context is an assignment, we assume that OTHERS is allowed,
1049             --  because the target of the assignment will have a constrained
1050             --  subtype when fully compiled.
1051
1052             --  Note that there is no node for Explicit_Actual_Parameter.
1053             --  To test for this context we therefore have to test for node
1054             --  N_Parameter_Association which itself appears only if there is a
1055             --  formal parameter. Consequently we also need to test for
1056             --  N_Procedure_Call_Statement or N_Function_Call.
1057
1058             Set_Etype (N, Aggr_Typ);  --  May be overridden later on
1059
1060             if Pkind = N_Assignment_Statement
1061               or else (Is_Constrained (Typ)
1062                         and then
1063                           (Pkind = N_Parameter_Association     or else
1064                            Pkind = N_Function_Call             or else
1065                            Pkind = N_Procedure_Call_Statement  or else
1066                            Pkind = N_Generic_Association       or else
1067                            Pkind = N_Formal_Object_Declaration or else
1068                            Pkind = N_Simple_Return_Statement   or else
1069                            Pkind = N_Object_Declaration        or else
1070                            Pkind = N_Component_Declaration     or else
1071                            Pkind = N_Parameter_Specification   or else
1072                            Pkind = N_Qualified_Expression      or else
1073                            Pkind = N_Aggregate                 or else
1074                            Pkind = N_Extension_Aggregate       or else
1075                            Pkind = N_Component_Association))
1076             then
1077                Aggr_Resolved :=
1078                  Resolve_Array_Aggregate
1079                    (N,
1080                     Index          => First_Index (Aggr_Typ),
1081                     Index_Constr   => First_Index (Typ),
1082                     Component_Typ  => Component_Type (Typ),
1083                     Others_Allowed => True);
1084
1085             elsif not Expander_Active
1086               and then Pkind = N_Assignment_Statement
1087             then
1088                Aggr_Resolved :=
1089                  Resolve_Array_Aggregate
1090                    (N,
1091                     Index          => First_Index (Aggr_Typ),
1092                     Index_Constr   => First_Index (Typ),
1093                     Component_Typ  => Component_Type (Typ),
1094                     Others_Allowed => True);
1095
1096             else
1097                Aggr_Resolved :=
1098                  Resolve_Array_Aggregate
1099                    (N,
1100                     Index          => First_Index (Aggr_Typ),
1101                     Index_Constr   => First_Index (Aggr_Typ),
1102                     Component_Typ  => Component_Type (Typ),
1103                     Others_Allowed => False);
1104             end if;
1105
1106             if not Aggr_Resolved then
1107
1108                --  A parenthesized expression may have been intended as an
1109                --  aggregate, leading to a type error when analyzing the
1110                --  component. This can also happen for a nested component
1111                --  (see Analyze_Aggr_Expr).
1112
1113                if Paren_Count (N) > 0 then
1114                   Error_Msg_N
1115                     ("positional aggregate cannot have one component", N);
1116                end if;
1117
1118                Aggr_Subtyp := Any_Composite;
1119
1120             else
1121                Aggr_Subtyp := Array_Aggr_Subtype (N, Typ);
1122             end if;
1123
1124             Set_Etype (N, Aggr_Subtyp);
1125          end Array_Aggregate;
1126
1127       elsif Is_Private_Type (Typ)
1128         and then Present (Full_View (Typ))
1129         and then (In_Inlined_Body or In_Instance_Body)
1130         and then Is_Composite_Type (Full_View (Typ))
1131       then
1132          Resolve (N, Full_View (Typ));
1133
1134       else
1135          Error_Msg_N ("illegal context for aggregate", N);
1136       end if;
1137
1138       --  If we can determine statically that the evaluation of the aggregate
1139       --  raises Constraint_Error, then replace the aggregate with an
1140       --  N_Raise_Constraint_Error node, but set the Etype to the right
1141       --  aggregate subtype. Gigi needs this.
1142
1143       if Raises_Constraint_Error (N) then
1144          Aggr_Subtyp := Etype (N);
1145          Rewrite (N,
1146            Make_Raise_Constraint_Error (Loc, Reason => CE_Range_Check_Failed));
1147          Set_Raises_Constraint_Error (N);
1148          Set_Etype (N, Aggr_Subtyp);
1149          Set_Analyzed (N);
1150       end if;
1151
1152       Check_Function_Writable_Actuals (N);
1153    end Resolve_Aggregate;
1154
1155    -----------------------------
1156    -- Resolve_Array_Aggregate --
1157    -----------------------------
1158
1159    function Resolve_Array_Aggregate
1160      (N              : Node_Id;
1161       Index          : Node_Id;
1162       Index_Constr   : Node_Id;
1163       Component_Typ  : Entity_Id;
1164       Others_Allowed : Boolean) return Boolean
1165    is
1166       Loc : constant Source_Ptr := Sloc (N);
1167
1168       Failure : constant Boolean := False;
1169       Success : constant Boolean := True;
1170
1171       Index_Typ      : constant Entity_Id := Etype (Index);
1172       Index_Typ_Low  : constant Node_Id   := Type_Low_Bound  (Index_Typ);
1173       Index_Typ_High : constant Node_Id   := Type_High_Bound (Index_Typ);
1174       --  The type of the index corresponding to the array sub-aggregate along
1175       --  with its low and upper bounds.
1176
1177       Index_Base      : constant Entity_Id := Base_Type (Index_Typ);
1178       Index_Base_Low  : constant Node_Id   := Type_Low_Bound (Index_Base);
1179       Index_Base_High : constant Node_Id   := Type_High_Bound (Index_Base);
1180       --  Ditto for the base type
1181
1182       function Add (Val : Uint; To : Node_Id) return Node_Id;
1183       --  Creates a new expression node where Val is added to expression To.
1184       --  Tries to constant fold whenever possible. To must be an already
1185       --  analyzed expression.
1186
1187       procedure Check_Bound (BH : Node_Id; AH : in out Node_Id);
1188       --  Checks that AH (the upper bound of an array aggregate) is less than
1189       --  or equal to BH (the upper bound of the index base type). If the check
1190       --  fails, a warning is emitted, the Raises_Constraint_Error flag of N is
1191       --  set, and AH is replaced with a duplicate of BH.
1192
1193       procedure Check_Bounds (L, H : Node_Id; AL, AH : Node_Id);
1194       --  Checks that range AL .. AH is compatible with range L .. H. Emits a
1195       --  warning if not and sets the Raises_Constraint_Error flag in N.
1196
1197       procedure Check_Length (L, H : Node_Id; Len : Uint);
1198       --  Checks that range L .. H contains at least Len elements. Emits a
1199       --  warning if not and sets the Raises_Constraint_Error flag in N.
1200
1201       function Dynamic_Or_Null_Range (L, H : Node_Id) return Boolean;
1202       --  Returns True if range L .. H is dynamic or null
1203
1204       procedure Get (Value : out Uint; From : Node_Id; OK : out Boolean);
1205       --  Given expression node From, this routine sets OK to False if it
1206       --  cannot statically evaluate From. Otherwise it stores this static
1207       --  value into Value.
1208
1209       function Resolve_Aggr_Expr
1210         (Expr        : Node_Id;
1211          Single_Elmt : Boolean) return Boolean;
1212       --  Resolves aggregate expression Expr. Returns False if resolution
1213       --  fails. If Single_Elmt is set to False, the expression Expr may be
1214       --  used to initialize several array aggregate elements (this can happen
1215       --  for discrete choices such as "L .. H => Expr" or the OTHERS choice).
1216       --  In this event we do not resolve Expr unless expansion is disabled.
1217       --  To know why, see the DELAYED COMPONENT RESOLUTION note above.
1218       --
1219       --  NOTE: In the case of "... => <>", we pass the in the
1220       --  N_Component_Association node as Expr, since there is no Expression in
1221       --  that case, and we need a Sloc for the error message.
1222
1223       ---------
1224       -- Add --
1225       ---------
1226
1227       function Add (Val : Uint; To : Node_Id) return Node_Id is
1228          Expr_Pos : Node_Id;
1229          Expr     : Node_Id;
1230          To_Pos   : Node_Id;
1231
1232       begin
1233          if Raises_Constraint_Error (To) then
1234             return To;
1235          end if;
1236
1237          --  First test if we can do constant folding
1238
1239          if Compile_Time_Known_Value (To)
1240            or else Nkind (To) = N_Integer_Literal
1241          then
1242             Expr_Pos := Make_Integer_Literal (Loc, Expr_Value (To) + Val);
1243             Set_Is_Static_Expression (Expr_Pos);
1244             Set_Etype (Expr_Pos, Etype (To));
1245             Set_Analyzed (Expr_Pos, Analyzed (To));
1246
1247             if not Is_Enumeration_Type (Index_Typ) then
1248                Expr := Expr_Pos;
1249
1250             --  If we are dealing with enumeration return
1251             --     Index_Typ'Val (Expr_Pos)
1252
1253             else
1254                Expr :=
1255                  Make_Attribute_Reference
1256                    (Loc,
1257                     Prefix         => New_Occurrence_Of (Index_Typ, Loc),
1258                     Attribute_Name => Name_Val,
1259                     Expressions    => New_List (Expr_Pos));
1260             end if;
1261
1262             return Expr;
1263          end if;
1264
1265          --  If we are here no constant folding possible
1266
1267          if not Is_Enumeration_Type (Index_Base) then
1268             Expr :=
1269               Make_Op_Add (Loc,
1270                 Left_Opnd  => Duplicate_Subexpr (To),
1271                 Right_Opnd => Make_Integer_Literal (Loc, Val));
1272
1273          --  If we are dealing with enumeration return
1274          --    Index_Typ'Val (Index_Typ'Pos (To) + Val)
1275
1276          else
1277             To_Pos :=
1278               Make_Attribute_Reference
1279                 (Loc,
1280                  Prefix         => New_Occurrence_Of (Index_Typ, Loc),
1281                  Attribute_Name => Name_Pos,
1282                  Expressions    => New_List (Duplicate_Subexpr (To)));
1283
1284             Expr_Pos :=
1285               Make_Op_Add (Loc,
1286                            Left_Opnd  => To_Pos,
1287                            Right_Opnd => Make_Integer_Literal (Loc, Val));
1288
1289             Expr :=
1290               Make_Attribute_Reference
1291                 (Loc,
1292                  Prefix         => New_Occurrence_Of (Index_Typ, Loc),
1293                  Attribute_Name => Name_Val,
1294                  Expressions    => New_List (Expr_Pos));
1295
1296             --  If the index type has a non standard representation, the
1297             --  attributes 'Val and 'Pos expand into function calls and the
1298             --  resulting expression is considered non-safe for reevaluation
1299             --  by the backend. Relocate it into a constant temporary in order
1300             --  to make it safe for reevaluation.
1301
1302             if Has_Non_Standard_Rep (Etype (N)) then
1303                declare
1304                   Def_Id : Entity_Id;
1305
1306                begin
1307                   Def_Id := Make_Temporary (Loc, 'R', Expr);
1308                   Set_Etype (Def_Id, Index_Typ);
1309                   Insert_Action (N,
1310                     Make_Object_Declaration (Loc,
1311                       Defining_Identifier => Def_Id,
1312                       Object_Definition   =>
1313                         New_Occurrence_Of (Index_Typ, Loc),
1314                       Constant_Present    => True,
1315                       Expression          => Relocate_Node (Expr)));
1316
1317                   Expr := New_Occurrence_Of (Def_Id, Loc);
1318                end;
1319             end if;
1320          end if;
1321
1322          return Expr;
1323       end Add;
1324
1325       -----------------
1326       -- Check_Bound --
1327       -----------------
1328
1329       procedure Check_Bound (BH : Node_Id; AH : in out Node_Id) is
1330          Val_BH : Uint;
1331          Val_AH : Uint;
1332
1333          OK_BH : Boolean;
1334          OK_AH : Boolean;
1335
1336       begin
1337          Get (Value => Val_BH, From => BH, OK => OK_BH);
1338          Get (Value => Val_AH, From => AH, OK => OK_AH);
1339
1340          if OK_BH and then OK_AH and then Val_BH < Val_AH then
1341             Set_Raises_Constraint_Error (N);
1342             Error_Msg_Warn := SPARK_Mode /= On;
1343             Error_Msg_N ("upper bound out of range<<", AH);
1344             Error_Msg_N ("\Constraint_Error [<<", AH);
1345
1346             --  You need to set AH to BH or else in the case of enumerations
1347             --  indexes we will not be able to resolve the aggregate bounds.
1348
1349             AH := Duplicate_Subexpr (BH);
1350          end if;
1351       end Check_Bound;
1352
1353       ------------------
1354       -- Check_Bounds --
1355       ------------------
1356
1357       procedure Check_Bounds (L, H : Node_Id; AL, AH : Node_Id) is
1358          Val_L  : Uint;
1359          Val_H  : Uint;
1360          Val_AL : Uint;
1361          Val_AH : Uint;
1362
1363          OK_L : Boolean;
1364          OK_H : Boolean;
1365
1366          OK_AL : Boolean;
1367          OK_AH  : Boolean;
1368          pragma Warnings (Off, OK_AL);
1369          pragma Warnings (Off, OK_AH);
1370
1371       begin
1372          if Raises_Constraint_Error (N)
1373            or else Dynamic_Or_Null_Range (AL, AH)
1374          then
1375             return;
1376          end if;
1377
1378          Get (Value => Val_L, From => L, OK => OK_L);
1379          Get (Value => Val_H, From => H, OK => OK_H);
1380
1381          Get (Value => Val_AL, From => AL, OK => OK_AL);
1382          Get (Value => Val_AH, From => AH, OK => OK_AH);
1383
1384          if OK_L and then Val_L > Val_AL then
1385             Set_Raises_Constraint_Error (N);
1386             Error_Msg_Warn := SPARK_Mode /= On;
1387             Error_Msg_N ("lower bound of aggregate out of range<<", N);
1388             Error_Msg_N ("\Constraint_Error [<<", N);
1389          end if;
1390
1391          if OK_H and then Val_H < Val_AH then
1392             Set_Raises_Constraint_Error (N);
1393             Error_Msg_Warn := SPARK_Mode /= On;
1394             Error_Msg_N ("upper bound of aggregate out of range<<", N);
1395             Error_Msg_N ("\Constraint_Error [<<", N);
1396          end if;
1397       end Check_Bounds;
1398
1399       ------------------
1400       -- Check_Length --
1401       ------------------
1402
1403       procedure Check_Length (L, H : Node_Id; Len : Uint) is
1404          Val_L  : Uint;
1405          Val_H  : Uint;
1406
1407          OK_L  : Boolean;
1408          OK_H  : Boolean;
1409
1410          Range_Len : Uint;
1411
1412       begin
1413          if Raises_Constraint_Error (N) then
1414             return;
1415          end if;
1416
1417          Get (Value => Val_L, From => L, OK => OK_L);
1418          Get (Value => Val_H, From => H, OK => OK_H);
1419
1420          if not OK_L or else not OK_H then
1421             return;
1422          end if;
1423
1424          --  If null range length is zero
1425
1426          if Val_L > Val_H then
1427             Range_Len := Uint_0;
1428          else
1429             Range_Len := Val_H - Val_L + 1;
1430          end if;
1431
1432          if Range_Len < Len then
1433             Set_Raises_Constraint_Error (N);
1434             Error_Msg_Warn := SPARK_Mode /= On;
1435             Error_Msg_N ("too many elements<<", N);
1436             Error_Msg_N ("\Constraint_Error [<<", N);
1437          end if;
1438       end Check_Length;
1439
1440       ---------------------------
1441       -- Dynamic_Or_Null_Range --
1442       ---------------------------
1443
1444       function Dynamic_Or_Null_Range (L, H : Node_Id) return Boolean is
1445          Val_L : Uint;
1446          Val_H : Uint;
1447
1448          OK_L  : Boolean;
1449          OK_H  : Boolean;
1450
1451       begin
1452          Get (Value => Val_L, From => L, OK => OK_L);
1453          Get (Value => Val_H, From => H, OK => OK_H);
1454
1455          return not OK_L or else not OK_H
1456            or else not Is_OK_Static_Expression (L)
1457            or else not Is_OK_Static_Expression (H)
1458            or else Val_L > Val_H;
1459       end Dynamic_Or_Null_Range;
1460
1461       ---------
1462       -- Get --
1463       ---------
1464
1465       procedure Get (Value : out Uint; From : Node_Id; OK : out Boolean) is
1466       begin
1467          OK := True;
1468
1469          if Compile_Time_Known_Value (From) then
1470             Value := Expr_Value (From);
1471
1472          --  If expression From is something like Some_Type'Val (10) then
1473          --  Value = 10.
1474
1475          elsif Nkind (From) = N_Attribute_Reference
1476            and then Attribute_Name (From) = Name_Val
1477            and then Compile_Time_Known_Value (First (Expressions (From)))
1478          then
1479             Value := Expr_Value (First (Expressions (From)));
1480
1481          else
1482             Value := Uint_0;
1483             OK := False;
1484          end if;
1485       end Get;
1486
1487       -----------------------
1488       -- Resolve_Aggr_Expr --
1489       -----------------------
1490
1491       function Resolve_Aggr_Expr
1492         (Expr        : Node_Id;
1493          Single_Elmt : Boolean) return Boolean
1494       is
1495          Nxt_Ind        : constant Node_Id := Next_Index (Index);
1496          Nxt_Ind_Constr : constant Node_Id := Next_Index (Index_Constr);
1497          --  Index is the current index corresponding to the expression
1498
1499          Resolution_OK : Boolean := True;
1500          --  Set to False if resolution of the expression failed
1501
1502       begin
1503          --  Defend against previous errors
1504
1505          if Nkind (Expr) = N_Error
1506            or else Error_Posted (Expr)
1507          then
1508             return True;
1509          end if;
1510
1511          --  If the array type against which we are resolving the aggregate
1512          --  has several dimensions, the expressions nested inside the
1513          --  aggregate must be further aggregates (or strings).
1514
1515          if Present (Nxt_Ind) then
1516             if Nkind (Expr) /= N_Aggregate then
1517
1518                --  A string literal can appear where a one-dimensional array
1519                --  of characters is expected. If the literal looks like an
1520                --  operator, it is still an operator symbol, which will be
1521                --  transformed into a string when analyzed.
1522
1523                if Is_Character_Type (Component_Typ)
1524                  and then No (Next_Index (Nxt_Ind))
1525                  and then Nkind_In (Expr, N_String_Literal, N_Operator_Symbol)
1526                then
1527                   --  A string literal used in a multidimensional array
1528                   --  aggregate in place of the final one-dimensional
1529                   --  aggregate must not be enclosed in parentheses.
1530
1531                   if Paren_Count (Expr) /= 0 then
1532                      Error_Msg_N ("no parenthesis allowed here", Expr);
1533                   end if;
1534
1535                   Make_String_Into_Aggregate (Expr);
1536
1537                else
1538                   Error_Msg_N ("nested array aggregate expected", Expr);
1539
1540                   --  If the expression is parenthesized, this may be
1541                   --  a missing component association for a 1-aggregate.
1542
1543                   if Paren_Count (Expr) > 0 then
1544                      Error_Msg_N
1545                        ("\if single-component aggregate is intended,"
1546                         & " write e.g. (1 ='> ...)", Expr);
1547                   end if;
1548
1549                   return Failure;
1550                end if;
1551             end if;
1552
1553             --  If it's "... => <>", nothing to resolve
1554
1555             if Nkind (Expr) = N_Component_Association then
1556                pragma Assert (Box_Present (Expr));
1557                return Success;
1558             end if;
1559
1560             --  Ada 2005 (AI-231): Propagate the type to the nested aggregate.
1561             --  Required to check the null-exclusion attribute (if present).
1562             --  This value may be overridden later on.
1563
1564             Set_Etype (Expr, Etype (N));
1565
1566             Resolution_OK := Resolve_Array_Aggregate
1567               (Expr, Nxt_Ind, Nxt_Ind_Constr, Component_Typ, Others_Allowed);
1568
1569          else
1570             --  If it's "... => <>", nothing to resolve
1571
1572             if Nkind (Expr) = N_Component_Association then
1573                pragma Assert (Box_Present (Expr));
1574                return Success;
1575             end if;
1576
1577             --  Do not resolve the expressions of discrete or others choices
1578             --  unless the expression covers a single component, or the
1579             --  expander is inactive.
1580
1581             --  In SPARK mode, expressions that can perform side-effects will
1582             --  be recognized by the gnat2why back-end, and the whole
1583             --  subprogram will be ignored. So semantic analysis can be
1584             --  performed safely.
1585
1586             if Single_Elmt
1587               or else not Expander_Active
1588               or else In_Spec_Expression
1589             then
1590                Analyze_And_Resolve (Expr, Component_Typ);
1591                Check_Expr_OK_In_Limited_Aggregate (Expr);
1592                Check_Non_Static_Context (Expr);
1593                Aggregate_Constraint_Checks (Expr, Component_Typ);
1594                Check_Unset_Reference (Expr);
1595             end if;
1596          end if;
1597
1598          --  If an aggregate component has a type with predicates, an explicit
1599          --  predicate check must be applied, as for an assignment statement,
1600          --  because the aggegate might not be expanded into individual
1601          --  component assignments.
1602
1603          if Present (Predicate_Function (Component_Typ)) then
1604             Apply_Predicate_Check (Expr, Component_Typ);
1605          end if;
1606
1607          if Raises_Constraint_Error (Expr)
1608            and then Nkind (Parent (Expr)) /= N_Component_Association
1609          then
1610             Set_Raises_Constraint_Error (N);
1611          end if;
1612
1613          --  If the expression has been marked as requiring a range check,
1614          --  then generate it here.
1615
1616          if Do_Range_Check (Expr) then
1617             Set_Do_Range_Check (Expr, False);
1618             Generate_Range_Check (Expr, Component_Typ, CE_Range_Check_Failed);
1619          end if;
1620
1621          return Resolution_OK;
1622       end Resolve_Aggr_Expr;
1623
1624       --  Variables local to Resolve_Array_Aggregate
1625
1626       Assoc  : Node_Id;
1627       Choice : Node_Id;
1628       Expr   : Node_Id;
1629
1630       Discard : Node_Id;
1631       pragma Warnings (Off, Discard);
1632
1633       Delete_Choice : Boolean;
1634       --  Used when replacing a subtype choice with predicate by a list
1635
1636       Aggr_Low  : Node_Id := Empty;
1637       Aggr_High : Node_Id := Empty;
1638       --  The actual low and high bounds of this sub-aggregate
1639
1640       Choices_Low  : Node_Id := Empty;
1641       Choices_High : Node_Id := Empty;
1642       --  The lowest and highest discrete choices values for a named aggregate
1643
1644       Nb_Elements : Uint := Uint_0;
1645       --  The number of elements in a positional aggregate
1646
1647       Others_Present : Boolean := False;
1648
1649       Nb_Choices : Nat := 0;
1650       --  Contains the overall number of named choices in this sub-aggregate
1651
1652       Nb_Discrete_Choices : Nat := 0;
1653       --  The overall number of discrete choices (not counting others choice)
1654
1655       Case_Table_Size : Nat;
1656       --  Contains the size of the case table needed to sort aggregate choices
1657
1658    --  Start of processing for Resolve_Array_Aggregate
1659
1660    begin
1661       --  Ignore junk empty aggregate resulting from parser error
1662
1663       if No (Expressions (N))
1664         and then No (Component_Associations (N))
1665         and then not Null_Record_Present (N)
1666       then
1667          return False;
1668       end if;
1669
1670       --  STEP 1: make sure the aggregate is correctly formatted
1671
1672       if Present (Component_Associations (N)) then
1673          Assoc := First (Component_Associations (N));
1674          while Present (Assoc) loop
1675             Choice := First (Choices (Assoc));
1676             Delete_Choice := False;
1677
1678             while Present (Choice) loop
1679                if Nkind (Choice) = N_Others_Choice then
1680                   Others_Present := True;
1681
1682                   if Choice /= First (Choices (Assoc))
1683                     or else Present (Next (Choice))
1684                   then
1685                      Error_Msg_N
1686                        ("OTHERS must appear alone in a choice list", Choice);
1687                      return Failure;
1688                   end if;
1689
1690                   if Present (Next (Assoc)) then
1691                      Error_Msg_N
1692                        ("OTHERS must appear last in an aggregate", Choice);
1693                      return Failure;
1694                   end if;
1695
1696                   if Ada_Version = Ada_83
1697                     and then Assoc /= First (Component_Associations (N))
1698                     and then Nkind_In (Parent (N), N_Assignment_Statement,
1699                                                    N_Object_Declaration)
1700                   then
1701                      Error_Msg_N
1702                        ("(Ada 83) illegal context for OTHERS choice", N);
1703                   end if;
1704
1705                elsif Is_Entity_Name (Choice) then
1706                   Analyze (Choice);
1707
1708                   declare
1709                      E      : constant Entity_Id := Entity (Choice);
1710                      New_Cs : List_Id;
1711                      P      : Node_Id;
1712                      C      : Node_Id;
1713
1714                   begin
1715                      if Is_Type (E) and then Has_Predicates (E) then
1716                         Freeze_Before (N, E);
1717
1718                         --  If the subtype has a static predicate, replace the
1719                         --  original choice with the list of individual values
1720                         --  covered by the predicate.
1721
1722                         if Present (Static_Predicate (E)) then
1723                            Delete_Choice := True;
1724
1725                            New_Cs := New_List;
1726                            P := First (Static_Predicate (E));
1727                            while Present (P) loop
1728                               C := New_Copy (P);
1729                               Set_Sloc (C, Sloc (Choice));
1730                               Append_To (New_Cs, C);
1731                               Next (P);
1732                            end loop;
1733
1734                            Insert_List_After (Choice, New_Cs);
1735                         end if;
1736                      end if;
1737                   end;
1738                end if;
1739
1740                Nb_Choices := Nb_Choices + 1;
1741
1742                declare
1743                   C : constant Node_Id := Choice;
1744
1745                begin
1746                   Next (Choice);
1747
1748                   if Delete_Choice then
1749                      Remove (C);
1750                      Nb_Choices := Nb_Choices - 1;
1751                      Delete_Choice := False;
1752                   end if;
1753                end;
1754             end loop;
1755
1756             Next (Assoc);
1757          end loop;
1758       end if;
1759
1760       --  At this point we know that the others choice, if present, is by
1761       --  itself and appears last in the aggregate. Check if we have mixed
1762       --  positional and discrete associations (other than the others choice).
1763
1764       if Present (Expressions (N))
1765         and then (Nb_Choices > 1
1766                    or else (Nb_Choices = 1 and then not Others_Present))
1767       then
1768          Error_Msg_N
1769            ("named association cannot follow positional association",
1770             First (Choices (First (Component_Associations (N)))));
1771          return Failure;
1772       end if;
1773
1774       --  Test for the validity of an others choice if present
1775
1776       if Others_Present and then not Others_Allowed then
1777          Error_Msg_N
1778            ("OTHERS choice not allowed here",
1779             First (Choices (First (Component_Associations (N)))));
1780          return Failure;
1781       end if;
1782
1783       --  Protect against cascaded errors
1784
1785       if Etype (Index_Typ) = Any_Type then
1786          return Failure;
1787       end if;
1788
1789       --  STEP 2: Process named components
1790
1791       if No (Expressions (N)) then
1792          if Others_Present then
1793             Case_Table_Size := Nb_Choices - 1;
1794          else
1795             Case_Table_Size := Nb_Choices;
1796          end if;
1797
1798          Step_2 : declare
1799             Low  : Node_Id;
1800             High : Node_Id;
1801             --  Denote the lowest and highest values in an aggregate choice
1802
1803             S_Low  : Node_Id := Empty;
1804             S_High : Node_Id := Empty;
1805             --  if a choice in an aggregate is a subtype indication these
1806             --  denote the lowest and highest values of the subtype
1807
1808             Table : Case_Table_Type (0 .. Case_Table_Size);
1809             --  Used to sort all the different choice values. Entry zero is
1810             --  reserved for sorting purposes.
1811
1812             Single_Choice : Boolean;
1813             --  Set to true every time there is a single discrete choice in a
1814             --  discrete association
1815
1816             Prev_Nb_Discrete_Choices : Nat;
1817             --  Used to keep track of the number of discrete choices in the
1818             --  current association.
1819
1820             Errors_Posted_On_Choices : Boolean := False;
1821             --  Keeps track of whether any choices have semantic errors
1822
1823             function Empty_Range (A : Node_Id)  return Boolean;
1824             --  If an association covers an empty range, some warnings on the
1825             --  expression of the association can be disabled.
1826
1827             -----------------
1828             -- Empty_Range --
1829             -----------------
1830
1831             function Empty_Range (A : Node_Id)  return Boolean is
1832                R : constant Node_Id := First (Choices (A));
1833             begin
1834                return No (Next (R))
1835                  and then Nkind (R) = N_Range
1836                  and then Compile_Time_Compare
1837                             (Low_Bound (R), High_Bound (R), False) = GT;
1838             end Empty_Range;
1839
1840          --  Start of processing for Step_2
1841
1842          begin
1843             --  STEP 2 (A): Check discrete choices validity
1844
1845             Assoc := First (Component_Associations (N));
1846             while Present (Assoc) loop
1847                Prev_Nb_Discrete_Choices := Nb_Discrete_Choices;
1848                Choice := First (Choices (Assoc));
1849                loop
1850                   Analyze (Choice);
1851
1852                   if Nkind (Choice) = N_Others_Choice then
1853                      Single_Choice := False;
1854                      exit;
1855
1856                   --  Test for subtype mark without constraint
1857
1858                   elsif Is_Entity_Name (Choice) and then
1859                     Is_Type (Entity (Choice))
1860                   then
1861                      if Base_Type (Entity (Choice)) /= Index_Base then
1862                         Error_Msg_N
1863                           ("invalid subtype mark in aggregate choice",
1864                            Choice);
1865                         return Failure;
1866                      end if;
1867
1868                   --  Case of subtype indication
1869
1870                   elsif Nkind (Choice) = N_Subtype_Indication then
1871                      Resolve_Discrete_Subtype_Indication (Choice, Index_Base);
1872
1873                      --  Does the subtype indication evaluation raise CE?
1874
1875                      Get_Index_Bounds (Subtype_Mark (Choice), S_Low, S_High);
1876                      Get_Index_Bounds (Choice, Low, High);
1877                      Check_Bounds (S_Low, S_High, Low, High);
1878
1879                   --  Case of range or expression
1880
1881                   else
1882                      Resolve (Choice, Index_Base);
1883                      Check_Unset_Reference (Choice);
1884                      Check_Non_Static_Context (Choice);
1885
1886                      --  If semantic errors were posted on the choice, then
1887                      --  record that for possible early return from later
1888                      --  processing (see handling of enumeration choices).
1889
1890                      if Error_Posted (Choice) then
1891                         Errors_Posted_On_Choices := True;
1892                      end if;
1893
1894                      --  Do not range check a choice. This check is redundant
1895                      --  since this test is already done when we check that the
1896                      --  bounds of the array aggregate are within range.
1897
1898                      Set_Do_Range_Check (Choice, False);
1899
1900                      --  In SPARK, the choice must be static
1901
1902                      if not (Is_Static_Expression (Choice)
1903                               or else (Nkind (Choice) = N_Range
1904                                         and then Is_Static_Range (Choice)))
1905                      then
1906                         Check_SPARK_Restriction
1907                           ("choice should be static", Choice);
1908                      end if;
1909                   end if;
1910
1911                   --  If we could not resolve the discrete choice stop here
1912
1913                   if Etype (Choice) = Any_Type then
1914                      return Failure;
1915
1916                   --  If the discrete choice raises CE get its original bounds
1917
1918                   elsif Nkind (Choice) = N_Raise_Constraint_Error then
1919                      Set_Raises_Constraint_Error (N);
1920                      Get_Index_Bounds (Original_Node (Choice), Low, High);
1921
1922                   --  Otherwise get its bounds as usual
1923
1924                   else
1925                      Get_Index_Bounds (Choice, Low, High);
1926                   end if;
1927
1928                   if (Dynamic_Or_Null_Range (Low, High)
1929                        or else (Nkind (Choice) = N_Subtype_Indication
1930                                  and then
1931                                    Dynamic_Or_Null_Range (S_Low, S_High)))
1932                     and then Nb_Choices /= 1
1933                   then
1934                      Error_Msg_N
1935                        ("dynamic or empty choice in aggregate " &
1936                         "must be the only choice", Choice);
1937                      return Failure;
1938                   end if;
1939
1940                   Nb_Discrete_Choices := Nb_Discrete_Choices + 1;
1941                   Table (Nb_Discrete_Choices).Lo := Low;
1942                   Table (Nb_Discrete_Choices).Hi := High;
1943                   Table (Nb_Discrete_Choices).Choice := Choice;
1944
1945                   Next (Choice);
1946
1947                   if No (Choice) then
1948
1949                      --  Check if we have a single discrete choice and whether
1950                      --  this discrete choice specifies a single value.
1951
1952                      Single_Choice :=
1953                        (Nb_Discrete_Choices = Prev_Nb_Discrete_Choices + 1)
1954                          and then (Low = High);
1955
1956                      exit;
1957                   end if;
1958                end loop;
1959
1960                --  Ada 2005 (AI-231)
1961
1962                if Ada_Version >= Ada_2005
1963                  and then Known_Null (Expression (Assoc))
1964                  and then not Empty_Range (Assoc)
1965                then
1966                   Check_Can_Never_Be_Null (Etype (N), Expression (Assoc));
1967                end if;
1968
1969                --  Ada 2005 (AI-287): In case of default initialized component
1970                --  we delay the resolution to the expansion phase.
1971
1972                if Box_Present (Assoc) then
1973
1974                   --  Ada 2005 (AI-287): In case of default initialization of a
1975                   --  component the expander will generate calls to the
1976                   --  corresponding initialization subprogram. We need to call
1977                   --  Resolve_Aggr_Expr to check the rules about
1978                   --  dimensionality.
1979
1980                   if not Resolve_Aggr_Expr
1981                            (Assoc, Single_Elmt => Single_Choice)
1982                   then
1983                      return Failure;
1984                   end if;
1985
1986                elsif not Resolve_Aggr_Expr
1987                            (Expression (Assoc), Single_Elmt => Single_Choice)
1988                then
1989                   return Failure;
1990
1991                --  Check incorrect use of dynamically tagged expression
1992
1993                --  We differentiate here two cases because the expression may
1994                --  not be decorated. For example, the analysis and resolution
1995                --  of the expression associated with the others choice will be
1996                --  done later with the full aggregate. In such case we
1997                --  duplicate the expression tree to analyze the copy and
1998                --  perform the required check.
1999
2000                elsif not Present (Etype (Expression (Assoc))) then
2001                   declare
2002                      Save_Analysis : constant Boolean := Full_Analysis;
2003                      Expr          : constant Node_Id :=
2004                                        New_Copy_Tree (Expression (Assoc));
2005
2006                   begin
2007                      Expander_Mode_Save_And_Set (False);
2008                      Full_Analysis := False;
2009
2010                      --  Analyze the expression, making sure it is properly
2011                      --  attached to the tree before we do the analysis.
2012
2013                      Set_Parent (Expr, Parent (Expression (Assoc)));
2014                      Analyze (Expr);
2015
2016                      --  If the expression is a literal, propagate this info
2017                      --  to the expression in the association, to enable some
2018                      --  optimizations downstream.
2019
2020                      if Is_Entity_Name (Expr)
2021                        and then Present (Entity (Expr))
2022                        and then Ekind (Entity (Expr)) = E_Enumeration_Literal
2023                      then
2024                         Analyze_And_Resolve
2025                           (Expression (Assoc), Component_Typ);
2026                      end if;
2027
2028                      Full_Analysis := Save_Analysis;
2029                      Expander_Mode_Restore;
2030
2031                      if Is_Tagged_Type (Etype (Expr)) then
2032                         Check_Dynamically_Tagged_Expression
2033                           (Expr => Expr,
2034                            Typ  => Component_Type (Etype (N)),
2035                            Related_Nod => N);
2036                      end if;
2037                   end;
2038
2039                elsif Is_Tagged_Type (Etype (Expression (Assoc))) then
2040                   Check_Dynamically_Tagged_Expression
2041                     (Expr        => Expression (Assoc),
2042                      Typ         => Component_Type (Etype (N)),
2043                      Related_Nod => N);
2044                end if;
2045
2046                Next (Assoc);
2047             end loop;
2048
2049             --  If aggregate contains more than one choice then these must be
2050             --  static. Check for duplicate and missing values.
2051
2052             --  Note: there is duplicated code here wrt Check_Choice_Set in
2053             --  the body of Sem_Case, and it is possible we could just reuse
2054             --  that procedure. To be checked ???
2055
2056             if Nb_Discrete_Choices > 1 then
2057                Check_Choices : declare
2058                   Choice : Node_Id;
2059                   --  Location of choice for messages
2060
2061                   Hi_Val : Uint;
2062                   Lo_Val : Uint;
2063                   --  High end of one range and Low end of the next. Should be
2064                   --  contiguous if there is no hole in the list of values.
2065
2066                   Lo_Dup : Uint;
2067                   Hi_Dup : Uint;
2068                   --  End points of duplicated range
2069
2070                   Missing_Or_Duplicates : Boolean := False;
2071                   --  Set True if missing or duplicate choices found
2072
2073                   procedure Output_Bad_Choices (Lo, Hi : Uint; C : Node_Id);
2074                   --  Output continuation message with a representation of the
2075                   --  bounds (just Lo if Lo = Hi, else Lo .. Hi). C is the
2076                   --  choice node where the message is to be posted.
2077
2078                   ------------------------
2079                   -- Output_Bad_Choices --
2080                   ------------------------
2081
2082                   procedure Output_Bad_Choices (Lo, Hi : Uint; C : Node_Id) is
2083                   begin
2084                      --  Enumeration type case
2085
2086                      if Is_Enumeration_Type (Index_Typ) then
2087                         Error_Msg_Name_1 :=
2088                           Chars (Get_Enum_Lit_From_Pos (Index_Typ, Lo, Loc));
2089                         Error_Msg_Name_2 :=
2090                           Chars (Get_Enum_Lit_From_Pos (Index_Typ, Hi, Loc));
2091
2092                         if Lo = Hi then
2093                            Error_Msg_N ("\\  %!", C);
2094                         else
2095                            Error_Msg_N ("\\  % .. %!", C);
2096                         end if;
2097
2098                         --  Integer types case
2099
2100                      else
2101                         Error_Msg_Uint_1 := Lo;
2102                         Error_Msg_Uint_2 := Hi;
2103
2104                         if Lo = Hi then
2105                            Error_Msg_N ("\\  ^!", C);
2106                         else
2107                            Error_Msg_N ("\\  ^ .. ^!", C);
2108                         end if;
2109                      end if;
2110                   end Output_Bad_Choices;
2111
2112                --  Start of processing for Check_Choices
2113
2114                begin
2115                   Sort_Case_Table (Table);
2116
2117                   --  First we do a quick linear loop to find out if we have
2118                   --  any duplicates or missing entries (usually we have a
2119                   --  legal aggregate, so this will get us out quickly).
2120
2121                   for J in 1 .. Nb_Discrete_Choices - 1 loop
2122                      Hi_Val := Expr_Value (Table (J).Hi);
2123                      Lo_Val := Expr_Value (Table (J + 1).Lo);
2124
2125                      if Lo_Val <= Hi_Val
2126                        or else (Lo_Val > Hi_Val + 1
2127                                  and then not Others_Present)
2128                      then
2129                         Missing_Or_Duplicates := True;
2130                         exit;
2131                      end if;
2132                   end loop;
2133
2134                   --  If we have missing or duplicate entries, first fill in
2135                   --  the Highest entries to make life easier in the following
2136                   --  loops to detect bad entries.
2137
2138                   if Missing_Or_Duplicates then
2139                      Table (1).Highest := Expr_Value (Table (1).Hi);
2140
2141                      for J in 2 .. Nb_Discrete_Choices loop
2142                         Table (J).Highest :=
2143                           UI_Max
2144                             (Table (J - 1).Highest, Expr_Value (Table (J).Hi));
2145                      end loop;
2146
2147                      --  Loop through table entries to find duplicate indexes
2148
2149                      for J in 2 .. Nb_Discrete_Choices loop
2150                         Lo_Val := Expr_Value (Table (J).Lo);
2151                         Hi_Val := Expr_Value (Table (J).Hi);
2152
2153                         --  Case where we have duplicates (the lower bound of
2154                         --  this choice is less than or equal to the highest
2155                         --  high bound found so far).
2156
2157                         if Lo_Val <= Table (J - 1).Highest then
2158
2159                            --  We move backwards looking for duplicates. We can
2160                            --  abandon this loop as soon as we reach a choice
2161                            --  highest value that is less than Lo_Val.
2162
2163                            for K in reverse 1 .. J - 1 loop
2164                               exit when Table (K).Highest < Lo_Val;
2165
2166                               --  Here we may have duplicates between entries
2167                               --  for K and J. Get range of duplicates.
2168
2169                               Lo_Dup :=
2170                                 UI_Max (Lo_Val, Expr_Value (Table (K).Lo));
2171                               Hi_Dup :=
2172                                 UI_Min (Hi_Val, Expr_Value (Table (K).Hi));
2173
2174                               --  Nothing to do if duplicate range is null
2175
2176                               if Lo_Dup > Hi_Dup then
2177                                  null;
2178
2179                               --  Otherwise place proper message
2180
2181                               else
2182                                  --  We place message on later choice, with a
2183                                  --  line reference to the earlier choice.
2184
2185                                  if Sloc (Table (J).Choice) <
2186                                    Sloc (Table (K).Choice)
2187                                  then
2188                                     Choice := Table (K).Choice;
2189                                     Error_Msg_Sloc := Sloc (Table (J).Choice);
2190                                  else
2191                                     Choice := Table (J).Choice;
2192                                     Error_Msg_Sloc := Sloc (Table (K).Choice);
2193                                  end if;
2194
2195                                  if Lo_Dup = Hi_Dup then
2196                                     Error_Msg_N
2197                                       ("index value in array aggregate "
2198                                        & "duplicates the one given#!", Choice);
2199                                  else
2200                                     Error_Msg_N
2201                                       ("index values in array aggregate "
2202                                        & "duplicate those given#!", Choice);
2203                                  end if;
2204
2205                                  Output_Bad_Choices (Lo_Dup, Hi_Dup, Choice);
2206                               end if;
2207                            end loop;
2208                         end if;
2209                      end loop;
2210
2211                      --  Loop through entries in table to find missing indexes.
2212                      --  Not needed if others, since missing impossible.
2213
2214                      if not Others_Present then
2215                         for J in 2 .. Nb_Discrete_Choices loop
2216                            Lo_Val := Expr_Value (Table (J).Lo);
2217                            Hi_Val := Table (J - 1).Highest;
2218
2219                            if Lo_Val > Hi_Val + 1 then
2220                               Choice := Table (J).Lo;
2221
2222                               if Hi_Val + 1 = Lo_Val - 1 then
2223                                  Error_Msg_N
2224                                    ("missing index value in array aggregate!",
2225                                     Choice);
2226                               else
2227                                  Error_Msg_N
2228                                    ("missing index values in array aggregate!",
2229                                     Choice);
2230                               end if;
2231
2232                               Output_Bad_Choices
2233                                 (Hi_Val + 1, Lo_Val - 1, Choice);
2234                            end if;
2235                         end loop;
2236                      end if;
2237
2238                      --  If either missing or duplicate values, return failure
2239
2240                      Set_Etype (N, Any_Composite);
2241                      return Failure;
2242                   end if;
2243                end Check_Choices;
2244             end if;
2245
2246             --  STEP 2 (B): Compute aggregate bounds and min/max choices values
2247
2248             if Nb_Discrete_Choices > 0 then
2249                Choices_Low  := Table (1).Lo;
2250                Choices_High := Table (Nb_Discrete_Choices).Hi;
2251             end if;
2252
2253             --  If Others is present, then bounds of aggregate come from the
2254             --  index constraint (not the choices in the aggregate itself).
2255
2256             if Others_Present then
2257                Get_Index_Bounds (Index_Constr, Aggr_Low, Aggr_High);
2258
2259             --  No others clause present
2260
2261             else
2262                --  Special processing if others allowed and not present. This
2263                --  means that the bounds of the aggregate come from the index
2264                --  constraint (and the length must match).
2265
2266                if Others_Allowed then
2267                   Get_Index_Bounds (Index_Constr, Aggr_Low, Aggr_High);
2268
2269                   --  If others allowed, and no others present, then the array
2270                   --  should cover all index values. If it does not, we will
2271                   --  get a length check warning, but there is two cases where
2272                   --  an additional warning is useful:
2273
2274                   --  If we have no positional components, and the length is
2275                   --  wrong (which we can tell by others being allowed with
2276                   --  missing components), and the index type is an enumeration
2277                   --  type, then issue appropriate warnings about these missing
2278                   --  components. They are only warnings, since the aggregate
2279                   --  is fine, it's just the wrong length. We skip this check
2280                   --  for standard character types (since there are no literals
2281                   --  and it is too much trouble to concoct them), and also if
2282                   --  any of the bounds have not-known-at-compile-time values.
2283
2284                   --  Another case warranting a warning is when the length is
2285                   --  right, but as above we have an index type that is an
2286                   --  enumeration, and the bounds do not match. This is a
2287                   --  case where dubious sliding is allowed and we generate
2288                   --  a warning that the bounds do not match.
2289
2290                   if No (Expressions (N))
2291                     and then Nkind (Index) = N_Range
2292                     and then Is_Enumeration_Type (Etype (Index))
2293                     and then not Is_Standard_Character_Type (Etype (Index))
2294                     and then Compile_Time_Known_Value (Aggr_Low)
2295                     and then Compile_Time_Known_Value (Aggr_High)
2296                     and then Compile_Time_Known_Value (Choices_Low)
2297                     and then Compile_Time_Known_Value (Choices_High)
2298                   then
2299                      --  If any of the expressions or range bounds in choices
2300                      --  have semantic errors, then do not attempt further
2301                      --  resolution, to prevent cascaded errors.
2302
2303                      if Errors_Posted_On_Choices then
2304                         return Failure;
2305                      end if;
2306
2307                      declare
2308                         ALo : constant Node_Id := Expr_Value_E (Aggr_Low);
2309                         AHi : constant Node_Id := Expr_Value_E (Aggr_High);
2310                         CLo : constant Node_Id := Expr_Value_E (Choices_Low);
2311                         CHi : constant Node_Id := Expr_Value_E (Choices_High);
2312
2313                         Ent : Entity_Id;
2314
2315                      begin
2316                         --  Warning case 1, missing values at start/end. Only
2317                         --  do the check if the number of entries is too small.
2318
2319                         if (Enumeration_Pos (CHi) - Enumeration_Pos (CLo))
2320                               <
2321                            (Enumeration_Pos (AHi) - Enumeration_Pos (ALo))
2322                         then
2323                            Error_Msg_N
2324                              ("missing index value(s) in array aggregate??",
2325                               N);
2326
2327                            --  Output missing value(s) at start
2328
2329                            if Chars (ALo) /= Chars (CLo) then
2330                               Ent := Prev (CLo);
2331
2332                               if Chars (ALo) = Chars (Ent) then
2333                                  Error_Msg_Name_1 := Chars (ALo);
2334                                  Error_Msg_N ("\  %??", N);
2335                               else
2336                                  Error_Msg_Name_1 := Chars (ALo);
2337                                  Error_Msg_Name_2 := Chars (Ent);
2338                                  Error_Msg_N ("\  % .. %??", N);
2339                               end if;
2340                            end if;
2341
2342                            --  Output missing value(s) at end
2343
2344                            if Chars (AHi) /= Chars (CHi) then
2345                               Ent := Next (CHi);
2346
2347                               if Chars (AHi) = Chars (Ent) then
2348                                  Error_Msg_Name_1 := Chars (Ent);
2349                                  Error_Msg_N ("\  %??", N);
2350                               else
2351                                  Error_Msg_Name_1 := Chars (Ent);
2352                                  Error_Msg_Name_2 := Chars (AHi);
2353                                  Error_Msg_N ("\  % .. %??", N);
2354                               end if;
2355                            end if;
2356
2357                         --  Warning case 2, dubious sliding. The First_Subtype
2358                         --  test distinguishes between a constrained type where
2359                         --  sliding is not allowed (so we will get a warning
2360                         --  later that Constraint_Error will be raised), and
2361                         --  the unconstrained case where sliding is permitted.
2362
2363                         elsif (Enumeration_Pos (CHi) - Enumeration_Pos (CLo))
2364                                  =
2365                               (Enumeration_Pos (AHi) - Enumeration_Pos (ALo))
2366                           and then Chars (ALo) /= Chars (CLo)
2367                           and then
2368                             not Is_Constrained (First_Subtype (Etype (N)))
2369                         then
2370                            Error_Msg_N
2371                              ("bounds of aggregate do not match target??", N);
2372                         end if;
2373                      end;
2374                   end if;
2375                end if;
2376
2377                --  If no others, aggregate bounds come from aggregate
2378
2379                Aggr_Low  := Choices_Low;
2380                Aggr_High := Choices_High;
2381             end if;
2382          end Step_2;
2383
2384       --  STEP 3: Process positional components
2385
2386       else
2387          --  STEP 3 (A): Process positional elements
2388
2389          Expr := First (Expressions (N));
2390          Nb_Elements := Uint_0;
2391          while Present (Expr) loop
2392             Nb_Elements := Nb_Elements + 1;
2393
2394             --  Ada 2005 (AI-231)
2395
2396             if Ada_Version >= Ada_2005
2397               and then Known_Null (Expr)
2398             then
2399                Check_Can_Never_Be_Null (Etype (N), Expr);
2400             end if;
2401
2402             if not Resolve_Aggr_Expr (Expr, Single_Elmt => True) then
2403                return Failure;
2404             end if;
2405
2406             --  Check incorrect use of dynamically tagged expression
2407
2408             if Is_Tagged_Type (Etype (Expr)) then
2409                Check_Dynamically_Tagged_Expression
2410                  (Expr => Expr,
2411                   Typ  => Component_Type (Etype (N)),
2412                   Related_Nod => N);
2413             end if;
2414
2415             Next (Expr);
2416          end loop;
2417
2418          if Others_Present then
2419             Assoc := Last (Component_Associations (N));
2420
2421             --  Ada 2005 (AI-231)
2422
2423             if Ada_Version >= Ada_2005
2424               and then Known_Null (Assoc)
2425             then
2426                Check_Can_Never_Be_Null (Etype (N), Expression (Assoc));
2427             end if;
2428
2429             --  Ada 2005 (AI-287): In case of default initialized component,
2430             --  we delay the resolution to the expansion phase.
2431
2432             if Box_Present (Assoc) then
2433
2434                --  Ada 2005 (AI-287): In case of default initialization of a
2435                --  component the expander will generate calls to the
2436                --  corresponding initialization subprogram. We need to call
2437                --  Resolve_Aggr_Expr to check the rules about
2438                --  dimensionality.
2439
2440                if not Resolve_Aggr_Expr (Assoc, Single_Elmt => False) then
2441                   return Failure;
2442                end if;
2443
2444             elsif not Resolve_Aggr_Expr (Expression (Assoc),
2445                                          Single_Elmt => False)
2446             then
2447                return Failure;
2448
2449             --  Check incorrect use of dynamically tagged expression. The
2450             --  expression of the others choice has not been resolved yet.
2451             --  In order to diagnose the semantic error we create a duplicate
2452             --  tree to analyze it and perform the check.
2453
2454             else
2455                declare
2456                   Save_Analysis : constant Boolean := Full_Analysis;
2457                   Expr          : constant Node_Id :=
2458                                     New_Copy_Tree (Expression (Assoc));
2459
2460                begin
2461                   Expander_Mode_Save_And_Set (False);
2462                   Full_Analysis := False;
2463                   Analyze (Expr);
2464                   Full_Analysis := Save_Analysis;
2465                   Expander_Mode_Restore;
2466
2467                   if Is_Tagged_Type (Etype (Expr)) then
2468                      Check_Dynamically_Tagged_Expression
2469                        (Expr => Expr,
2470                         Typ  => Component_Type (Etype (N)),
2471                         Related_Nod => N);
2472                   end if;
2473                end;
2474             end if;
2475          end if;
2476
2477          --  STEP 3 (B): Compute the aggregate bounds
2478
2479          if Others_Present then
2480             Get_Index_Bounds (Index_Constr, Aggr_Low, Aggr_High);
2481
2482          else
2483             if Others_Allowed then
2484                Get_Index_Bounds (Index_Constr, Aggr_Low, Discard);
2485             else
2486                Aggr_Low := Index_Typ_Low;
2487             end if;
2488
2489             Aggr_High := Add (Nb_Elements - 1, To => Aggr_Low);
2490             Check_Bound (Index_Base_High, Aggr_High);
2491          end if;
2492       end if;
2493
2494       --  STEP 4: Perform static aggregate checks and save the bounds
2495
2496       --  Check (A)
2497
2498       Check_Bounds (Index_Typ_Low, Index_Typ_High, Aggr_Low, Aggr_High);
2499       Check_Bounds (Index_Base_Low, Index_Base_High, Aggr_Low, Aggr_High);
2500
2501       --  Check (B)
2502
2503       if Others_Present and then Nb_Discrete_Choices > 0 then
2504          Check_Bounds (Aggr_Low, Aggr_High, Choices_Low, Choices_High);
2505          Check_Bounds (Index_Typ_Low, Index_Typ_High,
2506                        Choices_Low, Choices_High);
2507          Check_Bounds (Index_Base_Low, Index_Base_High,
2508                        Choices_Low, Choices_High);
2509
2510       --  Check (C)
2511
2512       elsif Others_Present and then Nb_Elements > 0 then
2513          Check_Length (Aggr_Low, Aggr_High, Nb_Elements);
2514          Check_Length (Index_Typ_Low, Index_Typ_High, Nb_Elements);
2515          Check_Length (Index_Base_Low, Index_Base_High, Nb_Elements);
2516       end if;
2517
2518       if Raises_Constraint_Error (Aggr_Low)
2519         or else Raises_Constraint_Error (Aggr_High)
2520       then
2521          Set_Raises_Constraint_Error (N);
2522       end if;
2523
2524       Aggr_Low := Duplicate_Subexpr (Aggr_Low);
2525
2526       --  Do not duplicate Aggr_High if Aggr_High = Aggr_Low + Nb_Elements
2527       --  since the addition node returned by Add is not yet analyzed. Attach
2528       --  to tree and analyze first. Reset analyzed flag to ensure it will get
2529       --  analyzed when it is a literal bound whose type must be properly set.
2530
2531       if Others_Present or else Nb_Discrete_Choices > 0 then
2532          Aggr_High := Duplicate_Subexpr (Aggr_High);
2533
2534          if Etype (Aggr_High) = Universal_Integer then
2535             Set_Analyzed (Aggr_High, False);
2536          end if;
2537       end if;
2538
2539       --  If the aggregate already has bounds attached to it, it means this is
2540       --  a positional aggregate created as an optimization by
2541       --  Exp_Aggr.Convert_To_Positional, so we don't want to change those
2542       --  bounds.
2543
2544       if Present (Aggregate_Bounds (N)) and then not Others_Allowed then
2545          Aggr_Low  := Low_Bound  (Aggregate_Bounds (N));
2546          Aggr_High := High_Bound (Aggregate_Bounds (N));
2547       end if;
2548
2549       Set_Aggregate_Bounds
2550         (N, Make_Range (Loc, Low_Bound => Aggr_Low, High_Bound => Aggr_High));
2551
2552       --  The bounds may contain expressions that must be inserted upwards.
2553       --  Attach them fully to the tree. After analysis, remove side effects
2554       --  from upper bound, if still needed.
2555
2556       Set_Parent (Aggregate_Bounds (N), N);
2557       Analyze_And_Resolve (Aggregate_Bounds (N), Index_Typ);
2558       Check_Unset_Reference (Aggregate_Bounds (N));
2559
2560       if not Others_Present and then Nb_Discrete_Choices = 0 then
2561          Set_High_Bound
2562            (Aggregate_Bounds (N),
2563             Duplicate_Subexpr (High_Bound (Aggregate_Bounds (N))));
2564       end if;
2565
2566       --  Check the dimensions of each component in the array aggregate
2567
2568       Analyze_Dimension_Array_Aggregate (N, Component_Typ);
2569
2570       return Success;
2571    end Resolve_Array_Aggregate;
2572
2573    ---------------------------------
2574    -- Resolve_Extension_Aggregate --
2575    ---------------------------------
2576
2577    --  There are two cases to consider:
2578
2579    --  a) If the ancestor part is a type mark, the components needed are the
2580    --  difference between the components of the expected type and the
2581    --  components of the given type mark.
2582
2583    --  b) If the ancestor part is an expression, it must be unambiguous, and
2584    --  once we have its type we can also compute the needed components as in
2585    --  the previous case. In both cases, if the ancestor type is not the
2586    --  immediate ancestor, we have to build this ancestor recursively.
2587
2588    --  In both cases, discriminants of the ancestor type do not play a role in
2589    --  the resolution of the needed components, because inherited discriminants
2590    --  cannot be used in a type extension. As a result we can compute
2591    --  independently the list of components of the ancestor type and of the
2592    --  expected type.
2593
2594    procedure Resolve_Extension_Aggregate (N : Node_Id; Typ : Entity_Id) is
2595       A      : constant Node_Id := Ancestor_Part (N);
2596       A_Type : Entity_Id;
2597       I      : Interp_Index;
2598       It     : Interp;
2599
2600       function Valid_Limited_Ancestor (Anc : Node_Id) return Boolean;
2601       --  If the type is limited, verify that the ancestor part is a legal
2602       --  expression (aggregate or function call, including 'Input)) that does
2603       --  not require a copy, as specified in 7.5(2).
2604
2605       function Valid_Ancestor_Type return Boolean;
2606       --  Verify that the type of the ancestor part is a non-private ancestor
2607       --  of the expected type, which must be a type extension.
2608
2609       ----------------------------
2610       -- Valid_Limited_Ancestor --
2611       ----------------------------
2612
2613       function Valid_Limited_Ancestor (Anc : Node_Id) return Boolean is
2614       begin
2615          if Is_Entity_Name (Anc)
2616            and then Is_Type (Entity (Anc))
2617          then
2618             return True;
2619
2620          elsif Nkind_In (Anc, N_Aggregate, N_Function_Call) then
2621             return True;
2622
2623          elsif Nkind (Anc) = N_Attribute_Reference
2624            and then Attribute_Name (Anc) = Name_Input
2625          then
2626             return True;
2627
2628          elsif Nkind (Anc) = N_Qualified_Expression then
2629             return Valid_Limited_Ancestor (Expression (Anc));
2630
2631          else
2632             return False;
2633          end if;
2634       end Valid_Limited_Ancestor;
2635
2636       -------------------------
2637       -- Valid_Ancestor_Type --
2638       -------------------------
2639
2640       function Valid_Ancestor_Type return Boolean is
2641          Imm_Type : Entity_Id;
2642
2643       begin
2644          Imm_Type := Base_Type (Typ);
2645          while Is_Derived_Type (Imm_Type) loop
2646             if Etype (Imm_Type) = Base_Type (A_Type) then
2647                return True;
2648
2649             --  The base type of the parent type may appear as  a private
2650             --  extension if it is declared as such in a parent unit of the
2651             --  current one. For consistency of the subsequent analysis use
2652             --  the partial view for the ancestor part.
2653
2654             elsif Is_Private_Type (Etype (Imm_Type))
2655               and then Present (Full_View (Etype (Imm_Type)))
2656               and then Base_Type (A_Type) = Full_View (Etype (Imm_Type))
2657             then
2658                A_Type := Etype (Imm_Type);
2659                return True;
2660
2661             --  The parent type may be a private extension. The aggregate is
2662             --  legal if the type of the aggregate is an extension of it that
2663             --  is not a private extension.
2664
2665             elsif Is_Private_Type (A_Type)
2666               and then not Is_Private_Type (Imm_Type)
2667               and then Present (Full_View (A_Type))
2668               and then Base_Type (Full_View (A_Type)) = Etype (Imm_Type)
2669             then
2670                return True;
2671
2672             else
2673                Imm_Type := Etype (Base_Type (Imm_Type));
2674             end if;
2675          end loop;
2676
2677          --  If previous loop did not find a proper ancestor, report error
2678
2679          Error_Msg_NE ("expect ancestor type of &", A, Typ);
2680          return False;
2681       end Valid_Ancestor_Type;
2682
2683    --  Start of processing for Resolve_Extension_Aggregate
2684
2685    begin
2686       --  Analyze the ancestor part and account for the case where it is a
2687       --  parameterless function call.
2688
2689       Analyze (A);
2690       Check_Parameterless_Call (A);
2691
2692       --  In SPARK, the ancestor part cannot be a type mark
2693
2694       if Is_Entity_Name (A)
2695         and then Is_Type (Entity (A))
2696       then
2697          Check_SPARK_Restriction ("ancestor part cannot be a type mark", A);
2698
2699          --  AI05-0115: if the ancestor part is a subtype mark, the ancestor
2700          --  must not have unknown discriminants.
2701
2702          if Has_Unknown_Discriminants (Root_Type (Typ)) then
2703             Error_Msg_NE
2704               ("aggregate not available for type& whose ancestor "
2705                  & "has unknown discriminants", N, Typ);
2706          end if;
2707       end if;
2708
2709       if not Is_Tagged_Type (Typ) then
2710          Error_Msg_N ("type of extension aggregate must be tagged", N);
2711          return;
2712
2713       elsif Is_Limited_Type (Typ) then
2714
2715          --  Ada 2005 (AI-287): Limited aggregates are allowed
2716
2717          if Ada_Version < Ada_2005 then
2718             Error_Msg_N ("aggregate type cannot be limited", N);
2719             Explain_Limited_Type (Typ, N);
2720             return;
2721
2722          elsif Valid_Limited_Ancestor (A) then
2723             null;
2724
2725          else
2726             Error_Msg_N
2727               ("limited ancestor part must be aggregate or function call", A);
2728          end if;
2729
2730       elsif Is_Class_Wide_Type (Typ) then
2731          Error_Msg_N ("aggregate cannot be of a class-wide type", N);
2732          return;
2733       end if;
2734
2735       if Is_Entity_Name (A)
2736         and then Is_Type (Entity (A))
2737       then
2738          A_Type := Get_Full_View (Entity (A));
2739
2740          if Valid_Ancestor_Type then
2741             Set_Entity (A, A_Type);
2742             Set_Etype  (A, A_Type);
2743
2744             Validate_Ancestor_Part (N);
2745             Resolve_Record_Aggregate (N, Typ);
2746          end if;
2747
2748       elsif Nkind (A) /= N_Aggregate then
2749          if Is_Overloaded (A) then
2750             A_Type := Any_Type;
2751
2752             Get_First_Interp (A, I, It);
2753             while Present (It.Typ) loop
2754                --  Only consider limited interpretations in the Ada 2005 case
2755
2756                if Is_Tagged_Type (It.Typ)
2757                  and then (Ada_Version >= Ada_2005
2758                             or else not Is_Limited_Type (It.Typ))
2759                then
2760                   if A_Type /= Any_Type then
2761                      Error_Msg_N ("cannot resolve expression", A);
2762                      return;
2763                   else
2764                      A_Type := It.Typ;
2765                   end if;
2766                end if;
2767
2768                Get_Next_Interp (I, It);
2769             end loop;
2770
2771             if A_Type = Any_Type then
2772                if Ada_Version >= Ada_2005 then
2773                   Error_Msg_N ("ancestor part must be of a tagged type", A);
2774                else
2775                   Error_Msg_N
2776                     ("ancestor part must be of a nonlimited tagged type", A);
2777                end if;
2778
2779                return;
2780             end if;
2781
2782          else
2783             A_Type := Etype (A);
2784          end if;
2785
2786          if Valid_Ancestor_Type then
2787             Resolve (A, A_Type);
2788             Check_Unset_Reference (A);
2789             Check_Non_Static_Context (A);
2790
2791             --  The aggregate is illegal if the ancestor expression is a call
2792             --  to a function with a limited unconstrained result, unless the
2793             --  type of the aggregate is a null extension. This restriction
2794             --  was added in AI05-67 to simplify implementation.
2795
2796             if Nkind (A) = N_Function_Call
2797               and then Is_Limited_Type (A_Type)
2798               and then not Is_Null_Extension (Typ)
2799               and then not Is_Constrained (A_Type)
2800             then
2801                Error_Msg_N
2802                  ("type of limited ancestor part must be constrained", A);
2803
2804             --  Reject the use of CPP constructors that leave objects partially
2805             --  initialized. For example:
2806
2807             --    type CPP_Root is tagged limited record ...
2808             --    pragma Import (CPP, CPP_Root);
2809
2810             --    type CPP_DT is new CPP_Root and Iface ...
2811             --    pragma Import (CPP, CPP_DT);
2812
2813             --    type Ada_DT is new CPP_DT with ...
2814
2815             --    Obj : Ada_DT := Ada_DT'(New_CPP_Root with others => <>);
2816
2817             --  Using the constructor of CPP_Root the slots of the dispatch
2818             --  table of CPP_DT cannot be set, and the secondary tag of
2819             --  CPP_DT is unknown.
2820
2821             elsif Nkind (A) = N_Function_Call
2822               and then Is_CPP_Constructor_Call (A)
2823               and then Enclosing_CPP_Parent (Typ) /= A_Type
2824             then
2825                Error_Msg_NE
2826                  ("??must use 'C'P'P constructor for type &", A,
2827                   Enclosing_CPP_Parent (Typ));
2828
2829                --  The following call is not needed if the previous warning
2830                --  is promoted to an error.
2831
2832                Resolve_Record_Aggregate (N, Typ);
2833
2834             elsif Is_Class_Wide_Type (Etype (A))
2835               and then Nkind (Original_Node (A)) = N_Function_Call
2836             then
2837                --  If the ancestor part is a dispatching call, it appears
2838                --  statically to be a legal ancestor, but it yields any member
2839                --  of the class, and it is not possible to determine whether
2840                --  it is an ancestor of the extension aggregate (much less
2841                --  which ancestor). It is not possible to determine the
2842                --  components of the extension part.
2843
2844                --  This check implements AI-306, which in fact was motivated by
2845                --  an AdaCore query to the ARG after this test was added.
2846
2847                Error_Msg_N ("ancestor part must be statically tagged", A);
2848             else
2849                Resolve_Record_Aggregate (N, Typ);
2850             end if;
2851          end if;
2852
2853       else
2854          Error_Msg_N ("no unique type for this aggregate",  A);
2855       end if;
2856
2857       Check_Function_Writable_Actuals (N);
2858    end Resolve_Extension_Aggregate;
2859
2860    ------------------------------
2861    -- Resolve_Record_Aggregate --
2862    ------------------------------
2863
2864    procedure Resolve_Record_Aggregate (N : Node_Id; Typ : Entity_Id) is
2865       Assoc : Node_Id;
2866       --  N_Component_Association node belonging to the input aggregate N
2867
2868       Expr            : Node_Id;
2869       Positional_Expr : Node_Id;
2870       Component       : Entity_Id;
2871       Component_Elmt  : Elmt_Id;
2872
2873       Components : constant Elist_Id := New_Elmt_List;
2874       --  Components is the list of the record components whose value must be
2875       --  provided in the aggregate. This list does include discriminants.
2876
2877       New_Assoc_List : constant List_Id := New_List;
2878       New_Assoc      : Node_Id;
2879       --  New_Assoc_List is the newly built list of N_Component_Association
2880       --  nodes. New_Assoc is one such N_Component_Association node in it.
2881       --  Note that while Assoc and New_Assoc contain the same kind of nodes,
2882       --  they are used to iterate over two different N_Component_Association
2883       --  lists.
2884
2885       Others_Etype : Entity_Id := Empty;
2886       --  This variable is used to save the Etype of the last record component
2887       --  that takes its value from the others choice. Its purpose is:
2888       --
2889       --    (a) make sure the others choice is useful
2890       --
2891       --    (b) make sure the type of all the components whose value is
2892       --        subsumed by the others choice are the same.
2893       --
2894       --  This variable is updated as a side effect of function Get_Value.
2895
2896       Is_Box_Present : Boolean := False;
2897       Others_Box     : Boolean := False;
2898       --  Ada 2005 (AI-287): Variables used in case of default initialization
2899       --  to provide a functionality similar to Others_Etype. Box_Present
2900       --  indicates that the component takes its default initialization;
2901       --  Others_Box indicates that at least one component takes its default
2902       --  initialization. Similar to Others_Etype, they are also updated as a
2903       --  side effect of function Get_Value.
2904
2905       procedure Add_Association
2906         (Component      : Entity_Id;
2907          Expr           : Node_Id;
2908          Assoc_List     : List_Id;
2909          Is_Box_Present : Boolean := False);
2910       --  Builds a new N_Component_Association node which associates Component
2911       --  to expression Expr and adds it to the association list being built,
2912       --  either New_Assoc_List, or the association being built for an inner
2913       --  aggregate.
2914
2915       function Discr_Present (Discr : Entity_Id) return Boolean;
2916       --  If aggregate N is a regular aggregate this routine will return True.
2917       --  Otherwise, if N is an extension aggregate, Discr is a discriminant
2918       --  whose value may already have been specified by N's ancestor part.
2919       --  This routine checks whether this is indeed the case and if so returns
2920       --  False, signaling that no value for Discr should appear in N's
2921       --  aggregate part. Also, in this case, the routine appends to
2922       --  New_Assoc_List the discriminant value specified in the ancestor part.
2923       --
2924       --  If the aggregate is in a context with expansion delayed, it will be
2925       --  reanalyzed. The inherited discriminant values must not be reinserted
2926       --  in the component list to prevent spurious errors, but they must be
2927       --  present on first analysis to build the proper subtype indications.
2928       --  The flag Inherited_Discriminant is used to prevent the re-insertion.
2929
2930       function Get_Value
2931         (Compon                 : Node_Id;
2932          From                   : List_Id;
2933          Consider_Others_Choice : Boolean := False)
2934          return                   Node_Id;
2935       --  Given a record component stored in parameter Compon, this function
2936       --  returns its value as it appears in the list From, which is a list
2937       --  of N_Component_Association nodes.
2938       --
2939       --  If no component association has a choice for the searched component,
2940       --  the value provided by the others choice is returned, if there is one,
2941       --  and Consider_Others_Choice is set to true. Otherwise Empty is
2942       --  returned. If there is more than one component association giving a
2943       --  value for the searched record component, an error message is emitted
2944       --  and the first found value is returned.
2945       --
2946       --  If Consider_Others_Choice is set and the returned expression comes
2947       --  from the others choice, then Others_Etype is set as a side effect.
2948       --  An error message is emitted if the components taking their value from
2949       --  the others choice do not have same type.
2950
2951       function New_Copy_Tree_And_Copy_Dimensions
2952         (Source    : Node_Id;
2953          Map       : Elist_Id   := No_Elist;
2954          New_Sloc  : Source_Ptr := No_Location;
2955          New_Scope : Entity_Id  := Empty) return Node_Id;
2956       --  Same as New_Copy_Tree (defined in Sem_Util), except that this routine
2957       --  also copies the dimensions of Source to the returned node.
2958
2959       procedure Resolve_Aggr_Expr (Expr : Node_Id; Component : Node_Id);
2960       --  Analyzes and resolves expression Expr against the Etype of the
2961       --  Component. This routine also applies all appropriate checks to Expr.
2962       --  It finally saves a Expr in the newly created association list that
2963       --  will be attached to the final record aggregate. Note that if the
2964       --  Parent pointer of Expr is not set then Expr was produced with a
2965       --  New_Copy_Tree or some such.
2966
2967       ---------------------
2968       -- Add_Association --
2969       ---------------------
2970
2971       procedure Add_Association
2972         (Component      : Entity_Id;
2973          Expr           : Node_Id;
2974          Assoc_List     : List_Id;
2975          Is_Box_Present : Boolean := False)
2976       is
2977          Loc : Source_Ptr;
2978          Choice_List : constant List_Id := New_List;
2979          New_Assoc   : Node_Id;
2980
2981       begin
2982          --  If this is a box association the expression is missing, so
2983          --  use the Sloc of the aggregate itself for the new association.
2984
2985          if Present (Expr) then
2986             Loc := Sloc (Expr);
2987          else
2988             Loc := Sloc (N);
2989          end if;
2990
2991          Append (New_Occurrence_Of (Component, Loc), Choice_List);
2992          New_Assoc :=
2993            Make_Component_Association (Loc,
2994              Choices     => Choice_List,
2995              Expression  => Expr,
2996              Box_Present => Is_Box_Present);
2997          Append (New_Assoc, Assoc_List);
2998       end Add_Association;
2999
3000       -------------------
3001       -- Discr_Present --
3002       -------------------
3003
3004       function Discr_Present (Discr : Entity_Id) return Boolean is
3005          Regular_Aggr : constant Boolean := Nkind (N) /= N_Extension_Aggregate;
3006
3007          Loc : Source_Ptr;
3008
3009          Ancestor     : Node_Id;
3010          Comp_Assoc   : Node_Id;
3011          Discr_Expr   : Node_Id;
3012
3013          Ancestor_Typ : Entity_Id;
3014          Orig_Discr   : Entity_Id;
3015          D            : Entity_Id;
3016          D_Val        : Elmt_Id := No_Elmt; -- stop junk warning
3017
3018          Ancestor_Is_Subtyp : Boolean;
3019
3020       begin
3021          if Regular_Aggr then
3022             return True;
3023          end if;
3024
3025          --  Check whether inherited discriminant values have already been
3026          --  inserted in the aggregate. This will be the case if we are
3027          --  re-analyzing an aggregate whose expansion was delayed.
3028
3029          if Present (Component_Associations (N)) then
3030             Comp_Assoc := First (Component_Associations (N));
3031             while Present (Comp_Assoc) loop
3032                if Inherited_Discriminant (Comp_Assoc) then
3033                   return True;
3034                end if;
3035
3036                Next (Comp_Assoc);
3037             end loop;
3038          end if;
3039
3040          Ancestor     := Ancestor_Part (N);
3041          Ancestor_Typ := Etype (Ancestor);
3042          Loc          := Sloc (Ancestor);
3043
3044          --  For a private type with unknown discriminants, use the underlying
3045          --  record view if it is available.
3046
3047          if Has_Unknown_Discriminants (Ancestor_Typ)
3048            and then Present (Full_View (Ancestor_Typ))
3049            and then Present (Underlying_Record_View (Full_View (Ancestor_Typ)))
3050          then
3051             Ancestor_Typ := Underlying_Record_View (Full_View (Ancestor_Typ));
3052          end if;
3053
3054          Ancestor_Is_Subtyp :=
3055            Is_Entity_Name (Ancestor) and then Is_Type (Entity (Ancestor));
3056
3057          --  If the ancestor part has no discriminants clearly N's aggregate
3058          --  part must provide a value for Discr.
3059
3060          if not Has_Discriminants (Ancestor_Typ) then
3061             return True;
3062
3063          --  If the ancestor part is an unconstrained subtype mark then the
3064          --  Discr must be present in N's aggregate part.
3065
3066          elsif Ancestor_Is_Subtyp
3067            and then not Is_Constrained (Entity (Ancestor))
3068          then
3069             return True;
3070          end if;
3071
3072          --  Now look to see if Discr was specified in the ancestor part
3073
3074          if Ancestor_Is_Subtyp then
3075             D_Val := First_Elmt (Discriminant_Constraint (Entity (Ancestor)));
3076          end if;
3077
3078          Orig_Discr := Original_Record_Component (Discr);
3079
3080          D := First_Discriminant (Ancestor_Typ);
3081          while Present (D) loop
3082
3083             --  If Ancestor has already specified Disc value then insert its
3084             --  value in the final aggregate.
3085
3086             if Original_Record_Component (D) = Orig_Discr then
3087                if Ancestor_Is_Subtyp then
3088                   Discr_Expr := New_Copy_Tree (Node (D_Val));
3089                else
3090                   Discr_Expr :=
3091                     Make_Selected_Component (Loc,
3092                       Prefix        => Duplicate_Subexpr (Ancestor),
3093                       Selector_Name => New_Occurrence_Of (Discr, Loc));
3094                end if;
3095
3096                Resolve_Aggr_Expr (Discr_Expr, Discr);
3097                Set_Inherited_Discriminant (Last (New_Assoc_List));
3098                return False;
3099             end if;
3100
3101             Next_Discriminant (D);
3102
3103             if Ancestor_Is_Subtyp then
3104                Next_Elmt (D_Val);
3105             end if;
3106          end loop;
3107
3108          return True;
3109       end Discr_Present;
3110
3111       ---------------
3112       -- Get_Value --
3113       ---------------
3114
3115       function Get_Value
3116         (Compon                 : Node_Id;
3117          From                   : List_Id;
3118          Consider_Others_Choice : Boolean := False)
3119          return                   Node_Id
3120       is
3121          Assoc         : Node_Id;
3122          Expr          : Node_Id := Empty;
3123          Selector_Name : Node_Id;
3124
3125       begin
3126          Is_Box_Present := False;
3127
3128          if Present (From) then
3129             Assoc := First (From);
3130          else
3131             return Empty;
3132          end if;
3133
3134          while Present (Assoc) loop
3135             Selector_Name := First (Choices (Assoc));
3136             while Present (Selector_Name) loop
3137                if Nkind (Selector_Name) = N_Others_Choice then
3138                   if Consider_Others_Choice and then No (Expr) then
3139
3140                      --  We need to duplicate the expression for each
3141                      --  successive component covered by the others choice.
3142                      --  This is redundant if the others_choice covers only
3143                      --  one component (small optimization possible???), but
3144                      --  indispensable otherwise, because each one must be
3145                      --  expanded individually to preserve side-effects.
3146
3147                      --  Ada 2005 (AI-287): In case of default initialization
3148                      --  of components, we duplicate the corresponding default
3149                      --  expression (from the record type declaration). The
3150                      --  copy must carry the sloc of the association (not the
3151                      --  original expression) to prevent spurious elaboration
3152                      --  checks when the default includes function calls.
3153
3154                      if Box_Present (Assoc) then
3155                         Others_Box     := True;
3156                         Is_Box_Present := True;
3157
3158                         if Expander_Active then
3159                            return
3160                              New_Copy_Tree_And_Copy_Dimensions
3161                                (Expression (Parent (Compon)),
3162                                 New_Sloc => Sloc (Assoc));
3163                         else
3164                            return Expression (Parent (Compon));
3165                         end if;
3166
3167                      else
3168                         if Present (Others_Etype) and then
3169                            Base_Type (Others_Etype) /= Base_Type (Etype
3170                                                                    (Compon))
3171                         then
3172                            Error_Msg_N ("components in OTHERS choice must " &
3173                                         "have same type", Selector_Name);
3174                         end if;
3175
3176                         Others_Etype := Etype (Compon);
3177
3178                         if Expander_Active then
3179                            return
3180                              New_Copy_Tree_And_Copy_Dimensions
3181                                (Expression (Assoc));
3182                         else
3183                            return Expression (Assoc);
3184                         end if;
3185                      end if;
3186                   end if;
3187
3188                elsif Chars (Compon) = Chars (Selector_Name) then
3189                   if No (Expr) then
3190
3191                      --  Ada 2005 (AI-231)
3192
3193                      if Ada_Version >= Ada_2005
3194                        and then Known_Null (Expression (Assoc))
3195                      then
3196                         Check_Can_Never_Be_Null (Compon, Expression (Assoc));
3197                      end if;
3198
3199                      --  We need to duplicate the expression when several
3200                      --  components are grouped together with a "|" choice.
3201                      --  For instance "filed1 | filed2 => Expr"
3202
3203                      --  Ada 2005 (AI-287)
3204
3205                      if Box_Present (Assoc) then
3206                         Is_Box_Present := True;
3207
3208                         --  Duplicate the default expression of the component
3209                         --  from the record type declaration, so a new copy
3210                         --  can be attached to the association.
3211
3212                         --  Note that we always copy the default expression,
3213                         --  even when the association has a single choice, in
3214                         --  order to create a proper association for the
3215                         --  expanded aggregate.
3216
3217                         --  Component may have no default, in which case the
3218                         --  expression is empty and the component is default-
3219                         --  initialized, but an association for the component
3220                         --  exists, and it is not covered by an others clause.
3221
3222                         return
3223                           New_Copy_Tree_And_Copy_Dimensions
3224                             (Expression (Parent (Compon)));
3225
3226                      else
3227                         if Present (Next (Selector_Name)) then
3228                            Expr :=
3229                              New_Copy_Tree_And_Copy_Dimensions
3230                                (Expression (Assoc));
3231                         else
3232                            Expr := Expression (Assoc);
3233                         end if;
3234                      end if;
3235
3236                      Generate_Reference (Compon, Selector_Name, 'm');
3237
3238                   else
3239                      Error_Msg_NE
3240                        ("more than one value supplied for &",
3241                         Selector_Name, Compon);
3242
3243                   end if;
3244                end if;
3245
3246                Next (Selector_Name);
3247             end loop;
3248
3249             Next (Assoc);
3250          end loop;
3251
3252          return Expr;
3253       end Get_Value;
3254
3255       ---------------------------------------
3256       -- New_Copy_Tree_And_Copy_Dimensions --
3257       ---------------------------------------
3258
3259       function New_Copy_Tree_And_Copy_Dimensions
3260         (Source    : Node_Id;
3261          Map       : Elist_Id   := No_Elist;
3262          New_Sloc  : Source_Ptr := No_Location;
3263          New_Scope : Entity_Id  := Empty) return Node_Id
3264       is
3265          New_Copy : constant Node_Id :=
3266                       New_Copy_Tree (Source, Map, New_Sloc, New_Scope);
3267       begin
3268          --  Move the dimensions of Source to New_Copy
3269
3270          Copy_Dimensions (Source, New_Copy);
3271          return New_Copy;
3272       end New_Copy_Tree_And_Copy_Dimensions;
3273
3274       -----------------------
3275       -- Resolve_Aggr_Expr --
3276       -----------------------
3277
3278       procedure Resolve_Aggr_Expr (Expr : Node_Id; Component : Node_Id) is
3279          Expr_Type : Entity_Id := Empty;
3280          New_C     : Entity_Id := Component;
3281          New_Expr  : Node_Id;
3282
3283          function Has_Expansion_Delayed (Expr : Node_Id) return Boolean;
3284          --  If the expression is an aggregate (possibly qualified) then its
3285          --  expansion is delayed until the enclosing aggregate is expanded
3286          --  into assignments. In that case, do not generate checks on the
3287          --  expression, because they will be generated later, and will other-
3288          --  wise force a copy (to remove side-effects) that would leave a
3289          --  dynamic-sized aggregate in the code, something that gigi cannot
3290          --  handle.
3291
3292          Relocate : Boolean;
3293          --  Set to True if the resolved Expr node needs to be relocated when
3294          --  attached to the newly created association list. This node need not
3295          --  be relocated if its parent pointer is not set. In fact in this
3296          --  case Expr is the output of a New_Copy_Tree call. If Relocate is
3297          --  True then we have analyzed the expression node in the original
3298          --  aggregate and hence it needs to be relocated when moved over to
3299          --  the new association list.
3300
3301          ---------------------------
3302          -- Has_Expansion_Delayed --
3303          ---------------------------
3304
3305          function Has_Expansion_Delayed (Expr : Node_Id) return Boolean is
3306             Kind : constant Node_Kind := Nkind (Expr);
3307          begin
3308             return (Nkind_In (Kind, N_Aggregate, N_Extension_Aggregate)
3309                      and then Present (Etype (Expr))
3310                      and then Is_Record_Type (Etype (Expr))
3311                      and then Expansion_Delayed (Expr))
3312               or else (Kind = N_Qualified_Expression
3313                         and then Has_Expansion_Delayed (Expression (Expr)));
3314          end Has_Expansion_Delayed;
3315
3316       --  Start of processing for Resolve_Aggr_Expr
3317
3318       begin
3319          --  If the type of the component is elementary or the type of the
3320          --  aggregate does not contain discriminants, use the type of the
3321          --  component to resolve Expr.
3322
3323          if Is_Elementary_Type (Etype (Component))
3324            or else not Has_Discriminants (Etype (N))
3325          then
3326             Expr_Type := Etype (Component);
3327
3328          --  Otherwise we have to pick up the new type of the component from
3329          --  the new constrained subtype of the aggregate. In fact components
3330          --  which are of a composite type might be constrained by a
3331          --  discriminant, and we want to resolve Expr against the subtype were
3332          --  all discriminant occurrences are replaced with their actual value.
3333
3334          else
3335             New_C := First_Component (Etype (N));
3336             while Present (New_C) loop
3337                if Chars (New_C) = Chars (Component) then
3338                   Expr_Type := Etype (New_C);
3339                   exit;
3340                end if;
3341
3342                Next_Component (New_C);
3343             end loop;
3344
3345             pragma Assert (Present (Expr_Type));
3346
3347             --  For each range in an array type where a discriminant has been
3348             --  replaced with the constraint, check that this range is within
3349             --  the range of the base type. This checks is done in the init
3350             --  proc for regular objects, but has to be done here for
3351             --  aggregates since no init proc is called for them.
3352
3353             if Is_Array_Type (Expr_Type) then
3354                declare
3355                   Index : Node_Id;
3356                   --  Range of the current constrained index in the array
3357
3358                   Orig_Index : Node_Id := First_Index (Etype (Component));
3359                   --  Range corresponding to the range Index above in the
3360                   --  original unconstrained record type. The bounds of this
3361                   --  range may be governed by discriminants.
3362
3363                   Unconstr_Index : Node_Id := First_Index (Etype (Expr_Type));
3364                   --  Range corresponding to the range Index above for the
3365                   --  unconstrained array type. This range is needed to apply
3366                   --  range checks.
3367
3368                begin
3369                   Index := First_Index (Expr_Type);
3370                   while Present (Index) loop
3371                      if Depends_On_Discriminant (Orig_Index) then
3372                         Apply_Range_Check (Index, Etype (Unconstr_Index));
3373                      end if;
3374
3375                      Next_Index (Index);
3376                      Next_Index (Orig_Index);
3377                      Next_Index (Unconstr_Index);
3378                   end loop;
3379                end;
3380             end if;
3381          end if;
3382
3383          --  If the Parent pointer of Expr is not set, Expr is an expression
3384          --  duplicated by New_Tree_Copy (this happens for record aggregates
3385          --  that look like (Field1 | Filed2 => Expr) or (others => Expr)).
3386          --  Such a duplicated expression must be attached to the tree
3387          --  before analysis and resolution to enforce the rule that a tree
3388          --  fragment should never be analyzed or resolved unless it is
3389          --  attached to the current compilation unit.
3390
3391          if No (Parent (Expr)) then
3392             Set_Parent (Expr, N);
3393             Relocate := False;
3394          else
3395             Relocate := True;
3396          end if;
3397
3398          Analyze_And_Resolve (Expr, Expr_Type);
3399          Check_Expr_OK_In_Limited_Aggregate (Expr);
3400          Check_Non_Static_Context (Expr);
3401          Check_Unset_Reference (Expr);
3402
3403          --  Check wrong use of class-wide types
3404
3405          if Is_Class_Wide_Type (Etype (Expr)) then
3406             Error_Msg_N ("dynamically tagged expression not allowed", Expr);
3407          end if;
3408
3409          if not Has_Expansion_Delayed (Expr) then
3410             Aggregate_Constraint_Checks (Expr, Expr_Type);
3411          end if;
3412
3413          --  If an aggregate component has a type with predicates, an explicit
3414          --  predicate check must be applied, as for an assignment statement,
3415          --  because the aggegate might not be expanded into individual
3416          --  component assignments.
3417
3418          if Present (Predicate_Function (Expr_Type)) then
3419             Apply_Predicate_Check (Expr, Expr_Type);
3420          end if;
3421
3422          if Raises_Constraint_Error (Expr) then
3423             Set_Raises_Constraint_Error (N);
3424          end if;
3425
3426          --  If the expression has been marked as requiring a range check, then
3427          --  generate it here.
3428
3429          if Do_Range_Check (Expr) then
3430             Set_Do_Range_Check (Expr, False);
3431             Generate_Range_Check (Expr, Expr_Type, CE_Range_Check_Failed);
3432          end if;
3433
3434          if Relocate then
3435             New_Expr := Relocate_Node (Expr);
3436
3437             --  Since New_Expr is not gonna be analyzed later on, we need to
3438             --  propagate here the dimensions form Expr to New_Expr.
3439
3440             Copy_Dimensions (Expr, New_Expr);
3441
3442          else
3443             New_Expr := Expr;
3444          end if;
3445
3446          Add_Association (New_C, New_Expr, New_Assoc_List);
3447       end Resolve_Aggr_Expr;
3448
3449    --  Start of processing for Resolve_Record_Aggregate
3450
3451    begin
3452       --  A record aggregate is restricted in SPARK:
3453
3454       --    Each named association can have only a single choice.
3455       --    OTHERS cannot be used.
3456       --    Positional and named associations cannot be mixed.
3457
3458       if Present (Component_Associations (N))
3459         and then Present (First (Component_Associations (N)))
3460       then
3461
3462          if Present (Expressions (N)) then
3463             Check_SPARK_Restriction
3464               ("named association cannot follow positional one",
3465                First (Choices (First (Component_Associations (N)))));
3466          end if;
3467
3468          declare
3469             Assoc : Node_Id;
3470
3471          begin
3472             Assoc := First (Component_Associations (N));
3473             while Present (Assoc) loop
3474                if List_Length (Choices (Assoc)) > 1 then
3475                   Check_SPARK_Restriction
3476                     ("component association in record aggregate must "
3477                      & "contain a single choice", Assoc);
3478                end if;
3479
3480                if Nkind (First (Choices (Assoc))) = N_Others_Choice then
3481                   Check_SPARK_Restriction
3482                     ("record aggregate cannot contain OTHERS", Assoc);
3483                end if;
3484
3485                Assoc := Next (Assoc);
3486             end loop;
3487          end;
3488       end if;
3489
3490       --  We may end up calling Duplicate_Subexpr on expressions that are
3491       --  attached to New_Assoc_List. For this reason we need to attach it
3492       --  to the tree by setting its parent pointer to N. This parent point
3493       --  will change in STEP 8 below.
3494
3495       Set_Parent (New_Assoc_List, N);
3496
3497       --  STEP 1: abstract type and null record verification
3498
3499       if Is_Abstract_Type (Typ) then
3500          Error_Msg_N ("type of aggregate cannot be abstract",  N);
3501       end if;
3502
3503       if No (First_Entity (Typ)) and then Null_Record_Present (N) then
3504          Set_Etype (N, Typ);
3505          return;
3506
3507       elsif Present (First_Entity (Typ))
3508         and then Null_Record_Present (N)
3509         and then not Is_Tagged_Type (Typ)
3510       then
3511          Error_Msg_N ("record aggregate cannot be null", N);
3512          return;
3513
3514       --  If the type has no components, then the aggregate should either
3515       --  have "null record", or in Ada 2005 it could instead have a single
3516       --  component association given by "others => <>". For Ada 95 we flag an
3517       --  error at this point, but for Ada 2005 we proceed with checking the
3518       --  associations below, which will catch the case where it's not an
3519       --  aggregate with "others => <>". Note that the legality of a <>
3520       --  aggregate for a null record type was established by AI05-016.
3521
3522       elsif No (First_Entity (Typ))
3523          and then Ada_Version < Ada_2005
3524       then
3525          Error_Msg_N ("record aggregate must be null", N);
3526          return;
3527       end if;
3528
3529       --  STEP 2: Verify aggregate structure
3530
3531       Step_2 : declare
3532          Selector_Name : Node_Id;
3533          Bad_Aggregate : Boolean := False;
3534
3535       begin
3536          if Present (Component_Associations (N)) then
3537             Assoc := First (Component_Associations (N));
3538          else
3539             Assoc := Empty;
3540          end if;
3541
3542          while Present (Assoc) loop
3543             Selector_Name := First (Choices (Assoc));
3544             while Present (Selector_Name) loop
3545                if Nkind (Selector_Name) = N_Identifier then
3546                   null;
3547
3548                elsif Nkind (Selector_Name) = N_Others_Choice then
3549                   if Selector_Name /= First (Choices (Assoc))
3550                     or else Present (Next (Selector_Name))
3551                   then
3552                      Error_Msg_N
3553                        ("OTHERS must appear alone in a choice list",
3554                         Selector_Name);
3555                      return;
3556
3557                   elsif Present (Next (Assoc)) then
3558                      Error_Msg_N
3559                        ("OTHERS must appear last in an aggregate",
3560                         Selector_Name);
3561                      return;
3562
3563                   --  (Ada 2005): If this is an association with a box,
3564                   --  indicate that the association need not represent
3565                   --  any component.
3566
3567                   elsif Box_Present (Assoc) then
3568                      Others_Box := True;
3569                   end if;
3570
3571                else
3572                   Error_Msg_N
3573                     ("selector name should be identifier or OTHERS",
3574                      Selector_Name);
3575                   Bad_Aggregate := True;
3576                end if;
3577
3578                Next (Selector_Name);
3579             end loop;
3580
3581             Next (Assoc);
3582          end loop;
3583
3584          if Bad_Aggregate then
3585             return;
3586          end if;
3587       end Step_2;
3588
3589       --  STEP 3: Find discriminant Values
3590
3591       Step_3 : declare
3592          Discrim               : Entity_Id;
3593          Missing_Discriminants : Boolean := False;
3594
3595       begin
3596          if Present (Expressions (N)) then
3597             Positional_Expr := First (Expressions (N));
3598          else
3599             Positional_Expr := Empty;
3600          end if;
3601
3602          --  AI05-0115: if the ancestor part is a subtype mark, the ancestor
3603          --  must not have unknown discriminants.
3604
3605          if Is_Derived_Type (Typ)
3606            and then Has_Unknown_Discriminants (Root_Type (Typ))
3607            and then Nkind (N) /= N_Extension_Aggregate
3608          then
3609             Error_Msg_NE
3610               ("aggregate not available for type& whose ancestor "
3611                  & "has unknown discriminants ", N, Typ);
3612          end if;
3613
3614          if Has_Unknown_Discriminants (Typ)
3615            and then Present (Underlying_Record_View (Typ))
3616          then
3617             Discrim := First_Discriminant (Underlying_Record_View (Typ));
3618          elsif Has_Discriminants (Typ) then
3619             Discrim := First_Discriminant (Typ);
3620          else
3621             Discrim := Empty;
3622          end if;
3623
3624          --  First find the discriminant values in the positional components
3625
3626          while Present (Discrim) and then Present (Positional_Expr) loop
3627             if Discr_Present (Discrim) then
3628                Resolve_Aggr_Expr (Positional_Expr, Discrim);
3629
3630                --  Ada 2005 (AI-231)
3631
3632                if Ada_Version >= Ada_2005
3633                  and then Known_Null (Positional_Expr)
3634                then
3635                   Check_Can_Never_Be_Null (Discrim, Positional_Expr);
3636                end if;
3637
3638                Next (Positional_Expr);
3639             end if;
3640
3641             if Present (Get_Value (Discrim, Component_Associations (N))) then
3642                Error_Msg_NE
3643                  ("more than one value supplied for discriminant&",
3644                   N, Discrim);
3645             end if;
3646
3647             Next_Discriminant (Discrim);
3648          end loop;
3649
3650          --  Find remaining discriminant values if any among named components
3651
3652          while Present (Discrim) loop
3653             Expr := Get_Value (Discrim, Component_Associations (N), True);
3654
3655             if not Discr_Present (Discrim) then
3656                if Present (Expr) then
3657                   Error_Msg_NE
3658                     ("more than one value supplied for discriminant&",
3659                      N, Discrim);
3660                end if;
3661
3662             elsif No (Expr) then
3663                Error_Msg_NE
3664                  ("no value supplied for discriminant &", N, Discrim);
3665                Missing_Discriminants := True;
3666
3667             else
3668                Resolve_Aggr_Expr (Expr, Discrim);
3669             end if;
3670
3671             Next_Discriminant (Discrim);
3672          end loop;
3673
3674          if Missing_Discriminants then
3675             return;
3676          end if;
3677
3678          --  At this point and until the beginning of STEP 6, New_Assoc_List
3679          --  contains only the discriminants and their values.
3680
3681       end Step_3;
3682
3683       --  STEP 4: Set the Etype of the record aggregate
3684
3685       --  ??? This code is pretty much a copy of Sem_Ch3.Build_Subtype. That
3686       --  routine should really be exported in sem_util or some such and used
3687       --  in sem_ch3 and here rather than have a copy of the code which is a
3688       --  maintenance nightmare.
3689
3690       --  ??? Performance WARNING. The current implementation creates a new
3691       --  itype for all aggregates whose base type is discriminated. This means
3692       --  that for record aggregates nested inside an array aggregate we will
3693       --  create a new itype for each record aggregate if the array component
3694       --  type has discriminants. For large aggregates this may be a problem.
3695       --  What should be done in this case is to reuse itypes as much as
3696       --  possible.
3697
3698       if Has_Discriminants (Typ)
3699         or else (Has_Unknown_Discriminants (Typ)
3700                    and then Present (Underlying_Record_View (Typ)))
3701       then
3702          Build_Constrained_Itype : declare
3703             Loc         : constant Source_Ptr := Sloc (N);
3704             Indic       : Node_Id;
3705             Subtyp_Decl : Node_Id;
3706             Def_Id      : Entity_Id;
3707
3708             C : constant List_Id := New_List;
3709
3710          begin
3711             New_Assoc := First (New_Assoc_List);
3712             while Present (New_Assoc) loop
3713                Append (Duplicate_Subexpr (Expression (New_Assoc)), To => C);
3714                Next (New_Assoc);
3715             end loop;
3716
3717             if Has_Unknown_Discriminants (Typ)
3718               and then Present (Underlying_Record_View (Typ))
3719             then
3720                Indic :=
3721                  Make_Subtype_Indication (Loc,
3722                    Subtype_Mark =>
3723                      New_Occurrence_Of (Underlying_Record_View (Typ), Loc),
3724                    Constraint  =>
3725                      Make_Index_Or_Discriminant_Constraint (Loc, C));
3726             else
3727                Indic :=
3728                  Make_Subtype_Indication (Loc,
3729                    Subtype_Mark =>
3730                      New_Occurrence_Of (Base_Type (Typ), Loc),
3731                    Constraint  =>
3732                      Make_Index_Or_Discriminant_Constraint (Loc, C));
3733             end if;
3734
3735             Def_Id := Create_Itype (Ekind (Typ), N);
3736
3737             Subtyp_Decl :=
3738               Make_Subtype_Declaration (Loc,
3739                 Defining_Identifier => Def_Id,
3740                 Subtype_Indication  => Indic);
3741             Set_Parent (Subtyp_Decl, Parent (N));
3742
3743             --  Itypes must be analyzed with checks off (see itypes.ads)
3744
3745             Analyze (Subtyp_Decl, Suppress => All_Checks);
3746
3747             Set_Etype (N, Def_Id);
3748             Check_Static_Discriminated_Subtype
3749               (Def_Id, Expression (First (New_Assoc_List)));
3750          end Build_Constrained_Itype;
3751
3752       else
3753          Set_Etype (N, Typ);
3754       end if;
3755
3756       --  STEP 5: Get remaining components according to discriminant values
3757
3758       Step_5 : declare
3759          Record_Def      : Node_Id;
3760          Parent_Typ      : Entity_Id;
3761          Root_Typ        : Entity_Id;
3762          Parent_Typ_List : Elist_Id;
3763          Parent_Elmt     : Elmt_Id;
3764          Errors_Found    : Boolean := False;
3765          Dnode           : Node_Id;
3766
3767          function Find_Private_Ancestor return Entity_Id;
3768          --  AI05-0115: Find earlier ancestor in the derivation chain that is
3769          --  derived from a private view. Whether the aggregate is legal
3770          --  depends on the current visibility of the type as well as that
3771          --  of the parent of the ancestor.
3772
3773          ---------------------------
3774          -- Find_Private_Ancestor --
3775          ---------------------------
3776
3777          function Find_Private_Ancestor return Entity_Id is
3778             Par : Entity_Id;
3779          begin
3780             Par := Typ;
3781             loop
3782                if Has_Private_Ancestor (Par)
3783                  and then not Has_Private_Ancestor (Etype (Base_Type (Par)))
3784                then
3785                   return Par;
3786
3787                elsif not Is_Derived_Type (Par) then
3788                   return Empty;
3789
3790                else
3791                   Par := Etype (Base_Type (Par));
3792                end if;
3793             end loop;
3794          end Find_Private_Ancestor;
3795
3796       --  Start of processing for Step_5
3797
3798       begin
3799          if Is_Derived_Type (Typ) and then Is_Tagged_Type (Typ) then
3800             Parent_Typ_List := New_Elmt_List;
3801
3802             --  If this is an extension aggregate, the component list must
3803             --  include all components that are not in the given ancestor type.
3804             --  Otherwise, the component list must include components of all
3805             --  ancestors, starting with the root.
3806
3807             if Nkind (N) = N_Extension_Aggregate then
3808                Root_Typ := Base_Type (Etype (Ancestor_Part (N)));
3809
3810             else
3811                --  AI05-0115:  check legality of aggregate for type with
3812                --  aa private ancestor.
3813
3814                Root_Typ := Root_Type (Typ);
3815                if Has_Private_Ancestor (Typ) then
3816                   declare
3817                      Ancestor      : constant Entity_Id :=
3818                        Find_Private_Ancestor;
3819                      Ancestor_Unit : constant Entity_Id :=
3820                        Cunit_Entity (Get_Source_Unit (Ancestor));
3821                      Parent_Unit   : constant Entity_Id :=
3822                        Cunit_Entity
3823                          (Get_Source_Unit (Base_Type (Etype (Ancestor))));
3824                   begin
3825
3826                      --  check whether we are in a scope that has full view
3827                      --  over the private ancestor and its parent. This can
3828                      --  only happen if the derivation takes place in a child
3829                      --  unit of the unit that declares the parent, and we are
3830                      --  in the private part or body of that child unit, else
3831                      --  the aggregate is illegal.
3832
3833                      if Is_Child_Unit (Ancestor_Unit)
3834                        and then Scope (Ancestor_Unit) = Parent_Unit
3835                        and then In_Open_Scopes (Scope (Ancestor))
3836                        and then
3837                         (In_Private_Part (Scope (Ancestor))
3838                            or else In_Package_Body (Scope (Ancestor)))
3839                      then
3840                         null;
3841
3842                      else
3843                         Error_Msg_NE
3844                           ("type of aggregate has private ancestor&!",
3845                               N, Root_Typ);
3846                         Error_Msg_N ("must use extension aggregate!", N);
3847                         return;
3848                      end if;
3849                   end;
3850                end if;
3851
3852                Dnode := Declaration_Node (Base_Type (Root_Typ));
3853
3854                --  If we don't get a full declaration, then we have some error
3855                --  which will get signalled later so skip this part. Otherwise
3856                --  gather components of root that apply to the aggregate type.
3857                --  We use the base type in case there is an applicable stored
3858                --  constraint that renames the discriminants of the root.
3859
3860                if Nkind (Dnode) = N_Full_Type_Declaration then
3861                   Record_Def := Type_Definition (Dnode);
3862                   Gather_Components
3863                     (Base_Type (Typ),
3864                      Component_List (Record_Def),
3865                      Governed_By   => New_Assoc_List,
3866                      Into          => Components,
3867                      Report_Errors => Errors_Found);
3868                end if;
3869             end if;
3870
3871             Parent_Typ := Base_Type (Typ);
3872             while Parent_Typ /= Root_Typ loop
3873                Prepend_Elmt (Parent_Typ, To => Parent_Typ_List);
3874                Parent_Typ := Etype (Parent_Typ);
3875
3876                if Nkind (Parent (Base_Type (Parent_Typ))) =
3877                                         N_Private_Type_Declaration
3878                  or else Nkind (Parent (Base_Type (Parent_Typ))) =
3879                                         N_Private_Extension_Declaration
3880                then
3881                   if Nkind (N) /= N_Extension_Aggregate then
3882                      Error_Msg_NE
3883                        ("type of aggregate has private ancestor&!",
3884                         N, Parent_Typ);
3885                      Error_Msg_N  ("must use extension aggregate!", N);
3886                      return;
3887
3888                   elsif Parent_Typ /= Root_Typ then
3889                      Error_Msg_NE
3890                        ("ancestor part of aggregate must be private type&",
3891                          Ancestor_Part (N), Parent_Typ);
3892                      return;
3893                   end if;
3894
3895                --  The current view of ancestor part may be a private type,
3896                --  while the context type is always non-private.
3897
3898                elsif Is_Private_Type (Root_Typ)
3899                  and then Present (Full_View (Root_Typ))
3900                  and then Nkind (N) = N_Extension_Aggregate
3901                then
3902                   exit when Base_Type (Full_View (Root_Typ)) = Parent_Typ;
3903                end if;
3904             end loop;
3905
3906             --  Now collect components from all other ancestors, beginning
3907             --  with the current type. If the type has unknown discriminants
3908             --  use the component list of the Underlying_Record_View, which
3909             --  needs to be used for the subsequent expansion of the aggregate
3910             --  into assignments.
3911
3912             Parent_Elmt := First_Elmt (Parent_Typ_List);
3913             while Present (Parent_Elmt) loop
3914                Parent_Typ := Node (Parent_Elmt);
3915
3916                if Has_Unknown_Discriminants (Parent_Typ)
3917                  and then Present (Underlying_Record_View (Typ))
3918                then
3919                   Parent_Typ := Underlying_Record_View (Parent_Typ);
3920                end if;
3921
3922                Record_Def := Type_Definition (Parent (Base_Type (Parent_Typ)));
3923                Gather_Components (Empty,
3924                  Component_List (Record_Extension_Part (Record_Def)),
3925                  Governed_By   => New_Assoc_List,
3926                  Into          => Components,
3927                  Report_Errors => Errors_Found);
3928
3929                Next_Elmt (Parent_Elmt);
3930             end loop;
3931
3932          --  Typ is not a derived tagged type
3933
3934          else
3935             --  A type derived from an untagged private type whose full view
3936             --  has discriminants is constructed as a record type but there
3937             --  are no legal aggregates for it.
3938
3939             if Is_Derived_Type (Typ)
3940               and then Has_Private_Ancestor (Typ)
3941               and then Nkind (N) /= N_Extension_Aggregate
3942             then
3943                Error_Msg_Node_2 := Base_Type (Etype (Typ));
3944                Error_Msg_NE
3945                  ("no aggregate available for type& derived from "
3946                   & "private type&", N, Typ);
3947                return;
3948             end if;
3949
3950             Record_Def := Type_Definition (Parent (Base_Type (Typ)));
3951
3952             if Null_Present (Record_Def) then
3953                null;
3954
3955             elsif not Has_Unknown_Discriminants (Typ) then
3956                Gather_Components
3957                  (Base_Type (Typ),
3958                   Component_List (Record_Def),
3959                   Governed_By   => New_Assoc_List,
3960                   Into          => Components,
3961                   Report_Errors => Errors_Found);
3962
3963             else
3964                Gather_Components
3965                  (Base_Type (Underlying_Record_View (Typ)),
3966                   Component_List (Record_Def),
3967                   Governed_By   => New_Assoc_List,
3968                   Into          => Components,
3969                   Report_Errors => Errors_Found);
3970             end if;
3971          end if;
3972
3973          if Errors_Found then
3974             return;
3975          end if;
3976       end Step_5;
3977
3978       --  STEP 6: Find component Values
3979
3980       Component := Empty;
3981       Component_Elmt := First_Elmt (Components);
3982
3983       --  First scan the remaining positional associations in the aggregate.
3984       --  Remember that at this point Positional_Expr contains the current
3985       --  positional association if any is left after looking for discriminant
3986       --  values in step 3.
3987
3988       while Present (Positional_Expr) and then Present (Component_Elmt) loop
3989          Component := Node (Component_Elmt);
3990          Resolve_Aggr_Expr (Positional_Expr, Component);
3991
3992          --  Ada 2005 (AI-231)
3993
3994          if Ada_Version >= Ada_2005
3995            and then Known_Null (Positional_Expr)
3996          then
3997             Check_Can_Never_Be_Null (Component, Positional_Expr);
3998          end if;
3999
4000          if Present (Get_Value (Component, Component_Associations (N))) then
4001             Error_Msg_NE
4002               ("more than one value supplied for Component &", N, Component);
4003          end if;
4004
4005          Next (Positional_Expr);
4006          Next_Elmt (Component_Elmt);
4007       end loop;
4008
4009       if Present (Positional_Expr) then
4010          Error_Msg_N
4011            ("too many components for record aggregate", Positional_Expr);
4012       end if;
4013
4014       --  Now scan for the named arguments of the aggregate
4015
4016       while Present (Component_Elmt) loop
4017          Component := Node (Component_Elmt);
4018          Expr := Get_Value (Component, Component_Associations (N), True);
4019
4020          --  Note: The previous call to Get_Value sets the value of the
4021          --  variable Is_Box_Present.
4022
4023          --  Ada 2005 (AI-287): Handle components with default initialization.
4024          --  Note: This feature was originally added to Ada 2005 for limited
4025          --  but it was finally allowed with any type.
4026
4027          if Is_Box_Present then
4028             Check_Box_Component : declare
4029                Ctyp : constant Entity_Id := Etype (Component);
4030
4031             begin
4032                --  If there is a default expression for the aggregate, copy
4033                --  it into a new association. This copy must modify the scopes
4034                --  of internal types that may be attached to the expression
4035                --  (e.g. index subtypes of arrays) because in general the type
4036                --  declaration and the aggregate appear in different scopes,
4037                --  and the backend requires the scope of the type to match the
4038                --  point at which it is elaborated.
4039
4040                --  If the component has an initialization procedure (IP) we
4041                --  pass the component to the expander, which will generate
4042                --  the call to such IP.
4043
4044                --  If the component has discriminants, their values must
4045                --  be taken from their subtype. This is indispensable for
4046                --  constraints that are given by the current instance of an
4047                --  enclosing type, to allow the expansion of the aggregate to
4048                --  replace the reference to the current instance by the target
4049                --  object of the aggregate.
4050
4051                if Present (Parent (Component))
4052                  and then
4053                    Nkind (Parent (Component)) = N_Component_Declaration
4054                  and then Present (Expression (Parent (Component)))
4055                then
4056                   Expr :=
4057                     New_Copy_Tree_And_Copy_Dimensions
4058                       (Expression (Parent (Component)),
4059                        New_Scope => Current_Scope,
4060                        New_Sloc  => Sloc (N));
4061
4062                   Add_Association
4063                     (Component  => Component,
4064                      Expr       => Expr,
4065                      Assoc_List => New_Assoc_List);
4066                   Set_Has_Self_Reference (N);
4067
4068                --  A box-defaulted access component gets the value null. Also
4069                --  included are components of private types whose underlying
4070                --  type is an access type. In either case set the type of the
4071                --  literal, for subsequent use in semantic checks.
4072
4073                elsif Present (Underlying_Type (Ctyp))
4074                  and then Is_Access_Type (Underlying_Type (Ctyp))
4075                then
4076                   if not Is_Private_Type (Ctyp) then
4077                      Expr := Make_Null (Sloc (N));
4078                      Set_Etype (Expr, Ctyp);
4079                      Add_Association
4080                        (Component  => Component,
4081                         Expr       => Expr,
4082                         Assoc_List => New_Assoc_List);
4083
4084                   --  If the component's type is private with an access type as
4085                   --  its underlying type then we have to create an unchecked
4086                   --  conversion to satisfy type checking.
4087
4088                   else
4089                      declare
4090                         Qual_Null : constant Node_Id :=
4091                                       Make_Qualified_Expression (Sloc (N),
4092                                         Subtype_Mark =>
4093                                           New_Occurrence_Of
4094                                             (Underlying_Type (Ctyp), Sloc (N)),
4095                                         Expression => Make_Null (Sloc (N)));
4096
4097                         Convert_Null : constant Node_Id :=
4098                                          Unchecked_Convert_To
4099                                            (Ctyp, Qual_Null);
4100
4101                      begin
4102                         Analyze_And_Resolve (Convert_Null, Ctyp);
4103                         Add_Association
4104                           (Component  => Component,
4105                            Expr       => Convert_Null,
4106                            Assoc_List => New_Assoc_List);
4107                      end;
4108                   end if;
4109
4110                --  Ada 2012: If component is scalar with default value, use it
4111
4112                elsif Is_Scalar_Type (Ctyp)
4113                  and then Has_Default_Aspect (Ctyp)
4114                then
4115                   Add_Association
4116                     (Component  => Component,
4117                      Expr       => Default_Aspect_Value
4118                                      (First_Subtype (Underlying_Type (Ctyp))),
4119                      Assoc_List => New_Assoc_List);
4120
4121                elsif Has_Non_Null_Base_Init_Proc (Ctyp)
4122                  or else not Expander_Active
4123                then
4124                   if Is_Record_Type (Ctyp)
4125                     and then Has_Discriminants (Ctyp)
4126                     and then not Is_Private_Type (Ctyp)
4127                   then
4128                      --  We build a partially initialized aggregate with the
4129                      --  values of the discriminants and box initialization
4130                      --  for the rest, if other components are present.
4131
4132                      --  The type of the aggregate is the known subtype of
4133                      --  the component. The capture of discriminants must
4134                      --  be recursive because subcomponents may be constrained
4135                      --  (transitively) by discriminants of enclosing types.
4136                      --  For a private type with discriminants, a call to the
4137                      --  initialization procedure will be generated, and no
4138                      --  subaggregate is needed.
4139
4140                      Capture_Discriminants : declare
4141                         Loc  : constant Source_Ptr := Sloc (N);
4142                         Expr : Node_Id;
4143
4144                         procedure Add_Discriminant_Values
4145                           (New_Aggr   : Node_Id;
4146                            Assoc_List : List_Id);
4147                         --  The constraint to a component may be given by a
4148                         --  discriminant of the enclosing type, in which case
4149                         --  we have to retrieve its value, which is part of the
4150                         --  enclosing aggregate. Assoc_List provides the
4151                         --  discriminant associations of the current type or
4152                         --  of some enclosing record.
4153
4154                         procedure Propagate_Discriminants
4155                           (Aggr       : Node_Id;
4156                            Assoc_List : List_Id);
4157                         --  Nested components may themselves be discriminated
4158                         --  types constrained by outer discriminants, whose
4159                         --  values must be captured before the aggregate is
4160                         --  expanded into assignments.
4161
4162                         -----------------------------
4163                         -- Add_Discriminant_Values --
4164                         -----------------------------
4165
4166                         procedure Add_Discriminant_Values
4167                           (New_Aggr   : Node_Id;
4168                            Assoc_List : List_Id)
4169                         is
4170                            Assoc      : Node_Id;
4171                            Discr      : Entity_Id;
4172                            Discr_Elmt : Elmt_Id;
4173                            Discr_Val  : Node_Id;
4174                            Val        : Entity_Id;
4175
4176                         begin
4177                            Discr := First_Discriminant (Etype (New_Aggr));
4178                            Discr_Elmt :=
4179                              First_Elmt
4180                                (Discriminant_Constraint (Etype (New_Aggr)));
4181                            while Present (Discr_Elmt) loop
4182                               Discr_Val := Node (Discr_Elmt);
4183
4184                               --  If the constraint is given by a discriminant
4185                               --  it is a discriminant of an enclosing record,
4186                               --  and its value has already been placed in the
4187                               --  association list.
4188
4189                               if Is_Entity_Name (Discr_Val)
4190                                 and then
4191                                   Ekind (Entity (Discr_Val)) = E_Discriminant
4192                               then
4193                                  Val := Entity (Discr_Val);
4194
4195                                  Assoc := First (Assoc_List);
4196                                  while Present (Assoc) loop
4197                                     if Present
4198                                       (Entity (First (Choices (Assoc))))
4199                                       and then
4200                                         Entity (First (Choices (Assoc)))
4201                                           = Val
4202                                     then
4203                                        Discr_Val := Expression (Assoc);
4204                                        exit;
4205                                     end if;
4206                                     Next (Assoc);
4207                                  end loop;
4208                               end if;
4209
4210                               Add_Association
4211                                 (Discr, New_Copy_Tree (Discr_Val),
4212                                   Component_Associations (New_Aggr));
4213
4214                               --  If the discriminant constraint is a current
4215                               --  instance, mark the current aggregate so that
4216                               --  the self-reference can be expanded later.
4217
4218                               if Nkind (Discr_Val) = N_Attribute_Reference
4219                                 and then Is_Entity_Name (Prefix (Discr_Val))
4220                                 and then Is_Type (Entity (Prefix (Discr_Val)))
4221                                 and then Etype (N) =
4222                                   Entity (Prefix (Discr_Val))
4223                               then
4224                                  Set_Has_Self_Reference (N);
4225                               end if;
4226
4227                               Next_Elmt (Discr_Elmt);
4228                               Next_Discriminant (Discr);
4229                            end loop;
4230                         end Add_Discriminant_Values;
4231
4232                         ------------------------------
4233                         --  Propagate_Discriminants --
4234                         ------------------------------
4235
4236                         procedure Propagate_Discriminants
4237                           (Aggr       : Node_Id;
4238                            Assoc_List : List_Id)
4239                         is
4240                            Aggr_Type : constant Entity_Id :=
4241                                          Base_Type (Etype (Aggr));
4242                            Def_Node  : constant Node_Id :=
4243                                          Type_Definition
4244                                            (Declaration_Node (Aggr_Type));
4245
4246                            Comp       : Node_Id;
4247                            Comp_Elmt  : Elmt_Id;
4248                            Components : constant Elist_Id := New_Elmt_List;
4249                            Needs_Box  : Boolean := False;
4250                            Errors     : Boolean;
4251
4252                            procedure Process_Component (Comp : Entity_Id);
4253                            --  Add one component with a box association to the
4254                            --  inner aggregate, and recurse if component is
4255                            --  itself composite.
4256
4257                            ------------------------
4258                            --  Process_Component --
4259                            ------------------------
4260
4261                            procedure Process_Component (Comp : Entity_Id) is
4262                               T : constant Entity_Id := Etype (Comp);
4263                               New_Aggr   : Node_Id;
4264
4265                            begin
4266                               if Is_Record_Type (T)
4267                                 and then Has_Discriminants (T)
4268                               then
4269                                  New_Aggr :=
4270                                    Make_Aggregate (Loc, New_List, New_List);
4271                                  Set_Etype (New_Aggr, T);
4272                                  Add_Association
4273                                    (Comp, New_Aggr,
4274                                      Component_Associations (Aggr));
4275
4276                                  --  Collect discriminant values and recurse
4277
4278                                  Add_Discriminant_Values
4279                                    (New_Aggr, Assoc_List);
4280                                  Propagate_Discriminants
4281                                    (New_Aggr, Assoc_List);
4282
4283                               else
4284                                  Needs_Box := True;
4285                               end if;
4286                            end Process_Component;
4287
4288                         --  Start of processing for Propagate_Discriminants
4289
4290                         begin
4291                            --  The component type may be a variant type, so
4292                            --  collect the components that are ruled by the
4293                            --  known values of the discriminants. Their values
4294                            --  have already been inserted into the component
4295                            --  list of the current aggregate.
4296
4297                            if Nkind (Def_Node) =  N_Record_Definition
4298                              and then
4299                                Present (Component_List (Def_Node))
4300                              and then
4301                                Present
4302                                  (Variant_Part (Component_List (Def_Node)))
4303                            then
4304                               Gather_Components (Aggr_Type,
4305                                 Component_List (Def_Node),
4306                                 Governed_By   => Component_Associations (Aggr),
4307                                 Into          => Components,
4308                                 Report_Errors => Errors);
4309
4310                               Comp_Elmt := First_Elmt (Components);
4311                               while Present (Comp_Elmt) loop
4312                                  if
4313                                    Ekind (Node (Comp_Elmt)) /= E_Discriminant
4314                                  then
4315                                     Process_Component (Node (Comp_Elmt));
4316                                  end if;
4317
4318                                  Next_Elmt (Comp_Elmt);
4319                               end loop;
4320
4321                            --  No variant part, iterate over all components
4322
4323                            else
4324                               Comp := First_Component (Etype (Aggr));
4325                               while Present (Comp) loop
4326                                  Process_Component (Comp);
4327                                  Next_Component (Comp);
4328                               end loop;
4329                            end if;
4330
4331                            if Needs_Box then
4332                               Append
4333                                 (Make_Component_Association (Loc,
4334                                    Choices     =>
4335                                      New_List (Make_Others_Choice (Loc)),
4336                                    Expression  => Empty,
4337                                       Box_Present => True),
4338                                  Component_Associations (Aggr));
4339                            end if;
4340                         end Propagate_Discriminants;
4341
4342                      --  Start of processing for Capture_Discriminants
4343
4344                      begin
4345                         Expr := Make_Aggregate (Loc, New_List, New_List);
4346                         Set_Etype (Expr, Ctyp);
4347
4348                         --  If the enclosing type has discriminants, they have
4349                         --  been collected in the aggregate earlier, and they
4350                         --  may appear as constraints of subcomponents.
4351
4352                         --  Similarly if this component has discriminants, they
4353                         --  might in turn be propagated to their components.
4354
4355                         if Has_Discriminants (Typ) then
4356                            Add_Discriminant_Values (Expr, New_Assoc_List);
4357                            Propagate_Discriminants (Expr, New_Assoc_List);
4358
4359                         elsif Has_Discriminants (Ctyp) then
4360                            Add_Discriminant_Values
4361                               (Expr, Component_Associations (Expr));
4362                            Propagate_Discriminants
4363                               (Expr, Component_Associations (Expr));
4364
4365                         else
4366                            declare
4367                               Comp : Entity_Id;
4368
4369                            begin
4370                               --  If the type has additional components, create
4371                               --  an OTHERS box association for them.
4372
4373                               Comp := First_Component (Ctyp);
4374                               while Present (Comp) loop
4375                                  if Ekind (Comp) = E_Component then
4376                                     if not Is_Record_Type (Etype (Comp)) then
4377                                        Append
4378                                          (Make_Component_Association (Loc,
4379                                             Choices     =>
4380                                               New_List
4381                                                (Make_Others_Choice (Loc)),
4382                                             Expression  => Empty,
4383                                                Box_Present => True),
4384                                           Component_Associations (Expr));
4385                                     end if;
4386                                     exit;
4387                                  end if;
4388
4389                                  Next_Component (Comp);
4390                               end loop;
4391                            end;
4392                         end if;
4393
4394                         Add_Association
4395                           (Component  => Component,
4396                            Expr       => Expr,
4397                            Assoc_List => New_Assoc_List);
4398                      end Capture_Discriminants;
4399
4400                   else
4401                      Add_Association
4402                        (Component      => Component,
4403                         Expr           => Empty,
4404                         Assoc_List     => New_Assoc_List,
4405                         Is_Box_Present => True);
4406                   end if;
4407
4408                --  Otherwise we only need to resolve the expression if the
4409                --  component has partially initialized values (required to
4410                --  expand the corresponding assignments and run-time checks).
4411
4412                elsif Present (Expr)
4413                  and then Is_Partially_Initialized_Type (Ctyp)
4414                then
4415                   Resolve_Aggr_Expr (Expr, Component);
4416                end if;
4417             end Check_Box_Component;
4418
4419          elsif No (Expr) then
4420
4421             --  Ignore hidden components associated with the position of the
4422             --  interface tags: these are initialized dynamically.
4423
4424             if not Present (Related_Type (Component)) then
4425                Error_Msg_NE
4426                  ("no value supplied for component &!", N, Component);
4427             end if;
4428
4429          else
4430             Resolve_Aggr_Expr (Expr, Component);
4431          end if;
4432
4433          Next_Elmt (Component_Elmt);
4434       end loop;
4435
4436       --  STEP 7: check for invalid components + check type in choice list
4437
4438       Step_7 : declare
4439          Selectr : Node_Id;
4440          --  Selector name
4441
4442          Typech : Entity_Id;
4443          --  Type of first component in choice list
4444
4445       begin
4446          if Present (Component_Associations (N)) then
4447             Assoc := First (Component_Associations (N));
4448          else
4449             Assoc := Empty;
4450          end if;
4451
4452          Verification : while Present (Assoc) loop
4453             Selectr := First (Choices (Assoc));
4454             Typech := Empty;
4455
4456             if Nkind (Selectr) = N_Others_Choice then
4457
4458                --  Ada 2005 (AI-287): others choice may have expression or box
4459
4460                if No (Others_Etype)
4461                   and then not Others_Box
4462                then
4463                   Error_Msg_N
4464                     ("OTHERS must represent at least one component", Selectr);
4465                end if;
4466
4467                exit Verification;
4468             end if;
4469
4470             while Present (Selectr) loop
4471                New_Assoc := First (New_Assoc_List);
4472                while Present (New_Assoc) loop
4473                   Component := First (Choices (New_Assoc));
4474
4475                   if Chars (Selectr) = Chars (Component) then
4476                      if Style_Check then
4477                         Check_Identifier (Selectr, Entity (Component));
4478                      end if;
4479
4480                      exit;
4481                   end if;
4482
4483                   Next (New_Assoc);
4484                end loop;
4485
4486                --  If no association, this is not a legal component of the type
4487                --  in question, unless its association is provided with a box.
4488
4489                if No (New_Assoc) then
4490                   if Box_Present (Parent (Selectr)) then
4491
4492                      --  This may still be a bogus component with a box. Scan
4493                      --  list of components to verify that a component with
4494                      --  that name exists.
4495
4496                      declare
4497                         C : Entity_Id;
4498
4499                      begin
4500                         C := First_Component (Typ);
4501                         while Present (C) loop
4502                            if Chars (C) = Chars (Selectr) then
4503
4504                               --  If the context is an extension aggregate,
4505                               --  the component must not be inherited from
4506                               --  the ancestor part of the aggregate.
4507
4508                               if Nkind (N) /= N_Extension_Aggregate
4509                                 or else
4510                                   Scope (Original_Record_Component (C)) /=
4511                                                      Etype (Ancestor_Part (N))
4512                               then
4513                                  exit;
4514                               end if;
4515                            end if;
4516
4517                            Next_Component (C);
4518                         end loop;
4519
4520                         if No (C) then
4521                            Error_Msg_Node_2 := Typ;
4522                            Error_Msg_N ("& is not a component of}", Selectr);
4523                         end if;
4524                      end;
4525
4526                   elsif Chars (Selectr) /= Name_uTag
4527                     and then Chars (Selectr) /= Name_uParent
4528                   then
4529                      if not Has_Discriminants (Typ) then
4530                         Error_Msg_Node_2 := Typ;
4531                         Error_Msg_N ("& is not a component of}", Selectr);
4532                      else
4533                         Error_Msg_N
4534                           ("& is not a component of the aggregate subtype",
4535                             Selectr);
4536                      end if;
4537
4538                      Check_Misspelled_Component (Components, Selectr);
4539                   end if;
4540
4541                elsif No (Typech) then
4542                   Typech := Base_Type (Etype (Component));
4543
4544                --  AI05-0199: In Ada 2012, several components of anonymous
4545                --  access types can appear in a choice list, as long as the
4546                --  designated types match.
4547
4548                elsif Typech /= Base_Type (Etype (Component)) then
4549                   if Ada_Version >= Ada_2012
4550                     and then Ekind (Typech) = E_Anonymous_Access_Type
4551                     and then
4552                        Ekind (Etype (Component)) = E_Anonymous_Access_Type
4553                     and then Base_Type (Designated_Type (Typech)) =
4554                              Base_Type (Designated_Type (Etype (Component)))
4555                     and then
4556                       Subtypes_Statically_Match (Typech, (Etype (Component)))
4557                   then
4558                      null;
4559
4560                   elsif not Box_Present (Parent (Selectr)) then
4561                      Error_Msg_N
4562                        ("components in choice list must have same type",
4563                         Selectr);
4564                   end if;
4565                end if;
4566
4567                Next (Selectr);
4568             end loop;
4569
4570             Next (Assoc);
4571          end loop Verification;
4572       end Step_7;
4573
4574       --  STEP 8: replace the original aggregate
4575
4576       Step_8 : declare
4577          New_Aggregate : constant Node_Id := New_Copy (N);
4578
4579       begin
4580          Set_Expressions            (New_Aggregate, No_List);
4581          Set_Etype                  (New_Aggregate, Etype (N));
4582          Set_Component_Associations (New_Aggregate, New_Assoc_List);
4583
4584          Rewrite (N, New_Aggregate);
4585       end Step_8;
4586
4587       --  Check the dimensions of the components in the record aggregate
4588
4589       Analyze_Dimension_Extension_Or_Record_Aggregate (N);
4590    end Resolve_Record_Aggregate;
4591
4592    -----------------------------
4593    -- Check_Can_Never_Be_Null --
4594    -----------------------------
4595
4596    procedure Check_Can_Never_Be_Null (Typ : Entity_Id; Expr : Node_Id) is
4597       Comp_Typ : Entity_Id;
4598
4599    begin
4600       pragma Assert
4601         (Ada_Version >= Ada_2005
4602           and then Present (Expr)
4603           and then Known_Null (Expr));
4604
4605       case Ekind (Typ) is
4606          when E_Array_Type  =>
4607             Comp_Typ := Component_Type (Typ);
4608
4609          when E_Component    |
4610               E_Discriminant =>
4611             Comp_Typ := Etype (Typ);
4612
4613          when others =>
4614             return;
4615       end case;
4616
4617       if Can_Never_Be_Null (Comp_Typ) then
4618
4619          --  Here we know we have a constraint error. Note that we do not use
4620          --  Apply_Compile_Time_Constraint_Error here to the Expr, which might
4621          --  seem the more natural approach. That's because in some cases the
4622          --  components are rewritten, and the replacement would be missed.
4623          --  We do not mark the whole aggregate as raising a constraint error,
4624          --  because the association may be a null array range.
4625
4626          Error_Msg_N
4627            ("(Ada 2005) null not allowed in null-excluding component??", Expr);
4628          Error_Msg_N
4629            ("\Constraint_Error will be raised at run time??", Expr);
4630
4631          Rewrite (Expr,
4632            Make_Raise_Constraint_Error
4633              (Sloc (Expr), Reason => CE_Access_Check_Failed));
4634          Set_Etype    (Expr, Comp_Typ);
4635          Set_Analyzed (Expr);
4636       end if;
4637    end Check_Can_Never_Be_Null;
4638
4639    ---------------------
4640    -- Sort_Case_Table --
4641    ---------------------
4642
4643    procedure Sort_Case_Table (Case_Table : in out Case_Table_Type) is
4644       U : constant Int := Case_Table'Last;
4645       K : Int;
4646       J : Int;
4647       T : Case_Bounds;
4648
4649    begin
4650       K := 1;
4651       while K < U loop
4652          T := Case_Table (K + 1);
4653
4654          J := K + 1;
4655          while J > 1
4656            and then Expr_Value (Case_Table (J - 1).Lo) > Expr_Value (T.Lo)
4657          loop
4658             Case_Table (J) := Case_Table (J - 1);
4659             J := J - 1;
4660          end loop;
4661
4662          Case_Table (J) := T;
4663          K := K + 1;
4664       end loop;
4665    end Sort_Case_Table;
4666
4667 end Sem_Aggr;