OSDN Git Service

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