OSDN Git Service

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