OSDN Git Service

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