OSDN Git Service

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