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