OSDN Git Service

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