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