OSDN Git Service

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