OSDN Git Service

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