OSDN Git Service

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