OSDN Git Service

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