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