OSDN Git Service

2007-04-20 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch12.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ C H 1 2                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2007, 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 Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Expander; use Expander;
32 with Fname;    use Fname;
33 with Fname.UF; use Fname.UF;
34 with Freeze;   use Freeze;
35 with Hostparm;
36 with Lib;      use Lib;
37 with Lib.Load; use Lib.Load;
38 with Lib.Xref; use Lib.Xref;
39 with Nlists;   use Nlists;
40 with Namet;    use Namet;
41 with Nmake;    use Nmake;
42 with Opt;      use Opt;
43 with Rident;   use Rident;
44 with Restrict; use Restrict;
45 with Rtsfind;  use Rtsfind;
46 with Sem;      use Sem;
47 with Sem_Cat;  use Sem_Cat;
48 with Sem_Ch3;  use Sem_Ch3;
49 with Sem_Ch6;  use Sem_Ch6;
50 with Sem_Ch7;  use Sem_Ch7;
51 with Sem_Ch8;  use Sem_Ch8;
52 with Sem_Ch10; use Sem_Ch10;
53 with Sem_Ch13; use Sem_Ch13;
54 with Sem_Disp; use Sem_Disp;
55 with Sem_Elab; use Sem_Elab;
56 with Sem_Elim; use Sem_Elim;
57 with Sem_Eval; use Sem_Eval;
58 with Sem_Res;  use Sem_Res;
59 with Sem_Type; use Sem_Type;
60 with Sem_Util; use Sem_Util;
61 with Sem_Warn; use Sem_Warn;
62 with Stand;    use Stand;
63 with Sinfo;    use Sinfo;
64 with Sinfo.CN; use Sinfo.CN;
65 with Sinput;   use Sinput;
66 with Sinput.L; use Sinput.L;
67 with Snames;   use Snames;
68 with Stringt;  use Stringt;
69 with Uname;    use Uname;
70 with Table;
71 with Tbuild;   use Tbuild;
72 with Uintp;    use Uintp;
73 with Urealp;   use Urealp;
74
75 with GNAT.HTable;
76
77 package body Sem_Ch12 is
78
79    ----------------------------------------------------------
80    -- Implementation of Generic Analysis and Instantiation --
81    ----------------------------------------------------------
82
83    --  GNAT implements generics by macro expansion. No attempt is made to share
84    --  generic instantiations (for now). Analysis of a generic definition does
85    --  not perform any expansion action, but the expander must be called on the
86    --  tree for each instantiation, because the expansion may of course depend
87    --  on the generic actuals. All of this is best achieved as follows:
88    --
89    --  a) Semantic analysis of a generic unit is performed on a copy of the
90    --  tree for the generic unit. All tree modifications that follow analysis
91    --  do not affect the original tree. Links are kept between the original
92    --  tree and the copy, in order to recognize non-local references within
93    --  the generic, and propagate them to each instance (recall that name
94    --  resolution is done on the generic declaration: generics are not really
95    --  macros!). This is summarized in the following diagram:
96
97    --              .-----------.               .----------.
98    --              |  semantic |<--------------|  generic |
99    --              |    copy   |               |    unit  |
100    --              |           |==============>|          |
101    --              |___________|    global     |__________|
102    --                             references     |   |  |
103    --                                            |   |  |
104    --                                          .-----|--|.
105    --                                          |  .-----|---.
106    --                                          |  |  .----------.
107    --                                          |  |  |  generic |
108    --                                          |__|  |          |
109    --                                             |__| instance |
110    --                                                |__________|
111
112    --  b) Each instantiation copies the original tree, and inserts into it a
113    --  series of declarations that describe the mapping between generic formals
114    --  and actuals. For example, a generic In OUT parameter is an object
115    --  renaming of the corresponing actual, etc. Generic IN parameters are
116    --  constant declarations.
117
118    --  c) In order to give the right visibility for these renamings, we use
119    --  a different scheme for package and subprogram instantiations. For
120    --  packages, the list of renamings is inserted into the package
121    --  specification, before the visible declarations of the package. The
122    --  renamings are analyzed before any of the text of the instance, and are
123    --  thus visible at the right place. Furthermore, outside of the instance,
124    --  the generic parameters are visible and denote their corresponding
125    --  actuals.
126
127    --  For subprograms, we create a container package to hold the renamings
128    --  and the subprogram instance itself. Analysis of the package makes the
129    --  renaming declarations visible to the subprogram. After analyzing the
130    --  package, the defining entity for the subprogram is touched-up so that
131    --  it appears declared in the current scope, and not inside the container
132    --  package.
133
134    --  If the instantiation is a compilation unit, the container package is
135    --  given the same name as the subprogram instance. This ensures that
136    --  the elaboration procedure called by the binder, using the compilation
137    --  unit name, calls in fact the elaboration procedure for the package.
138
139    --  Not surprisingly, private types complicate this approach. By saving in
140    --  the original generic object the non-local references, we guarantee that
141    --  the proper entities are referenced at the point of instantiation.
142    --  However, for private types, this by itself does not insure that the
143    --  proper VIEW of the entity is used (the full type may be visible at the
144    --  point of generic definition, but not at instantiation, or vice-versa).
145    --  In  order to reference the proper view, we special-case any reference
146    --  to private types in the generic object, by saving both views, one in
147    --  the generic and one in the semantic copy. At time of instantiation, we
148    --  check whether the two views are consistent, and exchange declarations if
149    --  necessary, in order to restore the correct visibility. Similarly, if
150    --  the instance view is private when the generic view was not, we perform
151    --  the exchange. After completing the instantiation, we restore the
152    --  current visibility. The flag Has_Private_View marks identifiers in the
153    --  the generic unit that require checking.
154
155    --  Visibility within nested generic units requires special handling.
156    --  Consider the following scheme:
157
158    --  type Global is ...         --  outside of generic unit.
159    --  generic ...
160    --  package Outer is
161    --     ...
162    --     type Semi_Global is ... --  global to inner.
163
164    --     generic ...                                         -- 1
165    --     procedure inner (X1 : Global;  X2 : Semi_Global);
166
167    --     procedure in2 is new inner (...);                   -- 4
168    --  end Outer;
169
170    --  package New_Outer is new Outer (...);                  -- 2
171    --  procedure New_Inner is new New_Outer.Inner (...);      -- 3
172
173    --  The semantic analysis of Outer captures all occurrences of Global.
174    --  The semantic analysis of Inner (at 1) captures both occurrences of
175    --  Global and Semi_Global.
176
177    --  At point 2 (instantiation of Outer), we also produce a generic copy
178    --  of Inner, even though Inner is, at that point, not being instantiated.
179    --  (This is just part of the semantic analysis of New_Outer).
180
181    --  Critically, references to Global within Inner must be preserved, while
182    --  references to Semi_Global should not preserved, because they must now
183    --  resolve to an entity within New_Outer. To distinguish between these, we
184    --  use a global variable, Current_Instantiated_Parent, which is set when
185    --  performing a generic copy during instantiation (at 2). This variable is
186    --  used when performing a generic copy that is not an instantiation, but
187    --  that is nested within one, as the occurrence of 1 within 2. The analysis
188    --  of a nested generic only preserves references that are global to the
189    --  enclosing Current_Instantiated_Parent. We use the Scope_Depth value to
190    --  determine whether a reference is external to the given parent.
191
192    --  The instantiation at point 3 requires no special treatment. The method
193    --  works as well for further nestings of generic units, but of course the
194    --  variable Current_Instantiated_Parent must be stacked because nested
195    --  instantiations can occur, e.g. the occurrence of 4 within 2.
196
197    --  The instantiation of package and subprogram bodies is handled in a
198    --  similar manner, except that it is delayed until after semantic
199    --  analysis is complete. In this fashion complex cross-dependencies
200    --  between several package declarations and bodies containing generics
201    --  can be compiled which otherwise would diagnose spurious circularities.
202
203    --  For example, it is possible to compile two packages A and B that
204    --  have the following structure:
205
206    --    package A is                         package B is
207    --       generic ...                          generic ...
208    --       package G_A is                       package G_B is
209
210    --    with B;                              with A;
211    --    package body A is                    package body B is
212    --       package N_B is new G_B (..)          package N_A is new G_A (..)
213
214    --  The table Pending_Instantiations in package Inline is used to keep
215    --  track of body instantiations that are delayed in this manner. Inline
216    --  handles the actual calls to do the body instantiations. This activity
217    --  is part of Inline, since the processing occurs at the same point, and
218    --  for essentially the same reason, as the handling of inlined routines.
219
220    ----------------------------------------------
221    -- Detection of Instantiation Circularities --
222    ----------------------------------------------
223
224    --  If we have a chain of instantiations that is circular, this is static
225    --  error which must be detected at compile time. The detection of these
226    --  circularities is carried out at the point that we insert a generic
227    --  instance spec or body. If there is a circularity, then the analysis of
228    --  the offending spec or body will eventually result in trying to load the
229    --  same unit again, and we detect this problem as we analyze the package
230    --  instantiation for the second time.
231
232    --  At least in some cases after we have detected the circularity, we get
233    --  into trouble if we try to keep going. The following flag is set if a
234    --  circularity is detected, and used to abandon compilation after the
235    --  messages have been posted.
236
237    Circularity_Detected : Boolean := False;
238    --  This should really be reset on encountering a new main unit, but in
239    --  practice we are not using multiple main units so it is not critical.
240
241    -------------------------------------------------
242    -- Formal packages and partial parametrization --
243    -------------------------------------------------
244
245    --  When compiling a generic, a formal package is a local instantiation. If
246    --  declared with a box, its generic formals are visible in the enclosing
247    --  generic. If declared with a partial list of actuals, those actuals that
248    --  are defaulted (covered by an Others clause, or given an explicit box
249    --  initialization) are also visible in the enclosing generic, while those
250    --  that have a corresponding actual are not.
251
252    --  In our source model of instantiation, the same visibility must be
253    --  present in the spec and body of an instance: the names of the formals
254    --  that are defaulted must be made visible within the instance, and made
255    --  invisible (hidden) after the instantiation is complete, so that they
256    --  are not accessible outside of the instance.
257
258    --  In a generic, a formal package is treated like a special instantiation.
259    --  Our Ada95 compiler handled formals with and without box in different
260    --  ways. With partial parametrization, we use a single model for both.
261    --  We create a package declaration that consists of the specification of
262    --  the generic package, and a set of declarations that map the actuals
263    --  into local renamings, just as we do for bona fide instantiations. For
264    --  defaulted parameters and formals with a box, we copy directly the
265    --  declarations of the formal into this local package. The result is a
266    --  a package whose visible declarations may include generic formals. This
267    --  package is only used for type checking and visibility analysis, and
268    --  never reaches the back-end, so it can freely violate the placement
269    --  rules for generic formal declarations.
270
271    --  The list of declarations (renamings and copies of formals) is built
272    --  by Analyze_Associations, just as for regular instantiations.
273
274    --  At the point of instantiation, conformance checking must be applied only
275    --  to those parameters that were specified in the formal. We perform this
276    --  checking by creating another internal instantiation, this one including
277    --  only the renamings and the formals (the rest of the package spec is not
278    --  relevant to conformance checking). We can then traverse two lists: the
279    --  list of actuals in the instance that corresponds to the formal package,
280    --  and the list of actuals produced for this bogus instantiation. We apply
281    --  the conformance rules to those actuals that are not defaulted (i.e.
282    --  which still appear as generic formals.
283
284    --  When we compile an instance body we must make the right parameters
285    --  visible again. The predicate Is_Generic_Formal indicates which of the
286    --  formals should have its Is_Hidden flag reset.
287
288    -----------------------
289    -- Local subprograms --
290    -----------------------
291
292    procedure Abandon_Instantiation (N : Node_Id);
293    pragma No_Return (Abandon_Instantiation);
294    --  Posts an error message "instantiation abandoned" at the indicated node
295    --  and then raises the exception Instantiation_Error to do it.
296
297    procedure Analyze_Formal_Array_Type
298      (T   : in out Entity_Id;
299       Def : Node_Id);
300    --  A formal array type is treated like an array type declaration, and
301    --  invokes Array_Type_Declaration (sem_ch3) whose first parameter is
302    --  in-out, because in the case of an anonymous type the entity is
303    --  actually created in the procedure.
304
305    --  The following procedures treat other kinds of formal parameters
306
307    procedure Analyze_Formal_Derived_Interface_Type
308      (N   : Node_Id;
309       T   : Entity_Id;
310       Def : Node_Id);
311
312    procedure Analyze_Formal_Derived_Type
313      (N   : Node_Id;
314       T   : Entity_Id;
315       Def : Node_Id);
316
317    procedure Analyze_Formal_Interface_Type
318      (N   : Node_Id;
319       T   : Entity_Id;
320       Def : Node_Id);
321
322    --  The following subprograms create abbreviated declarations for formal
323    --  scalar types. We introduce an anonymous base of the proper class for
324    --  each of them, and define the formals as constrained first subtypes of
325    --  their bases. The bounds are expressions that are non-static in the
326    --  generic.
327
328    procedure Analyze_Formal_Decimal_Fixed_Point_Type
329                                                 (T : Entity_Id; Def : Node_Id);
330    procedure Analyze_Formal_Discrete_Type       (T : Entity_Id; Def : Node_Id);
331    procedure Analyze_Formal_Floating_Type       (T : Entity_Id; Def : Node_Id);
332    procedure Analyze_Formal_Signed_Integer_Type (T : Entity_Id; Def : Node_Id);
333    procedure Analyze_Formal_Modular_Type        (T : Entity_Id; Def : Node_Id);
334    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
335                                                 (T : Entity_Id; Def : Node_Id);
336
337    procedure Analyze_Formal_Private_Type
338      (N   : Node_Id;
339       T   : Entity_Id;
340       Def : Node_Id);
341    --  Creates a new private type, which does not require completion
342
343    procedure Analyze_Generic_Formal_Part (N : Node_Id);
344
345    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id);
346    --  Create a new access type with the given designated type
347
348    function Analyze_Associations
349      (I_Node  : Node_Id;
350       Formals : List_Id;
351       F_Copy  : List_Id) return List_Id;
352    --  At instantiation time, build the list of associations between formals
353    --  and actuals. Each association becomes a renaming declaration for the
354    --  formal entity. F_Copy is the analyzed list of formals in the generic
355    --  copy. It is used to apply legality checks to the actuals. I_Node is the
356    --  instantiation node itself.
357
358    procedure Analyze_Subprogram_Instantiation
359      (N : Node_Id;
360       K : Entity_Kind);
361
362    procedure Build_Instance_Compilation_Unit_Nodes
363      (N        : Node_Id;
364       Act_Body : Node_Id;
365       Act_Decl : Node_Id);
366    --  This procedure is used in the case where the generic instance of a
367    --  subprogram body or package body is a library unit. In this case, the
368    --  original library unit node for the generic instantiation must be
369    --  replaced by the resulting generic body, and a link made to a new
370    --  compilation unit node for the generic declaration. The argument N is
371    --  the original generic instantiation. Act_Body and Act_Decl are the body
372    --  and declaration of the instance (either package body and declaration
373    --  nodes or subprogram body and declaration nodes depending on the case).
374    --  On return, the node N has been rewritten with the actual body.
375
376    procedure Check_Access_Definition (N : Node_Id);
377    --  Subsidiary routine to null exclusion processing. Perform an assertion
378    --  check on Ada version and the presence of an access definition in N.
379
380    procedure Check_Formal_Packages (P_Id : Entity_Id);
381    --  Apply the following to all formal packages in generic associations
382
383    procedure Check_Formal_Package_Instance
384      (Formal_Pack : Entity_Id;
385       Actual_Pack : Entity_Id);
386    --  Verify that the actuals of the actual instance match the actuals of
387    --  the template for a formal package that is not declared with a box.
388
389    procedure Check_Forward_Instantiation (Decl : Node_Id);
390    --  If the generic is a local entity and the corresponding body has not
391    --  been seen yet, flag enclosing packages to indicate that it will be
392    --  elaborated after the generic body. Subprograms declared in the same
393    --  package cannot be inlined by the front-end because front-end inlining
394    --  requires a strict linear order of elaboration.
395
396    procedure Check_Hidden_Child_Unit
397      (N           : Node_Id;
398       Gen_Unit    : Entity_Id;
399       Act_Decl_Id : Entity_Id);
400    --  If the generic unit is an implicit child instance within a parent
401    --  instance, we need to make an explicit test that it is not hidden by
402    --  a child instance of the same name and parent.
403
404    procedure Check_Generic_Actuals
405      (Instance      : Entity_Id;
406       Is_Formal_Box : Boolean);
407    --  Similar to previous one. Check the actuals in the instantiation,
408    --  whose views can change between the point of instantiation and the point
409    --  of instantiation of the body. In addition, mark the generic renamings
410    --  as generic actuals, so that they are not compatible with other actuals.
411    --  Recurse on an actual that is a formal package whose declaration has
412    --  a box.
413
414    function Contains_Instance_Of
415      (Inner : Entity_Id;
416       Outer : Entity_Id;
417       N     : Node_Id) return Boolean;
418    --  Inner is instantiated within the generic Outer. Check whether Inner
419    --  directly or indirectly contains an instance of Outer or of one of its
420    --  parents, in the case of a subunit. Each generic unit holds a list of
421    --  the entities instantiated within (at any depth). This procedure
422    --  determines whether the set of such lists contains a cycle, i.e. an
423    --  illegal circular instantiation.
424
425    function Denotes_Formal_Package
426      (Pack    : Entity_Id;
427       On_Exit : Boolean := False) return Boolean;
428    --  Returns True if E is a formal package of an enclosing generic, or
429    --  the actual for such a formal in an enclosing instantiation. If such
430    --  a package is used as a formal in an nested generic, or as an actual
431    --  in a nested instantiation, the visibility of ITS formals should not
432    --  be modified. When called from within Restore_Private_Views, the flag
433    --  On_Exit is true, to indicate that the search for a possible enclosing
434    --  instance should ignore the current one.
435
436    function Find_Actual_Type
437      (Typ       : Entity_Id;
438       Gen_Scope : Entity_Id) return Entity_Id;
439    --  When validating the actual types of a child instance, check whether
440    --  the formal is a formal type of the parent unit, and retrieve the current
441    --  actual for it. Typ is the entity in the analyzed formal type declaration
442    --  (component or index type of an array type, or designated type of an
443    --  access formal) and Gen_Scope is the scope of the analyzed formal array
444    --  or access type. The desired actual may be a formal of a parent, or may
445    --  be declared in a formal package of a parent. In both cases it is a
446    --  generic actual type because it appears within a visible instance.
447    --  Ambiguities may still arise if two homonyms are declared in two formal
448    --  packages, and the prefix of the formal type may be needed to resolve
449    --  the ambiguity in the instance ???
450
451    function In_Same_Declarative_Part
452      (F_Node : Node_Id;
453       Inst   : Node_Id) return Boolean;
454    --  True if the instantiation Inst and the given freeze_node F_Node appear
455    --  within the same declarative part, ignoring subunits, but with no inter-
456    --  vening suprograms or concurrent units. If true, the freeze node
457    --  of the instance can be placed after the freeze node of the parent,
458    --  which it itself an instance.
459
460    function In_Main_Context (E : Entity_Id) return Boolean;
461    --  Check whether an instantiation is in the context of the main unit.
462    --  Used to determine whether its body should be elaborated to allow
463    --  front-end inlining.
464
465    function Is_Generic_Formal (E : Entity_Id) return Boolean;
466    --  Utility to determine whether a given entity is declared by means of
467    --  of a formal parameter declaration. Used to set properly the visiblity
468    --  of generic formals of a generic package declared with a box or with
469    --  partial parametrization.
470
471    procedure Set_Instance_Env
472      (Gen_Unit : Entity_Id;
473       Act_Unit : Entity_Id);
474    --  Save current instance on saved environment, to be used to determine
475    --  the global status of entities in nested instances. Part of Save_Env.
476    --  called after verifying that the generic unit is legal for the instance,
477    --  The procedure also examines whether the generic unit is a predefined
478    --  unit, in order to set configuration switches accordingly. As a result
479    --  the procedure must be called after analyzing and freezing the actuals.
480
481    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id);
482    --  Associate analyzed generic parameter with corresponding
483    --  instance. Used for semantic checks at instantiation time.
484
485    function Has_Been_Exchanged (E : Entity_Id) return Boolean;
486    --  Traverse the Exchanged_Views list to see if a type was private
487    --  and has already been flipped during this phase of instantiation.
488
489    procedure Hide_Current_Scope;
490    --  When compiling a generic child unit, the parent context must be
491    --  present, but the instance and all entities that may be generated
492    --  must be inserted in the current scope. We leave the current scope
493    --  on the stack, but make its entities invisible to avoid visibility
494    --  problems. This is reversed at the end of instantiations. This is
495    --  not done for the instantiation of the bodies, which only require the
496    --  instances of the generic parents to be in scope.
497
498    procedure Install_Body
499      (Act_Body : Node_Id;
500       N        : Node_Id;
501       Gen_Body : Node_Id;
502       Gen_Decl : Node_Id);
503    --  If the instantiation happens textually before the body of the generic,
504    --  the instantiation of the body must be analyzed after the generic body,
505    --  and not at the point of instantiation. Such early instantiations can
506    --  happen if the generic and the instance appear in  a package declaration
507    --  because the generic body can only appear in the corresponding package
508    --  body. Early instantiations can also appear if generic, instance and
509    --  body are all in the declarative part of a subprogram or entry. Entities
510    --  of packages that are early instantiations are delayed, and their freeze
511    --  node appears after the generic body.
512
513    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id);
514    --  Insert freeze node at the end of the declarative part that includes the
515    --  instance node N. If N is in the visible part of an enclosing package
516    --  declaration, the freeze node has to be inserted at the end of the
517    --  private declarations, if any.
518
519    procedure Freeze_Subprogram_Body
520      (Inst_Node : Node_Id;
521       Gen_Body  : Node_Id;
522       Pack_Id   : Entity_Id);
523    --  The generic body may appear textually after the instance, including
524    --  in the proper body of a stub, or within a different package instance.
525    --  Given that the instance can only be elaborated after the generic, we
526    --  place freeze_nodes for the instance and/or for packages that may enclose
527    --  the instance and the generic, so that the back-end can establish the
528    --  proper order of elaboration.
529
530    procedure Init_Env;
531    --  Establish environment for subsequent instantiation. Separated from
532    --  Save_Env because data-structures for visibility handling must be
533    --  initialized before call to Check_Generic_Child_Unit.
534
535    procedure Install_Formal_Packages (Par : Entity_Id);
536    --  If any of the formals of the parent are formal packages with box,
537    --  their formal parts are visible in the parent and thus in the child
538    --  unit as well. Analogous to what is done in Check_Generic_Actuals
539    --  for the unit itself. This procedure is also used in an instance, to
540    --  make visible the proper entities of the actual for a formal package
541    --  declared with a box.
542
543    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False);
544    --  When compiling an instance of a child unit the parent (which is
545    --  itself an instance) is an enclosing scope that must be made
546    --  immediately visible. This procedure is also used to install the non-
547    --  generic parent of a generic child unit when compiling its body, so
548    --  that full views of types in the parent are made visible.
549
550    procedure Remove_Parent (In_Body : Boolean := False);
551    --  Reverse effect after instantiation of child is complete
552
553    procedure Inline_Instance_Body
554      (N        : Node_Id;
555       Gen_Unit : Entity_Id;
556       Act_Decl : Node_Id);
557    --  If front-end inlining is requested, instantiate the package body,
558    --  and preserve the visibility of its compilation unit, to insure
559    --  that successive instantiations succeed.
560
561    --  The functions Instantiate_XXX perform various legality checks and build
562    --  the declarations for instantiated generic parameters. In all of these
563    --  Formal is the entity in the generic unit, Actual is the entity of
564    --  expression in the generic associations, and Analyzed_Formal is the
565    --  formal in the generic copy, which contains the semantic information to
566    --  be used to validate the actual.
567
568    function Instantiate_Object
569      (Formal          : Node_Id;
570       Actual          : Node_Id;
571       Analyzed_Formal : Node_Id) return List_Id;
572
573    function Instantiate_Type
574      (Formal          : Node_Id;
575       Actual          : Node_Id;
576       Analyzed_Formal : Node_Id;
577       Actual_Decls    : List_Id) return List_Id;
578
579    function Instantiate_Formal_Subprogram
580      (Formal          : Node_Id;
581       Actual          : Node_Id;
582       Analyzed_Formal : Node_Id) return Node_Id;
583
584    function Instantiate_Formal_Package
585      (Formal          : Node_Id;
586       Actual          : Node_Id;
587       Analyzed_Formal : Node_Id) return List_Id;
588    --  If the formal package is declared with a box, special visibility rules
589    --  apply to its formals: they are in the visible part of the package. This
590    --  is true in the declarative region of the formal package, that is to say
591    --  in the enclosing generic or instantiation. For an instantiation, the
592    --  parameters of the formal package are made visible in an explicit step.
593    --  Furthermore, if the actual is a visible use_clause, these formals must
594    --  be made potentially use_visible as well. On exit from the enclosing
595    --  instantiation, the reverse must be done.
596
597    --  For a formal package declared without a box, there are conformance rules
598    --  that apply to the actuals in the generic declaration and the actuals of
599    --  the actual package in the enclosing instantiation. The simplest way to
600    --  apply these rules is to repeat the instantiation of the formal package
601    --  in the context of the enclosing instance, and compare the generic
602    --  associations of this instantiation with those of the actual package.
603    --  This internal instantiation only needs to contain the renamings of the
604    --  formals: the visible and private declarations themselves need not be
605    --  created.
606
607    --  In Ada2005, the formal package may be only partially parametrized. In
608    --  that case the visibility step must make visible those actuals whose
609    --  corresponding formals were given with a box. A final complication
610    --  involves inherited operations from formal derived types, which must be
611    --  visible if the type is.
612
613    function Is_In_Main_Unit (N : Node_Id) return Boolean;
614    --  Test if given node is in the main unit
615
616    procedure Load_Parent_Of_Generic (N : Node_Id; Spec : Node_Id);
617    --  If the generic appears in a separate non-generic library unit,
618    --  load the corresponding body to retrieve the body of the generic.
619    --  N is the node for the generic instantiation, Spec is the generic
620    --  package declaration.
621
622    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id);
623    --  Add the context clause of the unit containing a generic unit to
624    --  an instantiation that is a compilation unit.
625
626    function Get_Associated_Node (N : Node_Id) return Node_Id;
627    --  In order to propagate semantic information back from the analyzed
628    --  copy to the original generic, we maintain links between selected nodes
629    --  in the generic and their corresponding copies. At the end of generic
630    --  analysis, the routine Save_Global_References traverses the generic
631    --  tree, examines the semantic information, and preserves the links to
632    --  those nodes that contain global information. At instantiation, the
633    --  information from the associated node is placed on the new copy, so
634    --  that name resolution is not repeated.
635    --
636    --  Three kinds of source nodes have associated nodes:
637    --
638    --    a) those that can reference (denote) entities, that is identifiers,
639    --       character literals, expanded_names, operator symbols, operators,
640    --       and attribute reference nodes. These nodes have an Entity field
641    --       and are the set of nodes that are in N_Has_Entity.
642    --
643    --    b) aggregates (N_Aggregate and N_Extension_Aggregate)
644    --
645    --    c) selected components (N_Selected_Component)
646    --
647    --  For the first class, the associated node preserves the entity if it is
648    --  global. If the generic contains nested instantiations, the associated
649    --  node itself has been recopied, and a chain of them must be followed.
650    --
651    --  For aggregates, the associated node allows retrieval of the type, which
652    --  may otherwise not appear in the generic. The view of this type may be
653    --  different between generic and instantiation, and the full view can be
654    --  installed before the instantiation is analyzed. For aggregates of
655    --  type extensions, the same view exchange may have to be performed for
656    --  some of the ancestor types, if their view is private at the point of
657    --  instantiation.
658    --
659    --  Nodes that are selected components in the parse tree may be rewritten
660    --  as expanded names after resolution, and must be treated as potential
661    --  entity holders. which is why they also have an Associated_Node.
662    --
663    --  Nodes that do not come from source, such as freeze nodes, do not appear
664    --  in the generic tree, and need not have an associated node.
665    --
666    --  The associated node is stored in the Associated_Node field. Note that
667    --  this field overlaps Entity, which is fine, because the whole point is
668    --  that we don't need or want the normal Entity field in this situation.
669
670    procedure Move_Freeze_Nodes
671      (Out_Of : Entity_Id;
672       After  : Node_Id;
673       L      : List_Id);
674    --  Freeze nodes can be generated in the analysis of a generic unit, but
675    --  will not be seen by the back-end. It is necessary to move those nodes
676    --  to the enclosing scope if they freeze an outer entity. We place them
677    --  at the end of the enclosing generic package, which is semantically
678    --  neutral.
679
680    procedure Pre_Analyze_Actuals (N : Node_Id);
681    --  Analyze actuals to perform name resolution. Full resolution is done
682    --  later, when the expected types are known, but names have to be captured
683    --  before installing parents of generics, that are not visible for the
684    --  actuals themselves.
685
686    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id);
687    --  Verify that an attribute that appears as the default for a formal
688    --  subprogram is a function or procedure with the correct profile.
689
690    -------------------------------------------
691    -- Data Structures for Generic Renamings --
692    -------------------------------------------
693
694    --  The map Generic_Renamings associates generic entities with their
695    --  corresponding actuals. Currently used to validate type instances.
696    --  It will eventually be used for all generic parameters to eliminate
697    --  the need for overload resolution in the instance.
698
699    type Assoc_Ptr is new Int;
700
701    Assoc_Null : constant Assoc_Ptr := -1;
702
703    type Assoc is record
704       Gen_Id         : Entity_Id;
705       Act_Id         : Entity_Id;
706       Next_In_HTable : Assoc_Ptr;
707    end record;
708
709    package Generic_Renamings is new Table.Table
710      (Table_Component_Type => Assoc,
711       Table_Index_Type     => Assoc_Ptr,
712       Table_Low_Bound      => 0,
713       Table_Initial        => 10,
714       Table_Increment      => 100,
715       Table_Name           => "Generic_Renamings");
716
717    --  Variable to hold enclosing instantiation. When the environment is
718    --  saved for a subprogram inlining, the corresponding Act_Id is empty.
719
720    Current_Instantiated_Parent : Assoc := (Empty, Empty, Assoc_Null);
721
722    --  Hash table for associations
723
724    HTable_Size : constant := 37;
725    type HTable_Range is range 0 .. HTable_Size - 1;
726
727    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr);
728    function  Next_Assoc     (E : Assoc_Ptr) return Assoc_Ptr;
729    function Get_Gen_Id      (E : Assoc_Ptr) return Entity_Id;
730    function Hash            (F : Entity_Id) return HTable_Range;
731
732    package Generic_Renamings_HTable is new GNAT.HTable.Static_HTable (
733       Header_Num => HTable_Range,
734       Element    => Assoc,
735       Elmt_Ptr   => Assoc_Ptr,
736       Null_Ptr   => Assoc_Null,
737       Set_Next   => Set_Next_Assoc,
738       Next       => Next_Assoc,
739       Key        => Entity_Id,
740       Get_Key    => Get_Gen_Id,
741       Hash       => Hash,
742       Equal      => "=");
743
744    Exchanged_Views : Elist_Id;
745    --  This list holds the private views that have been exchanged during
746    --  instantiation to restore the visibility of the generic declaration.
747    --  (see comments above). After instantiation, the current visibility is
748    --  reestablished by means of a traversal of this list.
749
750    Hidden_Entities : Elist_Id;
751    --  This list holds the entities of the current scope that are removed
752    --  from immediate visibility when instantiating a child unit. Their
753    --  visibility is restored in Remove_Parent.
754
755    --  Because instantiations can be recursive, the following must be saved
756    --  on entry and restored on exit from an instantiation (spec or body).
757    --  This is done by the two procedures Save_Env and Restore_Env. For
758    --  package and subprogram instantiations (but not for the body instances)
759    --  the action of Save_Env is done in two steps: Init_Env is called before
760    --  Check_Generic_Child_Unit, because setting the parent instances requires
761    --  that the visibility data structures be properly initialized. Once the
762    --  generic is unit is validated, Set_Instance_Env completes Save_Env.
763
764    Parent_Unit_Visible : Boolean := False;
765    --  Parent_Unit_Visible is used when the generic is a child unit, and
766    --  indicates whether the ultimate parent of the generic is visible in the
767    --  instantiation environment. It is used to reset the visibility of the
768    --  parent at the end of the instantiation (see Remove_Parent).
769
770    Instance_Parent_Unit : Entity_Id := Empty;
771    --  This records the ultimate parent unit of an instance of a generic
772    --  child unit and is used in conjunction with Parent_Unit_Visible to
773    --  indicate the unit to which the Parent_Unit_Visible flag corresponds.
774
775    type Instance_Env is record
776       Instantiated_Parent  : Assoc;
777       Exchanged_Views      : Elist_Id;
778       Hidden_Entities      : Elist_Id;
779       Current_Sem_Unit     : Unit_Number_Type;
780       Parent_Unit_Visible  : Boolean   := False;
781       Instance_Parent_Unit : Entity_Id := Empty;
782       Switches             : Config_Switches_Type;
783    end record;
784
785    package Instance_Envs is new Table.Table (
786      Table_Component_Type => Instance_Env,
787      Table_Index_Type     => Int,
788      Table_Low_Bound      => 0,
789      Table_Initial        => 32,
790      Table_Increment      => 100,
791      Table_Name           => "Instance_Envs");
792
793    procedure Restore_Private_Views
794      (Pack_Id    : Entity_Id;
795       Is_Package : Boolean := True);
796    --  Restore the private views of external types, and unmark the generic
797    --  renamings of actuals, so that they become comptible subtypes again.
798    --  For subprograms, Pack_Id is the package constructed to hold the
799    --  renamings.
800
801    procedure Switch_View (T : Entity_Id);
802    --  Switch the partial and full views of a type and its private
803    --  dependents (i.e. its subtypes and derived types).
804
805    ------------------------------------
806    -- Structures for Error Reporting --
807    ------------------------------------
808
809    Instantiation_Node : Node_Id;
810    --  Used by subprograms that validate instantiation of formal parameters
811    --  where there might be no actual on which to place the error message.
812    --  Also used to locate the instantiation node for generic subunits.
813
814    Instantiation_Error : exception;
815    --  When there is a semantic error in the generic parameter matching,
816    --  there is no point in continuing the instantiation, because the
817    --  number of cascaded errors is unpredictable. This exception aborts
818    --  the instantiation process altogether.
819
820    S_Adjustment : Sloc_Adjustment;
821    --  Offset created for each node in an instantiation, in order to keep
822    --  track of the source position of the instantiation in each of its nodes.
823    --  A subsequent semantic error or warning on a construct of the instance
824    --  points to both places: the original generic node, and the point of
825    --  instantiation. See Sinput and Sinput.L for additional details.
826
827    ------------------------------------------------------------
828    -- Data structure for keeping track when inside a Generic --
829    ------------------------------------------------------------
830
831    --  The following table is used to save values of the Inside_A_Generic
832    --  flag (see spec of Sem) when they are saved by Start_Generic.
833
834    package Generic_Flags is new Table.Table (
835      Table_Component_Type => Boolean,
836      Table_Index_Type     => Int,
837      Table_Low_Bound      => 0,
838      Table_Initial        => 32,
839      Table_Increment      => 200,
840      Table_Name           => "Generic_Flags");
841
842    ---------------------------
843    -- Abandon_Instantiation --
844    ---------------------------
845
846    procedure Abandon_Instantiation (N : Node_Id) is
847    begin
848       Error_Msg_N ("\instantiation abandoned!", N);
849       raise Instantiation_Error;
850    end Abandon_Instantiation;
851
852    --------------------------
853    -- Analyze_Associations --
854    --------------------------
855
856    function Analyze_Associations
857      (I_Node  : Node_Id;
858       Formals : List_Id;
859       F_Copy  : List_Id) return List_Id
860    is
861       Actual_Types : constant Elist_Id  := New_Elmt_List;
862       Assoc        : constant List_Id   := New_List;
863       Default_Actuals : constant Elist_Id  := New_Elmt_List;
864       Gen_Unit     : constant Entity_Id := Defining_Entity (Parent (F_Copy));
865       Actuals         : List_Id;
866       Actual          : Node_Id;
867       Formal          : Node_Id;
868       Next_Formal     : Node_Id;
869       Temp_Formal     : Node_Id;
870       Analyzed_Formal : Node_Id;
871       Match           : Node_Id;
872       Named           : Node_Id;
873       First_Named     : Node_Id := Empty;
874
875       Default_Formals : constant List_Id := New_List;
876       --  If an Other_Choice is present, some of the formals may be defaulted.
877       --  To simplify the treatement of visibility in an instance, we introduce
878       --  individual defaults for each such formal. These defaults are
879       --  appended to the list of associations and replace the Others_Choice.
880
881       Found_Assoc     : Node_Id;
882       --  Association for the current formal being match. Empty if there are
883       --  no remaining actuals, or if there is no named association with the
884       --  name of the formal.
885
886       Is_Named_Assoc  : Boolean;
887       Num_Matched     : Int := 0;
888       Num_Actuals     : Int := 0;
889
890       Others_Present  : Boolean := False;
891       --  In Ada 2005, indicates partial parametrization of of a formal
892       --  package. As usual an others association must be last in the list.
893
894       function Matching_Actual
895         (F   : Entity_Id;
896          A_F : Entity_Id) return Node_Id;
897       --  Find actual that corresponds to a given a formal parameter. If the
898       --  actuals are positional, return the next one, if any. If the actuals
899       --  are named, scan the parameter associations to find the right one.
900       --  A_F is the corresponding entity in the analyzed generic,which is
901       --  placed on the selector name for ASIS use.
902
903       --  In Ada 2005, a named association may be given with a box, in which
904       --  case Matching_Actual sets Found_Assoc to the generic association,
905       --  but return Empty for the actual itself. In this case the code below
906       --  creates a corresponding declaration for the formal.
907
908       function Partial_Parametrization return Boolean;
909       --  Ada 2005: if no match is found for a given formal, check if the
910       --  association for it includes a box, or whether the associations
911       --  include an Others clause.
912
913       procedure Process_Default (F : Entity_Id);
914       --  Add a copy of the declaration of generic formal  F to the list of
915       --  associations, and add an explicit box association for F  if there
916       --  is none yet, and the default comes from an Others_Choice.
917
918       procedure Set_Analyzed_Formal;
919       --  Find the node in the generic copy that corresponds to a given formal.
920       --  The semantic information on this node is used to perform legality
921       --  checks on the actuals. Because semantic analysis can introduce some
922       --  anonymous entities or modify the declaration node itself, the
923       --  correspondence between the two lists is not one-one. In addition to
924       --  anonymous types, the presence a formal equality will introduce an
925       --  implicit declaration for the corresponding inequality.
926
927       ---------------------
928       -- Matching_Actual --
929       ---------------------
930
931       function Matching_Actual
932         (F   : Entity_Id;
933          A_F : Entity_Id) return Node_Id
934       is
935          Prev  : Node_Id;
936          Act   : Node_Id;
937
938       begin
939          Is_Named_Assoc := False;
940
941          --  End of list of purely positional parameters
942
943          if No (Actual)
944            or else Nkind (Actual) = N_Others_Choice
945          then
946             Found_Assoc := Empty;
947             Act         := Empty;
948
949          --  Case of positional parameter corresponding to current formal
950
951          elsif No (Selector_Name (Actual)) then
952             Found_Assoc := Actual;
953             Act :=  Explicit_Generic_Actual_Parameter (Actual);
954             Num_Matched := Num_Matched + 1;
955             Next (Actual);
956
957          --  Otherwise scan list of named actuals to find the one with the
958          --  desired name. All remaining actuals have explicit names.
959
960          else
961             Is_Named_Assoc := True;
962             Found_Assoc := Empty;
963             Act         := Empty;
964             Prev        := Empty;
965
966             while Present (Actual) loop
967                if Chars (Selector_Name (Actual)) = Chars (F) then
968                   Set_Entity (Selector_Name (Actual), A_F);
969                   Set_Etype  (Selector_Name (Actual), Etype (A_F));
970                   Generate_Reference (A_F, Selector_Name (Actual));
971                   Found_Assoc := Actual;
972                   Act :=  Explicit_Generic_Actual_Parameter (Actual);
973                   Num_Matched := Num_Matched + 1;
974                   exit;
975                end if;
976
977                Prev := Actual;
978                Next (Actual);
979             end loop;
980
981             --  Reset for subsequent searches. In most cases the named
982             --  associations are in order. If they are not, we reorder them
983             --  to avoid scanning twice the same actual. This is not just a
984             --  question of efficiency: there may be multiple defaults with
985             --  boxes that have the same name. In a nested instantiation we
986             --  insert actuals for those defaults, and cannot rely on their
987             --  names to disambiguate them.
988
989             if Actual = First_Named  then
990                Next (First_Named);
991
992             elsif Present (Actual) then
993                Insert_Before (First_Named, Remove_Next (Prev));
994             end if;
995
996             Actual := First_Named;
997          end if;
998
999          return Act;
1000       end Matching_Actual;
1001
1002       -----------------------------
1003       -- Partial_Parametrization --
1004       -----------------------------
1005
1006       function Partial_Parametrization return Boolean is
1007       begin
1008          return Others_Present
1009           or else (Present (Found_Assoc) and then Box_Present (Found_Assoc));
1010       end Partial_Parametrization;
1011
1012       ---------------------
1013       -- Process_Default --
1014       ---------------------
1015
1016       procedure Process_Default (F : Entity_Id)  is
1017          Loc     : constant Source_Ptr := Sloc (I_Node);
1018          Decl    : Node_Id;
1019          Default : Node_Id;
1020          Id      : Entity_Id;
1021
1022       begin
1023          --  Append copy of formal declaration to associations, and create
1024          --  new defining identifier for it.
1025
1026          Decl := New_Copy_Tree (F);
1027
1028          if Nkind (F) = N_Formal_Concrete_Subprogram_Declaration then
1029             Id :=
1030                Make_Defining_Identifier (Sloc (Defining_Entity (F)),
1031                  Chars => Chars (Defining_Entity (F)));
1032             Set_Defining_Unit_Name (Specification (Decl), Id);
1033
1034          else
1035             Id :=
1036               Make_Defining_Identifier (Sloc (Defining_Entity (F)),
1037                 Chars => Chars (Defining_Identifier (F)));
1038             Set_Defining_Identifier (Decl, Id);
1039          end if;
1040
1041          Append (Decl, Assoc);
1042
1043          if No (Found_Assoc) then
1044             Default :=
1045                Make_Generic_Association (Loc,
1046                  Selector_Name => New_Occurrence_Of (Id, Loc),
1047                  Explicit_Generic_Actual_Parameter => Empty);
1048             Set_Box_Present (Default);
1049             Append (Default, Default_Formals);
1050          end if;
1051       end Process_Default;
1052
1053       -------------------------
1054       -- Set_Analyzed_Formal --
1055       -------------------------
1056
1057       procedure Set_Analyzed_Formal is
1058          Kind : Node_Kind;
1059       begin
1060          while Present (Analyzed_Formal) loop
1061             Kind := Nkind (Analyzed_Formal);
1062
1063             case Nkind (Formal) is
1064
1065                when N_Formal_Subprogram_Declaration =>
1066                   exit when Kind in N_Formal_Subprogram_Declaration
1067                     and then
1068                       Chars
1069                         (Defining_Unit_Name (Specification (Formal))) =
1070                       Chars
1071                         (Defining_Unit_Name (Specification (Analyzed_Formal)));
1072
1073                when N_Formal_Package_Declaration =>
1074                   exit when
1075                     Kind = N_Formal_Package_Declaration
1076                       or else
1077                     Kind = N_Generic_Package_Declaration
1078                       or else
1079                     Kind = N_Package_Declaration;
1080
1081                when N_Use_Package_Clause | N_Use_Type_Clause => exit;
1082
1083                when others =>
1084
1085                   --  Skip freeze nodes, and nodes inserted to replace
1086                   --  unrecognized pragmas.
1087
1088                   exit when
1089                     Kind not in N_Formal_Subprogram_Declaration
1090                       and then Kind /= N_Subprogram_Declaration
1091                       and then Kind /= N_Freeze_Entity
1092                       and then Kind /= N_Null_Statement
1093                       and then Kind /= N_Itype_Reference
1094                       and then Chars (Defining_Identifier (Formal)) =
1095                                Chars (Defining_Identifier (Analyzed_Formal));
1096             end case;
1097
1098             Next (Analyzed_Formal);
1099          end loop;
1100       end Set_Analyzed_Formal;
1101
1102    --  Start of processing for Analyze_Associations
1103
1104    begin
1105       Actuals := Generic_Associations (I_Node);
1106
1107       if Present (Actuals) then
1108
1109          --  check for an Others choice, indicating a partial parametrization
1110          --  for a formal package.
1111
1112          Actual := First (Actuals);
1113          while Present (Actual) loop
1114             if Nkind (Actual) = N_Others_Choice then
1115                Others_Present := True;
1116                if Present (Next (Actual)) then
1117                   Error_Msg_N ("others must be last association", Actual);
1118                end if;
1119
1120                --  This subprogram is used both for formal packages and for
1121                --  instantiations. For the latter, associations must all be
1122                --  explicit.
1123
1124                if Nkind (I_Node) /= N_Formal_Package_Declaration
1125                  and then Comes_From_Source (I_Node)
1126                then
1127                   Error_Msg_N
1128                     ("others association not allowed in an instance",
1129                       Actual);
1130                end if;
1131
1132                --  In any case, nothing to do after the others association
1133
1134                exit;
1135
1136             elsif Box_Present (Actual)
1137               and then Comes_From_Source (I_Node)
1138               and then Nkind (I_Node) /= N_Formal_Package_Declaration
1139             then
1140                Error_Msg_N
1141                  ("box association not allowed in an instance", Actual);
1142             end if;
1143
1144             Next (Actual);
1145          end loop;
1146
1147          --  If named associations are present, save first named association
1148          --  (it may of course be Empty) to facilitate subsequent name search.
1149
1150          First_Named := First (Actuals);
1151          while Present (First_Named)
1152            and then Nkind (First_Named) /= N_Others_Choice
1153            and then No (Selector_Name (First_Named))
1154          loop
1155             Num_Actuals := Num_Actuals + 1;
1156             Next (First_Named);
1157          end loop;
1158       end if;
1159
1160       Named := First_Named;
1161       while Present (Named) loop
1162          if Nkind (Named) /= N_Others_Choice
1163            and then  No (Selector_Name (Named))
1164          then
1165             Error_Msg_N ("invalid positional actual after named one", Named);
1166             Abandon_Instantiation (Named);
1167          end if;
1168
1169          --  A named association may lack an actual parameter, if it was
1170          --  introduced for a default subprogram that turns out to be local
1171          --  to the outer instantiation.
1172
1173          if Nkind (Named) /= N_Others_Choice
1174            and then  Present (Explicit_Generic_Actual_Parameter (Named))
1175          then
1176             Num_Actuals := Num_Actuals + 1;
1177          end if;
1178
1179          Next (Named);
1180       end loop;
1181
1182       if Present (Formals) then
1183          Formal := First_Non_Pragma (Formals);
1184          Analyzed_Formal := First_Non_Pragma (F_Copy);
1185
1186          if Present (Actuals) then
1187             Actual := First (Actuals);
1188
1189          --  All formals should have default values
1190
1191          else
1192             Actual := Empty;
1193          end if;
1194
1195          while Present (Formal) loop
1196             Set_Analyzed_Formal;
1197             Next_Formal := Next_Non_Pragma (Formal);
1198
1199             case Nkind (Formal) is
1200                when N_Formal_Object_Declaration =>
1201                   Match :=
1202                     Matching_Actual (
1203                       Defining_Identifier (Formal),
1204                       Defining_Identifier (Analyzed_Formal));
1205
1206                   if No (Match) and then Partial_Parametrization then
1207                      Process_Default (Formal);
1208                   else
1209                      Append_List
1210                        (Instantiate_Object (Formal, Match, Analyzed_Formal),
1211                         Assoc);
1212                   end if;
1213
1214                when N_Formal_Type_Declaration =>
1215                   Match :=
1216                     Matching_Actual (
1217                       Defining_Identifier (Formal),
1218                       Defining_Identifier (Analyzed_Formal));
1219
1220                   if No (Match) then
1221                      if Partial_Parametrization then
1222                         Process_Default (Formal);
1223
1224                      else
1225                         Error_Msg_Sloc := Sloc (Gen_Unit);
1226                         Error_Msg_NE
1227                           ("missing actual&",
1228                             Instantiation_Node,
1229                               Defining_Identifier (Formal));
1230                         Error_Msg_NE ("\in instantiation of & declared#",
1231                             Instantiation_Node, Gen_Unit);
1232                         Abandon_Instantiation (Instantiation_Node);
1233                      end if;
1234
1235                   else
1236                      Analyze (Match);
1237                      Append_List
1238                        (Instantiate_Type
1239                          (Formal, Match, Analyzed_Formal, Assoc),
1240                        Assoc);
1241
1242                      --  An instantiation is a freeze point for the actuals,
1243                      --  unless this is a rewritten formal package.
1244
1245                      if Nkind (I_Node) /= N_Formal_Package_Declaration then
1246                         Append_Elmt (Entity (Match), Actual_Types);
1247                      end if;
1248                   end if;
1249
1250                   --  A remote access-to-class-wide type must not be an
1251                   --  actual parameter for a generic formal of an access
1252                   --  type (E.2.2 (17)).
1253
1254                   if Nkind (Analyzed_Formal) = N_Formal_Type_Declaration
1255                     and then
1256                       Nkind (Formal_Type_Definition (Analyzed_Formal)) =
1257                                             N_Access_To_Object_Definition
1258                   then
1259                      Validate_Remote_Access_To_Class_Wide_Type (Match);
1260                   end if;
1261
1262                when N_Formal_Subprogram_Declaration =>
1263                   Match :=
1264                     Matching_Actual (
1265                       Defining_Unit_Name (Specification (Formal)),
1266                       Defining_Unit_Name (Specification (Analyzed_Formal)));
1267
1268                   --  If the formal subprogram has the same name as
1269                   --  another formal subprogram of the generic, then
1270                   --  a named association is illegal (12.3(9)). Exclude
1271                   --  named associations that are generated for a nested
1272                   --  instance.
1273
1274                   if Present (Match)
1275                     and then Is_Named_Assoc
1276                     and then Comes_From_Source (Found_Assoc)
1277                   then
1278                      Temp_Formal := First (Formals);
1279                      while Present (Temp_Formal) loop
1280                         if Nkind (Temp_Formal) in
1281                              N_Formal_Subprogram_Declaration
1282                           and then Temp_Formal /= Formal
1283                           and then
1284                             Chars (Selector_Name (Found_Assoc)) =
1285                               Chars (Defining_Unit_Name
1286                                        (Specification (Temp_Formal)))
1287                         then
1288                            Error_Msg_N
1289                              ("name not allowed for overloaded formal",
1290                               Found_Assoc);
1291                            Abandon_Instantiation (Instantiation_Node);
1292                         end if;
1293
1294                         Next (Temp_Formal);
1295                      end loop;
1296                   end if;
1297
1298                   --  If there is no corresponding actual, this may be case of
1299                   --  partial parametrization, or else the formal has a default
1300                   --  or a box.
1301
1302                   if No (Match)
1303                     and then  Partial_Parametrization
1304                   then
1305                      Process_Default (Formal);
1306                   else
1307                      Append_To (Assoc,
1308                        Instantiate_Formal_Subprogram
1309                          (Formal, Match, Analyzed_Formal));
1310                   end if;
1311
1312                   --  If this is a nested generic, preserve default for later
1313                   --  instantiations.
1314
1315                   if No (Match)
1316                     and then Box_Present (Formal)
1317                   then
1318                      Append_Elmt
1319                        (Defining_Unit_Name (Specification (Last (Assoc))),
1320                         Default_Actuals);
1321                   end if;
1322
1323                when N_Formal_Package_Declaration =>
1324                   Match :=
1325                     Matching_Actual (
1326                       Defining_Identifier (Formal),
1327                       Defining_Identifier (Original_Node (Analyzed_Formal)));
1328
1329                   if No (Match) then
1330                      if Partial_Parametrization then
1331                         Process_Default (Formal);
1332
1333                      else
1334                         Error_Msg_Sloc := Sloc (Gen_Unit);
1335                         Error_Msg_NE
1336                           ("missing actual&",
1337                             Instantiation_Node, Defining_Identifier (Formal));
1338                         Error_Msg_NE ("\in instantiation of & declared#",
1339                             Instantiation_Node, Gen_Unit);
1340
1341                         Abandon_Instantiation (Instantiation_Node);
1342                      end if;
1343
1344                   else
1345                      Analyze (Match);
1346                      Append_List
1347                        (Instantiate_Formal_Package
1348                          (Formal, Match, Analyzed_Formal),
1349                         Assoc);
1350                   end if;
1351
1352                --  For use type and use package appearing in the generic part,
1353                --  we have already copied them, so we can just move them where
1354                --  they belong (we mustn't recopy them since this would mess up
1355                --  the Sloc values).
1356
1357                when N_Use_Package_Clause |
1358                     N_Use_Type_Clause    =>
1359                   if Nkind (Original_Node (I_Node)) =
1360                     N_Formal_Package_Declaration
1361                   then
1362                      Append (New_Copy_Tree (Formal), Assoc);
1363                   else
1364                      Remove (Formal);
1365                      Append (Formal, Assoc);
1366                   end if;
1367
1368                when others =>
1369                   raise Program_Error;
1370
1371             end case;
1372
1373             Formal := Next_Formal;
1374             Next_Non_Pragma (Analyzed_Formal);
1375          end loop;
1376
1377          if Num_Actuals > Num_Matched then
1378             Error_Msg_Sloc := Sloc (Gen_Unit);
1379
1380             if Present (Selector_Name (Actual)) then
1381                Error_Msg_NE
1382                  ("unmatched actual&",
1383                     Actual, Selector_Name (Actual));
1384                Error_Msg_NE ("\in instantiation of& declared#",
1385                     Actual, Gen_Unit);
1386             else
1387                Error_Msg_NE
1388                  ("unmatched actual in instantiation of& declared#",
1389                    Actual, Gen_Unit);
1390             end if;
1391          end if;
1392
1393       elsif Present (Actuals) then
1394          Error_Msg_N
1395            ("too many actuals in generic instantiation", Instantiation_Node);
1396       end if;
1397
1398       declare
1399          Elmt : Elmt_Id := First_Elmt (Actual_Types);
1400
1401       begin
1402          while Present (Elmt) loop
1403             Freeze_Before (I_Node, Node (Elmt));
1404             Next_Elmt (Elmt);
1405          end loop;
1406       end;
1407
1408       --  If there are default subprograms, normalize the tree by adding
1409       --  explicit associations for them. This is required if the instance
1410       --  appears within a generic.
1411
1412       declare
1413          Elmt  : Elmt_Id;
1414          Subp  : Entity_Id;
1415          New_D : Node_Id;
1416
1417       begin
1418          Elmt := First_Elmt (Default_Actuals);
1419          while Present (Elmt) loop
1420             if No (Actuals) then
1421                Actuals := New_List;
1422                Set_Generic_Associations (I_Node, Actuals);
1423             end if;
1424
1425             Subp := Node (Elmt);
1426             New_D :=
1427               Make_Generic_Association (Sloc (Subp),
1428                 Selector_Name => New_Occurrence_Of (Subp, Sloc (Subp)),
1429                   Explicit_Generic_Actual_Parameter =>
1430                     New_Occurrence_Of (Subp, Sloc (Subp)));
1431             Mark_Rewrite_Insertion (New_D);
1432             Append_To (Actuals, New_D);
1433             Next_Elmt (Elmt);
1434          end loop;
1435       end;
1436
1437       --  If this is a formal package. normalize the parameter list by adding
1438       --  explicit box asssociations for the formals that are covered by an
1439       --  Others_Choice.
1440
1441       if not Is_Empty_List (Default_Formals) then
1442          Append_List (Default_Formals, Formals);
1443       end if;
1444
1445       return Assoc;
1446    end Analyze_Associations;
1447
1448    -------------------------------
1449    -- Analyze_Formal_Array_Type --
1450    -------------------------------
1451
1452    procedure Analyze_Formal_Array_Type
1453      (T   : in out Entity_Id;
1454       Def : Node_Id)
1455    is
1456       DSS : Node_Id;
1457
1458    begin
1459       --  Treated like a non-generic array declaration, with additional
1460       --  semantic checks.
1461
1462       Enter_Name (T);
1463
1464       if Nkind (Def) = N_Constrained_Array_Definition then
1465          DSS := First (Discrete_Subtype_Definitions (Def));
1466          while Present (DSS) loop
1467             if Nkind (DSS) = N_Subtype_Indication
1468               or else Nkind (DSS) = N_Range
1469               or else Nkind (DSS) = N_Attribute_Reference
1470             then
1471                Error_Msg_N ("only a subtype mark is allowed in a formal", DSS);
1472             end if;
1473
1474             Next (DSS);
1475          end loop;
1476       end if;
1477
1478       Array_Type_Declaration (T, Def);
1479       Set_Is_Generic_Type (Base_Type (T));
1480
1481       if Ekind (Component_Type (T)) = E_Incomplete_Type
1482         and then No (Full_View (Component_Type (T)))
1483       then
1484          Error_Msg_N ("premature usage of incomplete type", Def);
1485
1486       --  Check that range constraint is not allowed on the component type
1487       --  of a generic formal array type (AARM 12.5.3(3))
1488
1489       elsif Is_Internal (Component_Type (T))
1490         and then Present (Subtype_Indication (Component_Definition (Def)))
1491         and then Nkind (Original_Node
1492                         (Subtype_Indication (Component_Definition (Def))))
1493           = N_Subtype_Indication
1494       then
1495          Error_Msg_N
1496            ("in a formal, a subtype indication can only be "
1497              & "a subtype mark ('R'M 12.5.3(3))",
1498              Subtype_Indication (Component_Definition (Def)));
1499       end if;
1500
1501    end Analyze_Formal_Array_Type;
1502
1503    ---------------------------------------------
1504    -- Analyze_Formal_Decimal_Fixed_Point_Type --
1505    ---------------------------------------------
1506
1507    --  As for other generic types, we create a valid type representation with
1508    --  legal but arbitrary attributes, whose values are never considered
1509    --  static. For all scalar types we introduce an anonymous base type, with
1510    --  the same attributes. We choose the corresponding integer type to be
1511    --  Standard_Integer.
1512
1513    procedure Analyze_Formal_Decimal_Fixed_Point_Type
1514      (T   : Entity_Id;
1515       Def : Node_Id)
1516    is
1517       Loc       : constant Source_Ptr := Sloc (Def);
1518       Base      : constant Entity_Id :=
1519                     New_Internal_Entity
1520                       (E_Decimal_Fixed_Point_Type,
1521                        Current_Scope, Sloc (Def), 'G');
1522       Int_Base  : constant Entity_Id := Standard_Integer;
1523       Delta_Val : constant Ureal := Ureal_1;
1524       Digs_Val  : constant Uint  := Uint_6;
1525
1526    begin
1527       Enter_Name (T);
1528
1529       Set_Etype          (Base, Base);
1530       Set_Size_Info      (Base, Int_Base);
1531       Set_RM_Size        (Base, RM_Size (Int_Base));
1532       Set_First_Rep_Item (Base, First_Rep_Item (Int_Base));
1533       Set_Digits_Value   (Base, Digs_Val);
1534       Set_Delta_Value    (Base, Delta_Val);
1535       Set_Small_Value    (Base, Delta_Val);
1536       Set_Scalar_Range   (Base,
1537         Make_Range (Loc,
1538           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1539           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1540
1541       Set_Is_Generic_Type (Base);
1542       Set_Parent          (Base, Parent (Def));
1543
1544       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
1545       Set_Etype          (T, Base);
1546       Set_Size_Info      (T, Int_Base);
1547       Set_RM_Size        (T, RM_Size (Int_Base));
1548       Set_First_Rep_Item (T, First_Rep_Item (Int_Base));
1549       Set_Digits_Value   (T, Digs_Val);
1550       Set_Delta_Value    (T, Delta_Val);
1551       Set_Small_Value    (T, Delta_Val);
1552       Set_Scalar_Range   (T, Scalar_Range (Base));
1553       Set_Is_Constrained (T);
1554
1555       Check_Restriction (No_Fixed_Point, Def);
1556    end Analyze_Formal_Decimal_Fixed_Point_Type;
1557
1558    -------------------------------------------
1559    -- Analyze_Formal_Derived_Interface_Type --
1560    -------------------------------------------
1561
1562    procedure Analyze_Formal_Derived_Interface_Type
1563      (N   : Node_Id;
1564       T   : Entity_Id;
1565       Def : Node_Id)
1566    is
1567       Loc   : constant Source_Ptr := Sloc (Def);
1568       New_N : Node_Id;
1569
1570    begin
1571       --  Rewrite as a type declaration of a derived type. This ensures that
1572       --  the interface list and primitive operations are properly captured.
1573
1574       New_N :=
1575         Make_Full_Type_Declaration (Loc,
1576           Defining_Identifier => T,
1577            Type_Definition => Def);
1578
1579       Rewrite (N, New_N);
1580       Analyze (N);
1581       Set_Is_Generic_Type (T);
1582    end Analyze_Formal_Derived_Interface_Type;
1583
1584    ---------------------------------
1585    -- Analyze_Formal_Derived_Type --
1586    ---------------------------------
1587
1588    procedure Analyze_Formal_Derived_Type
1589      (N   : Node_Id;
1590       T   : Entity_Id;
1591       Def : Node_Id)
1592    is
1593       Loc      : constant Source_Ptr := Sloc (Def);
1594       Unk_Disc : constant Boolean    := Unknown_Discriminants_Present (N);
1595       New_N    : Node_Id;
1596
1597    begin
1598       Set_Is_Generic_Type (T);
1599
1600       if Private_Present (Def) then
1601          New_N :=
1602            Make_Private_Extension_Declaration (Loc,
1603              Defining_Identifier           => T,
1604              Discriminant_Specifications   => Discriminant_Specifications (N),
1605              Unknown_Discriminants_Present => Unk_Disc,
1606              Subtype_Indication            => Subtype_Mark (Def),
1607              Interface_List                => Interface_List (Def));
1608
1609          Set_Abstract_Present     (New_N, Abstract_Present     (Def));
1610          Set_Limited_Present      (New_N, Limited_Present      (Def));
1611          Set_Synchronized_Present (New_N, Synchronized_Present (Def));
1612
1613       else
1614          New_N :=
1615            Make_Full_Type_Declaration (Loc,
1616              Defining_Identifier => T,
1617              Discriminant_Specifications =>
1618                Discriminant_Specifications (Parent (T)),
1619               Type_Definition =>
1620                 Make_Derived_Type_Definition (Loc,
1621                   Subtype_Indication => Subtype_Mark (Def)));
1622
1623          Set_Abstract_Present
1624            (Type_Definition (New_N), Abstract_Present (Def));
1625          Set_Limited_Present
1626            (Type_Definition (New_N), Limited_Present  (Def));
1627       end if;
1628
1629       Rewrite (N, New_N);
1630       Analyze (N);
1631
1632       if Unk_Disc then
1633          if not Is_Composite_Type (T) then
1634             Error_Msg_N
1635               ("unknown discriminants not allowed for elementary types", N);
1636          else
1637             Set_Has_Unknown_Discriminants (T);
1638             Set_Is_Constrained (T, False);
1639          end if;
1640       end if;
1641
1642       --  If the parent type has a known size, so does the formal, which makes
1643       --  legal representation clauses that involve the formal.
1644
1645       Set_Size_Known_At_Compile_Time
1646         (T, Size_Known_At_Compile_Time (Entity (Subtype_Mark (Def))));
1647
1648    end Analyze_Formal_Derived_Type;
1649
1650    ----------------------------------
1651    -- Analyze_Formal_Discrete_Type --
1652    ----------------------------------
1653
1654    --  The operations defined for a discrete types are those of an enumeration
1655    --  type. The size is set to an arbitrary value, for use in analyzing the
1656    --  generic unit.
1657
1658    procedure Analyze_Formal_Discrete_Type (T : Entity_Id; Def : Node_Id) is
1659       Loc : constant Source_Ptr := Sloc (Def);
1660       Lo  : Node_Id;
1661       Hi  : Node_Id;
1662
1663       Base : constant Entity_Id :=
1664                New_Internal_Entity
1665                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1666    begin
1667       Enter_Name          (T);
1668       Set_Ekind           (T, E_Enumeration_Subtype);
1669       Set_Etype           (T, Base);
1670       Init_Size           (T, 8);
1671       Init_Alignment      (T);
1672       Set_Is_Generic_Type (T);
1673       Set_Is_Constrained  (T);
1674
1675       --  For semantic analysis, the bounds of the type must be set to some
1676       --  non-static value. The simplest is to create attribute nodes for those
1677       --  bounds, that refer to the type itself. These bounds are never
1678       --  analyzed but serve as place-holders.
1679
1680       Lo :=
1681         Make_Attribute_Reference (Loc,
1682           Attribute_Name => Name_First,
1683           Prefix => New_Reference_To (T, Loc));
1684       Set_Etype (Lo, T);
1685
1686       Hi :=
1687         Make_Attribute_Reference (Loc,
1688           Attribute_Name => Name_Last,
1689           Prefix => New_Reference_To (T, Loc));
1690       Set_Etype (Hi, T);
1691
1692       Set_Scalar_Range (T,
1693         Make_Range (Loc,
1694           Low_Bound => Lo,
1695           High_Bound => Hi));
1696
1697       Set_Ekind           (Base, E_Enumeration_Type);
1698       Set_Etype           (Base, Base);
1699       Init_Size           (Base, 8);
1700       Init_Alignment      (Base);
1701       Set_Is_Generic_Type (Base);
1702       Set_Scalar_Range    (Base, Scalar_Range (T));
1703       Set_Parent          (Base, Parent (Def));
1704    end Analyze_Formal_Discrete_Type;
1705
1706    ----------------------------------
1707    -- Analyze_Formal_Floating_Type --
1708    ---------------------------------
1709
1710    procedure Analyze_Formal_Floating_Type (T : Entity_Id; Def : Node_Id) is
1711       Base : constant Entity_Id :=
1712                New_Internal_Entity
1713                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1714
1715    begin
1716       --  The various semantic attributes are taken from the predefined type
1717       --  Float, just so that all of them are initialized. Their values are
1718       --  never used because no constant folding or expansion takes place in
1719       --  the generic itself.
1720
1721       Enter_Name (T);
1722       Set_Ekind          (T, E_Floating_Point_Subtype);
1723       Set_Etype          (T, Base);
1724       Set_Size_Info      (T,              (Standard_Float));
1725       Set_RM_Size        (T, RM_Size      (Standard_Float));
1726       Set_Digits_Value   (T, Digits_Value (Standard_Float));
1727       Set_Scalar_Range   (T, Scalar_Range (Standard_Float));
1728       Set_Is_Constrained (T);
1729
1730       Set_Is_Generic_Type (Base);
1731       Set_Etype           (Base, Base);
1732       Set_Size_Info       (Base,              (Standard_Float));
1733       Set_RM_Size         (Base, RM_Size      (Standard_Float));
1734       Set_Digits_Value    (Base, Digits_Value (Standard_Float));
1735       Set_Scalar_Range    (Base, Scalar_Range (Standard_Float));
1736       Set_Parent          (Base, Parent (Def));
1737
1738       Check_Restriction (No_Floating_Point, Def);
1739    end Analyze_Formal_Floating_Type;
1740
1741    -----------------------------------
1742    -- Analyze_Formal_Interface_Type;--
1743    -----------------------------------
1744
1745    procedure Analyze_Formal_Interface_Type
1746       (N   : Node_Id;
1747        T   : Entity_Id;
1748        Def : Node_Id)
1749    is
1750       Loc   : constant Source_Ptr := Sloc (N);
1751       New_N : Node_Id;
1752
1753    begin
1754       New_N :=
1755         Make_Full_Type_Declaration (Loc,
1756           Defining_Identifier => T,
1757           Type_Definition => Def);
1758
1759       Rewrite (N, New_N);
1760       Analyze (N);
1761       Set_Is_Generic_Type (T);
1762    end Analyze_Formal_Interface_Type;
1763
1764    ---------------------------------
1765    -- Analyze_Formal_Modular_Type --
1766    ---------------------------------
1767
1768    procedure Analyze_Formal_Modular_Type (T : Entity_Id; Def : Node_Id) is
1769    begin
1770       --  Apart from their entity kind, generic modular types are treated like
1771       --  signed integer types, and have the same attributes.
1772
1773       Analyze_Formal_Signed_Integer_Type (T, Def);
1774       Set_Ekind (T, E_Modular_Integer_Subtype);
1775       Set_Ekind (Etype (T), E_Modular_Integer_Type);
1776
1777    end Analyze_Formal_Modular_Type;
1778
1779    ---------------------------------------
1780    -- Analyze_Formal_Object_Declaration --
1781    ---------------------------------------
1782
1783    procedure Analyze_Formal_Object_Declaration (N : Node_Id) is
1784       E  : constant Node_Id := Default_Expression (N);
1785       Id : constant Node_Id := Defining_Identifier (N);
1786       K  : Entity_Kind;
1787       T  : Node_Id;
1788
1789    begin
1790       Enter_Name (Id);
1791
1792       --  Determine the mode of the formal object
1793
1794       if Out_Present (N) then
1795          K := E_Generic_In_Out_Parameter;
1796
1797          if not In_Present (N) then
1798             Error_Msg_N ("formal generic objects cannot have mode OUT", N);
1799          end if;
1800
1801       else
1802          K := E_Generic_In_Parameter;
1803       end if;
1804
1805       if Present (Subtype_Mark (N)) then
1806          Find_Type (Subtype_Mark (N));
1807          T := Entity (Subtype_Mark (N));
1808
1809       --  Ada 2005 (AI-423): Formal object with an access definition
1810
1811       else
1812          Check_Access_Definition (N);
1813          T := Access_Definition
1814                 (Related_Nod => N,
1815                  N           => Access_Definition (N));
1816       end if;
1817
1818       if Ekind (T) = E_Incomplete_Type then
1819          declare
1820             Error_Node : Node_Id;
1821
1822          begin
1823             if Present (Subtype_Mark (N)) then
1824                Error_Node := Subtype_Mark (N);
1825             else
1826                Check_Access_Definition (N);
1827                Error_Node := Access_Definition (N);
1828             end if;
1829
1830             Error_Msg_N ("premature usage of incomplete type", Error_Node);
1831          end;
1832       end if;
1833
1834       if K = E_Generic_In_Parameter then
1835
1836          --  Ada 2005 (AI-287): Limited aggregates allowed in generic formals
1837
1838          if Ada_Version < Ada_05 and then Is_Limited_Type (T) then
1839             Error_Msg_N
1840               ("generic formal of mode IN must not be of limited type", N);
1841             Explain_Limited_Type (T, N);
1842          end if;
1843
1844          if Is_Abstract_Type (T) then
1845             Error_Msg_N
1846               ("generic formal of mode IN must not be of abstract type", N);
1847          end if;
1848
1849          if Present (E) then
1850             Analyze_Per_Use_Expression (E, T);
1851
1852             if Is_Limited_Type (T) and then not OK_For_Limited_Init (E) then
1853                Error_Msg_N
1854                  ("initialization not allowed for limited types", E);
1855                Explain_Limited_Type (T, E);
1856             end if;
1857          end if;
1858
1859          Set_Ekind (Id, K);
1860          Set_Etype (Id, T);
1861
1862       --  Case of generic IN OUT parameter
1863
1864       else
1865          --  If the formal has an unconstrained type, construct its actual
1866          --  subtype, as is done for subprogram formals. In this fashion, all
1867          --  its uses can refer to specific bounds.
1868
1869          Set_Ekind (Id, K);
1870          Set_Etype (Id, T);
1871
1872          if (Is_Array_Type (T)
1873               and then not Is_Constrained (T))
1874            or else
1875             (Ekind (T) = E_Record_Type
1876               and then Has_Discriminants (T))
1877          then
1878             declare
1879                Non_Freezing_Ref : constant Node_Id :=
1880                                     New_Reference_To (Id, Sloc (Id));
1881                Decl : Node_Id;
1882
1883             begin
1884                --  Make sure the actual subtype doesn't generate bogus freezing
1885
1886                Set_Must_Not_Freeze (Non_Freezing_Ref);
1887                Decl := Build_Actual_Subtype (T, Non_Freezing_Ref);
1888                Insert_Before_And_Analyze (N, Decl);
1889                Set_Actual_Subtype (Id, Defining_Identifier (Decl));
1890             end;
1891          else
1892             Set_Actual_Subtype (Id, T);
1893          end if;
1894
1895          if Present (E) then
1896             Error_Msg_N
1897               ("initialization not allowed for `IN OUT` formals", N);
1898          end if;
1899       end if;
1900
1901    end Analyze_Formal_Object_Declaration;
1902
1903    ----------------------------------------------
1904    -- Analyze_Formal_Ordinary_Fixed_Point_Type --
1905    ----------------------------------------------
1906
1907    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
1908      (T   : Entity_Id;
1909       Def : Node_Id)
1910    is
1911       Loc  : constant Source_Ptr := Sloc (Def);
1912       Base : constant Entity_Id :=
1913                New_Internal_Entity
1914                  (E_Ordinary_Fixed_Point_Type, Current_Scope, Sloc (Def), 'G');
1915    begin
1916       --  The semantic attributes are set for completeness only, their values
1917       --  will never be used, since all properties of the type are non-static.
1918
1919       Enter_Name (T);
1920       Set_Ekind            (T, E_Ordinary_Fixed_Point_Subtype);
1921       Set_Etype            (T, Base);
1922       Set_Size_Info        (T, Standard_Integer);
1923       Set_RM_Size          (T, RM_Size (Standard_Integer));
1924       Set_Small_Value      (T, Ureal_1);
1925       Set_Delta_Value      (T, Ureal_1);
1926       Set_Scalar_Range     (T,
1927         Make_Range (Loc,
1928           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1929           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1930       Set_Is_Constrained   (T);
1931
1932       Set_Is_Generic_Type (Base);
1933       Set_Etype           (Base, Base);
1934       Set_Size_Info       (Base, Standard_Integer);
1935       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1936       Set_Small_Value     (Base, Ureal_1);
1937       Set_Delta_Value     (Base, Ureal_1);
1938       Set_Scalar_Range    (Base, Scalar_Range (T));
1939       Set_Parent          (Base, Parent (Def));
1940
1941       Check_Restriction (No_Fixed_Point, Def);
1942    end Analyze_Formal_Ordinary_Fixed_Point_Type;
1943
1944    ----------------------------
1945    -- Analyze_Formal_Package --
1946    ----------------------------
1947
1948    procedure Analyze_Formal_Package (N : Node_Id) is
1949       Loc              : constant Source_Ptr := Sloc (N);
1950       Pack_Id          : constant Entity_Id := Defining_Identifier (N);
1951       Formal           : Entity_Id;
1952       Gen_Id           : constant Node_Id    := Name (N);
1953       Gen_Decl         : Node_Id;
1954       Gen_Unit         : Entity_Id;
1955       New_N            : Node_Id;
1956       Parent_Installed : Boolean := False;
1957       Renaming         : Node_Id;
1958       Parent_Instance  : Entity_Id;
1959       Renaming_In_Par  : Entity_Id;
1960       No_Associations  : Boolean := False;
1961
1962       function Build_Local_Package return Node_Id;
1963       --  The formal package is rewritten so that its parameters are replaced
1964       --  with corresponding declarations. For parameters with bona fide
1965       --  associations these declarations are created by Analyze_Associations
1966       --  as for aa regular instantiation. For boxed parameters, we preserve
1967       --  the formal declarations and analyze them, in order to introduce
1968       --  entities of the right kind in the environment of the formal.
1969
1970       -------------------------
1971       -- Build_Local_Package --
1972       -------------------------
1973
1974       function Build_Local_Package return Node_Id is
1975          Decls     : List_Id;
1976          Pack_Decl : Node_Id;
1977
1978       begin
1979          --  Within the formal, the name of the generic package is a renaming
1980          --  of the formal (as for a regular instantiation).
1981
1982          Pack_Decl :=
1983            Make_Package_Declaration (Loc,
1984              Specification =>
1985                Copy_Generic_Node
1986                  (Specification (Original_Node (Gen_Decl)),
1987                     Empty, Instantiating => True));
1988
1989          Renaming := Make_Package_Renaming_Declaration (Loc,
1990              Defining_Unit_Name =>
1991                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
1992              Name => New_Occurrence_Of (Formal, Loc));
1993
1994          if Nkind (Gen_Id) = N_Identifier
1995            and then Chars (Gen_Id) = Chars (Pack_Id)
1996          then
1997             Error_Msg_NE
1998               ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
1999          end if;
2000
2001          --  If the formal is declared with a box, or with an others choice,
2002          --  create corresponding declarations for all entities in the formal
2003          --  part, so that names with the proper types are available in the
2004          --  specification of the formal package.
2005
2006          if No_Associations then
2007             declare
2008                Formal_Decl : Node_Id;
2009
2010             begin
2011                --  TBA : for a formal package, need to recurse ???
2012
2013                Decls := New_List;
2014                Formal_Decl :=
2015                  First
2016                    (Generic_Formal_Declarations (Original_Node (Gen_Decl)));
2017                while Present (Formal_Decl) loop
2018                   Append_To
2019                     (Decls, Copy_Generic_Node (Formal_Decl, Empty, True));
2020                   Next (Formal_Decl);
2021                end loop;
2022             end;
2023
2024          --  If generic associations are present, use Analyze_Associations to
2025          --  create the proper renaming declarations.
2026
2027          else
2028             declare
2029                Act_Tree : constant Node_Id :=
2030                             Copy_Generic_Node
2031                               (Original_Node (Gen_Decl), Empty,
2032                                Instantiating => True);
2033
2034             begin
2035                Generic_Renamings.Set_Last (0);
2036                Generic_Renamings_HTable.Reset;
2037                Instantiation_Node := N;
2038
2039                Decls :=
2040                  Analyze_Associations
2041                    (Original_Node (N),
2042                       Generic_Formal_Declarations (Act_Tree),
2043                       Generic_Formal_Declarations (Gen_Decl));
2044             end;
2045          end if;
2046
2047          Append (Renaming, To => Decls);
2048
2049          --  Add generated declarations ahead of local declarations in
2050          --  the package.
2051
2052          if No (Visible_Declarations (Specification (Pack_Decl))) then
2053             Set_Visible_Declarations (Specification (Pack_Decl), Decls);
2054          else
2055             Insert_List_Before
2056               (First (Visible_Declarations (Specification (Pack_Decl))),
2057                  Decls);
2058          end if;
2059
2060          return Pack_Decl;
2061       end Build_Local_Package;
2062
2063    --  Start of processing for Analyze_Formal_Package
2064
2065    begin
2066       Text_IO_Kludge (Gen_Id);
2067
2068       Init_Env;
2069       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
2070       Gen_Unit := Entity (Gen_Id);
2071
2072       --  Check for a formal package that is a package renaming
2073
2074       if Present (Renamed_Object (Gen_Unit)) then
2075          Gen_Unit := Renamed_Object (Gen_Unit);
2076       end if;
2077
2078       if Ekind (Gen_Unit) /= E_Generic_Package then
2079          Error_Msg_N ("expect generic package name", Gen_Id);
2080          Restore_Env;
2081          return;
2082
2083       elsif  Gen_Unit = Current_Scope then
2084          Error_Msg_N
2085            ("generic package cannot be used as a formal package of itself",
2086              Gen_Id);
2087          Restore_Env;
2088          return;
2089
2090       elsif In_Open_Scopes (Gen_Unit) then
2091          if Is_Compilation_Unit (Gen_Unit)
2092            and then Is_Child_Unit (Current_Scope)
2093          then
2094             --  Special-case the error when the formal is a parent, and
2095             --  continue analysis to minimize cascaded errors.
2096
2097             Error_Msg_N
2098               ("generic parent cannot be used as formal package "
2099                 & "of a child unit",
2100                 Gen_Id);
2101
2102          else
2103             Error_Msg_N
2104               ("generic package cannot be used as a formal package "
2105                 & "within itself",
2106                 Gen_Id);
2107             Restore_Env;
2108             return;
2109          end if;
2110       end if;
2111
2112       if Box_Present (N)
2113         or else No (Generic_Associations (N))
2114         or else Nkind (First (Generic_Associations (N))) = N_Others_Choice
2115       then
2116          No_Associations := True;
2117       end if;
2118
2119       --  If there are no generic associations, the generic parameters appear
2120       --  as local entities and are instantiated like them. We copy the generic
2121       --  package declaration as if it were an instantiation, and analyze it
2122       --  like a regular package, except that we treat the formals as
2123       --  additional visible components.
2124
2125       Gen_Decl := Unit_Declaration_Node (Gen_Unit);
2126
2127       if In_Extended_Main_Source_Unit (N) then
2128          Set_Is_Instantiated (Gen_Unit);
2129          Generate_Reference  (Gen_Unit, N);
2130       end if;
2131
2132       Formal := New_Copy (Pack_Id);
2133       Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
2134
2135       --  Make local generic without formals. The formals will be replaced with
2136       --  internal declarations.
2137
2138       New_N := Build_Local_Package;
2139       Rewrite (N, New_N);
2140       Set_Defining_Unit_Name (Specification (New_N), Formal);
2141       Set_Generic_Parent (Specification (N), Gen_Unit);
2142       Set_Instance_Env (Gen_Unit, Formal);
2143       Set_Is_Generic_Instance (Formal);
2144
2145       Enter_Name (Formal);
2146       Set_Ekind  (Formal, E_Package);
2147       Set_Etype  (Formal, Standard_Void_Type);
2148       Set_Inner_Instances (Formal, New_Elmt_List);
2149       Push_Scope  (Formal);
2150
2151       if Is_Child_Unit (Gen_Unit)
2152         and then Parent_Installed
2153       then
2154          --  Similarly, we have to make the name of the formal visible in the
2155          --  parent instance, to resolve properly fully qualified names that
2156          --  may appear in the generic unit. The parent instance has been
2157          --  placed on the scope stack ahead of the current scope.
2158
2159          Parent_Instance := Scope_Stack.Table (Scope_Stack.Last - 1).Entity;
2160
2161          Renaming_In_Par :=
2162            Make_Defining_Identifier (Loc, Chars (Gen_Unit));
2163          Set_Ekind (Renaming_In_Par, E_Package);
2164          Set_Etype (Renaming_In_Par, Standard_Void_Type);
2165          Set_Scope (Renaming_In_Par, Parent_Instance);
2166          Set_Parent (Renaming_In_Par, Parent (Formal));
2167          Set_Renamed_Object (Renaming_In_Par, Formal);
2168          Append_Entity (Renaming_In_Par, Parent_Instance);
2169       end if;
2170
2171       Analyze (Specification (N));
2172
2173       --  The formals for which associations are provided are not visible
2174       --  outside of the formal package. The others are still declared by a
2175       --  formal parameter declaration.
2176
2177       if not No_Associations then
2178          declare
2179             E : Entity_Id;
2180
2181          begin
2182             E := First_Entity (Formal);
2183             while Present (E) loop
2184                exit when Ekind (E) = E_Package
2185                  and then Renamed_Entity (E) = Formal;
2186
2187                if not Is_Generic_Formal (E) then
2188                   Set_Is_Hidden (E);
2189                end if;
2190
2191                Next_Entity (E);
2192             end loop;
2193          end;
2194       end if;
2195
2196       End_Package_Scope (Formal);
2197
2198       if Parent_Installed then
2199          Remove_Parent;
2200       end if;
2201
2202       Restore_Env;
2203
2204       --  Inside the generic unit, the formal package is a regular package, but
2205       --  no body is needed for it. Note that after instantiation, the defining
2206       --  unit name we need is in the new tree and not in the original (see
2207       --  Package_Instantiation). A generic formal package is an instance, and
2208       --  can be used as an actual for an inner instance.
2209
2210       Set_Has_Completion (Formal, True);
2211
2212       --  Add semantic information to the original defining identifier.
2213       --  for ASIS use.
2214
2215       Set_Ekind (Pack_Id, E_Package);
2216       Set_Etype (Pack_Id, Standard_Void_Type);
2217       Set_Scope (Pack_Id, Scope (Formal));
2218       Set_Has_Completion (Pack_Id, True);
2219
2220       --  If there are errors in the parameter list, Analyze_Associations
2221       --  raises Instantiation_Error. Patch the declaration to prevent
2222       --  further exception propagation.
2223
2224       exception
2225          when Instantiation_Error =>
2226
2227             Enter_Name (Formal);
2228             Set_Ekind  (Formal, E_Variable);
2229             Set_Etype  (Formal, Any_Type);
2230
2231             if Parent_Installed then
2232                Remove_Parent;
2233             end if;
2234    end Analyze_Formal_Package;
2235
2236    ---------------------------------
2237    -- Analyze_Formal_Private_Type --
2238    ---------------------------------
2239
2240    procedure Analyze_Formal_Private_Type
2241      (N   : Node_Id;
2242       T   : Entity_Id;
2243       Def : Node_Id)
2244    is
2245    begin
2246       New_Private_Type (N, T, Def);
2247
2248       --  Set the size to an arbitrary but legal value
2249
2250       Set_Size_Info (T, Standard_Integer);
2251       Set_RM_Size   (T, RM_Size (Standard_Integer));
2252    end Analyze_Formal_Private_Type;
2253
2254    ----------------------------------------
2255    -- Analyze_Formal_Signed_Integer_Type --
2256    ----------------------------------------
2257
2258    procedure Analyze_Formal_Signed_Integer_Type
2259      (T   : Entity_Id;
2260       Def : Node_Id)
2261    is
2262       Base : constant Entity_Id :=
2263                New_Internal_Entity
2264                  (E_Signed_Integer_Type, Current_Scope, Sloc (Def), 'G');
2265
2266    begin
2267       Enter_Name (T);
2268
2269       Set_Ekind          (T, E_Signed_Integer_Subtype);
2270       Set_Etype          (T, Base);
2271       Set_Size_Info      (T, Standard_Integer);
2272       Set_RM_Size        (T, RM_Size (Standard_Integer));
2273       Set_Scalar_Range   (T, Scalar_Range (Standard_Integer));
2274       Set_Is_Constrained (T);
2275
2276       Set_Is_Generic_Type (Base);
2277       Set_Size_Info       (Base, Standard_Integer);
2278       Set_RM_Size         (Base, RM_Size (Standard_Integer));
2279       Set_Etype           (Base, Base);
2280       Set_Scalar_Range    (Base, Scalar_Range (Standard_Integer));
2281       Set_Parent          (Base, Parent (Def));
2282    end Analyze_Formal_Signed_Integer_Type;
2283
2284    -------------------------------
2285    -- Analyze_Formal_Subprogram --
2286    -------------------------------
2287
2288    procedure Analyze_Formal_Subprogram (N : Node_Id) is
2289       Spec : constant Node_Id   := Specification (N);
2290       Def  : constant Node_Id   := Default_Name (N);
2291       Nam  : constant Entity_Id := Defining_Unit_Name (Spec);
2292       Subp : Entity_Id;
2293
2294    begin
2295       if Nam = Error then
2296          return;
2297       end if;
2298
2299       if Nkind (Nam) = N_Defining_Program_Unit_Name then
2300          Error_Msg_N ("name of formal subprogram must be a direct name", Nam);
2301          return;
2302       end if;
2303
2304       Analyze_Subprogram_Declaration (N);
2305       Set_Is_Formal_Subprogram (Nam);
2306       Set_Has_Completion (Nam);
2307
2308       if Nkind (N) = N_Formal_Abstract_Subprogram_Declaration then
2309          Set_Is_Abstract_Subprogram (Nam);
2310          Set_Is_Dispatching_Operation (Nam);
2311
2312          declare
2313             Ctrl_Type : constant Entity_Id := Find_Dispatching_Type (Nam);
2314          begin
2315             if No (Ctrl_Type) then
2316                Error_Msg_N
2317                  ("abstract formal subprogram must have a controlling type",
2318                   N);
2319             else
2320                Check_Controlling_Formals (Ctrl_Type, Nam);
2321             end if;
2322          end;
2323       end if;
2324
2325       --  Default name is resolved at the point of instantiation
2326
2327       if Box_Present (N) then
2328          null;
2329
2330       --  Else default is bound at the point of generic declaration
2331
2332       elsif Present (Def) then
2333          if Nkind (Def) = N_Operator_Symbol then
2334             Find_Direct_Name (Def);
2335
2336          elsif Nkind (Def) /= N_Attribute_Reference then
2337             Analyze (Def);
2338
2339          else
2340             --  For an attribute reference, analyze the prefix and verify
2341             --  that it has the proper profile for the subprogram.
2342
2343             Analyze (Prefix (Def));
2344             Valid_Default_Attribute (Nam, Def);
2345             return;
2346          end if;
2347
2348          --  Default name may be overloaded, in which case the interpretation
2349          --  with the correct profile must be  selected, as for a renaming.
2350
2351          if Etype (Def) = Any_Type then
2352             return;
2353
2354          elsif Nkind (Def) = N_Selected_Component then
2355             Subp := Entity (Selector_Name (Def));
2356
2357             if Ekind (Subp) /= E_Entry then
2358                Error_Msg_N ("expect valid subprogram name as default", Def);
2359                return;
2360             end if;
2361
2362          elsif Nkind (Def) = N_Indexed_Component then
2363
2364             if  Nkind (Prefix (Def)) /= N_Selected_Component then
2365                Error_Msg_N ("expect valid subprogram name as default", Def);
2366                return;
2367
2368             else
2369                Subp := Entity (Selector_Name (Prefix (Def)));
2370
2371                if Ekind (Subp) /= E_Entry_Family then
2372                   Error_Msg_N ("expect valid subprogram name as default", Def);
2373                   return;
2374                end if;
2375             end if;
2376
2377          elsif Nkind (Def) = N_Character_Literal then
2378
2379             --  Needs some type checks: subprogram should be parameterless???
2380
2381             Resolve (Def, (Etype (Nam)));
2382
2383          elsif not Is_Entity_Name (Def)
2384            or else not Is_Overloadable (Entity (Def))
2385          then
2386             Error_Msg_N ("expect valid subprogram name as default", Def);
2387             return;
2388
2389          elsif not Is_Overloaded (Def) then
2390             Subp := Entity (Def);
2391
2392             if Subp = Nam then
2393                Error_Msg_N ("premature usage of formal subprogram", Def);
2394
2395             elsif not Entity_Matches_Spec (Subp, Nam) then
2396                Error_Msg_N ("no visible entity matches specification", Def);
2397             end if;
2398
2399          else
2400             declare
2401                I   : Interp_Index;
2402                I1  : Interp_Index := 0;
2403                It  : Interp;
2404                It1 : Interp;
2405
2406             begin
2407                Subp := Any_Id;
2408                Get_First_Interp (Def, I, It);
2409                while Present (It.Nam) loop
2410
2411                   if Entity_Matches_Spec (It.Nam, Nam) then
2412                      if Subp /= Any_Id then
2413                         It1 := Disambiguate (Def, I1, I, Etype (Subp));
2414
2415                         if It1 = No_Interp then
2416                            Error_Msg_N ("ambiguous default subprogram", Def);
2417                         else
2418                            Subp := It1.Nam;
2419                         end if;
2420
2421                         exit;
2422
2423                      else
2424                         I1  := I;
2425                         Subp := It.Nam;
2426                      end if;
2427                   end if;
2428
2429                   Get_Next_Interp (I, It);
2430                end loop;
2431             end;
2432
2433             if Subp /= Any_Id then
2434                Set_Entity (Def, Subp);
2435
2436                if Subp = Nam then
2437                   Error_Msg_N ("premature usage of formal subprogram", Def);
2438
2439                elsif Ekind (Subp) /= E_Operator then
2440                   Check_Mode_Conformant (Subp, Nam);
2441                end if;
2442
2443             else
2444                Error_Msg_N ("no visible subprogram matches specification", N);
2445             end if;
2446          end if;
2447       end if;
2448    end Analyze_Formal_Subprogram;
2449
2450    -------------------------------------
2451    -- Analyze_Formal_Type_Declaration --
2452    -------------------------------------
2453
2454    procedure Analyze_Formal_Type_Declaration (N : Node_Id) is
2455       Def : constant Node_Id := Formal_Type_Definition (N);
2456       T   : Entity_Id;
2457
2458    begin
2459       T := Defining_Identifier (N);
2460
2461       if Present (Discriminant_Specifications (N))
2462         and then Nkind (Def) /= N_Formal_Private_Type_Definition
2463       then
2464          Error_Msg_N
2465            ("discriminants not allowed for this formal type",
2466             Defining_Identifier (First (Discriminant_Specifications (N))));
2467       end if;
2468
2469       --  Enter the new name, and branch to specific routine
2470
2471       case Nkind (Def) is
2472          when N_Formal_Private_Type_Definition         =>
2473             Analyze_Formal_Private_Type (N, T, Def);
2474
2475          when N_Formal_Derived_Type_Definition         =>
2476             Analyze_Formal_Derived_Type (N, T, Def);
2477
2478          when N_Formal_Discrete_Type_Definition        =>
2479             Analyze_Formal_Discrete_Type (T, Def);
2480
2481          when N_Formal_Signed_Integer_Type_Definition  =>
2482             Analyze_Formal_Signed_Integer_Type (T, Def);
2483
2484          when N_Formal_Modular_Type_Definition         =>
2485             Analyze_Formal_Modular_Type (T, Def);
2486
2487          when N_Formal_Floating_Point_Definition       =>
2488             Analyze_Formal_Floating_Type (T, Def);
2489
2490          when N_Formal_Ordinary_Fixed_Point_Definition =>
2491             Analyze_Formal_Ordinary_Fixed_Point_Type (T, Def);
2492
2493          when N_Formal_Decimal_Fixed_Point_Definition  =>
2494             Analyze_Formal_Decimal_Fixed_Point_Type (T, Def);
2495
2496          when N_Array_Type_Definition =>
2497             Analyze_Formal_Array_Type (T, Def);
2498
2499          when N_Access_To_Object_Definition            |
2500               N_Access_Function_Definition             |
2501               N_Access_Procedure_Definition            =>
2502             Analyze_Generic_Access_Type (T, Def);
2503
2504          --  Ada 2005: a interface declaration is encoded as an abstract
2505          --  record declaration or a abstract type derivation.
2506
2507          when N_Record_Definition                      =>
2508             Analyze_Formal_Interface_Type (N, T, Def);
2509
2510          when N_Derived_Type_Definition                =>
2511             Analyze_Formal_Derived_Interface_Type (N, T, Def);
2512
2513          when N_Error                                  =>
2514             null;
2515
2516          when others                                   =>
2517             raise Program_Error;
2518
2519       end case;
2520
2521       Set_Is_Generic_Type (T);
2522    end Analyze_Formal_Type_Declaration;
2523
2524    ------------------------------------
2525    -- Analyze_Function_Instantiation --
2526    ------------------------------------
2527
2528    procedure Analyze_Function_Instantiation (N : Node_Id) is
2529    begin
2530       Analyze_Subprogram_Instantiation (N, E_Function);
2531    end Analyze_Function_Instantiation;
2532
2533    ---------------------------------
2534    -- Analyze_Generic_Access_Type --
2535    ---------------------------------
2536
2537    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id) is
2538    begin
2539       Enter_Name (T);
2540
2541       if Nkind (Def) = N_Access_To_Object_Definition then
2542          Access_Type_Declaration (T, Def);
2543
2544          if Is_Incomplete_Or_Private_Type (Designated_Type (T))
2545            and then No (Full_View (Designated_Type (T)))
2546            and then not Is_Generic_Type (Designated_Type (T))
2547          then
2548             Error_Msg_N ("premature usage of incomplete type", Def);
2549
2550          elsif Is_Internal (Designated_Type (T)) then
2551             Error_Msg_N
2552               ("only a subtype mark is allowed in a formal", Def);
2553          end if;
2554
2555       else
2556          Access_Subprogram_Declaration (T, Def);
2557       end if;
2558    end Analyze_Generic_Access_Type;
2559
2560    ---------------------------------
2561    -- Analyze_Generic_Formal_Part --
2562    ---------------------------------
2563
2564    procedure Analyze_Generic_Formal_Part (N : Node_Id) is
2565       Gen_Parm_Decl : Node_Id;
2566
2567    begin
2568       --  The generic formals are processed in the scope of the generic unit,
2569       --  where they are immediately visible. The scope is installed by the
2570       --  caller.
2571
2572       Gen_Parm_Decl := First (Generic_Formal_Declarations (N));
2573
2574       while Present (Gen_Parm_Decl) loop
2575          Analyze (Gen_Parm_Decl);
2576          Next (Gen_Parm_Decl);
2577       end loop;
2578
2579       Generate_Reference_To_Generic_Formals (Current_Scope);
2580    end Analyze_Generic_Formal_Part;
2581
2582    ------------------------------------------
2583    -- Analyze_Generic_Package_Declaration  --
2584    ------------------------------------------
2585
2586    procedure Analyze_Generic_Package_Declaration (N : Node_Id) is
2587       Loc         : constant Source_Ptr := Sloc (N);
2588       Id          : Entity_Id;
2589       New_N       : Node_Id;
2590       Save_Parent : Node_Id;
2591       Renaming    : Node_Id;
2592       Decls       : constant List_Id :=
2593                       Visible_Declarations (Specification (N));
2594       Decl        : Node_Id;
2595
2596    begin
2597       --  We introduce a renaming of the enclosing package, to have a usable
2598       --  entity as the prefix of an expanded name for a local entity of the
2599       --  form Par.P.Q, where P is the generic package. This is because a local
2600       --  entity named P may hide it, so that the usual visibility rules in
2601       --  the instance will not resolve properly.
2602
2603       Renaming :=
2604         Make_Package_Renaming_Declaration (Loc,
2605           Defining_Unit_Name =>
2606             Make_Defining_Identifier (Loc,
2607              Chars => New_External_Name (Chars (Defining_Entity (N)), "GH")),
2608           Name => Make_Identifier (Loc, Chars (Defining_Entity (N))));
2609
2610       if Present (Decls) then
2611          Decl := First (Decls);
2612          while Present (Decl)
2613            and then Nkind (Decl) = N_Pragma
2614          loop
2615             Next (Decl);
2616          end loop;
2617
2618          if Present (Decl) then
2619             Insert_Before (Decl, Renaming);
2620          else
2621             Append (Renaming, Visible_Declarations (Specification (N)));
2622          end if;
2623
2624       else
2625          Set_Visible_Declarations (Specification (N), New_List (Renaming));
2626       end if;
2627
2628       --  Create copy of generic unit, and save for instantiation. If the unit
2629       --  is a child unit, do not copy the specifications for the parent, which
2630       --  are not part of the generic tree.
2631
2632       Save_Parent := Parent_Spec (N);
2633       Set_Parent_Spec (N, Empty);
2634
2635       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2636       Set_Parent_Spec (New_N, Save_Parent);
2637       Rewrite (N, New_N);
2638       Id := Defining_Entity (N);
2639       Generate_Definition (Id);
2640
2641       --  Expansion is not applied to generic units
2642
2643       Start_Generic;
2644
2645       Enter_Name (Id);
2646       Set_Ekind (Id, E_Generic_Package);
2647       Set_Etype (Id, Standard_Void_Type);
2648       Push_Scope (Id);
2649       Enter_Generic_Scope (Id);
2650       Set_Inner_Instances (Id, New_Elmt_List);
2651
2652       Set_Categorization_From_Pragmas (N);
2653       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2654
2655       --  Link the declaration of the generic homonym in the generic copy to
2656       --  the package it renames, so that it is always resolved properly.
2657
2658       Set_Generic_Homonym (Id, Defining_Unit_Name (Renaming));
2659       Set_Entity (Associated_Node (Name (Renaming)), Id);
2660
2661       --  For a library unit, we have reconstructed the entity for the unit,
2662       --  and must reset it in the library tables.
2663
2664       if Nkind (Parent (N)) = N_Compilation_Unit then
2665          Set_Cunit_Entity (Current_Sem_Unit, Id);
2666       end if;
2667
2668       Analyze_Generic_Formal_Part (N);
2669
2670       --  After processing the generic formals, analysis proceeds as for a
2671       --  non-generic package.
2672
2673       Analyze (Specification (N));
2674
2675       Validate_Categorization_Dependency (N, Id);
2676
2677       End_Generic;
2678
2679       End_Package_Scope (Id);
2680       Exit_Generic_Scope (Id);
2681
2682       if Nkind (Parent (N)) /= N_Compilation_Unit then
2683          Move_Freeze_Nodes (Id, N, Visible_Declarations (Specification (N)));
2684          Move_Freeze_Nodes (Id, N, Private_Declarations (Specification (N)));
2685          Move_Freeze_Nodes (Id, N, Generic_Formal_Declarations (N));
2686
2687       else
2688          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2689          Validate_RT_RAT_Component (N);
2690
2691          --  If this is a spec without a body, check that generic parameters
2692          --  are referenced.
2693
2694          if not Body_Required (Parent (N)) then
2695             Check_References (Id);
2696          end if;
2697       end if;
2698    end Analyze_Generic_Package_Declaration;
2699
2700    --------------------------------------------
2701    -- Analyze_Generic_Subprogram_Declaration --
2702    --------------------------------------------
2703
2704    procedure Analyze_Generic_Subprogram_Declaration (N : Node_Id) is
2705       Spec        : Node_Id;
2706       Id          : Entity_Id;
2707       Formals     : List_Id;
2708       New_N       : Node_Id;
2709       Result_Type : Entity_Id;
2710       Save_Parent : Node_Id;
2711
2712    begin
2713       --  Create copy of generic unit,and save for instantiation. If the unit
2714       --  is a child unit, do not copy the specifications for the parent, which
2715       --  are not part of the generic tree.
2716
2717       Save_Parent := Parent_Spec (N);
2718       Set_Parent_Spec (N, Empty);
2719
2720       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2721       Set_Parent_Spec (New_N, Save_Parent);
2722       Rewrite (N, New_N);
2723
2724       Spec := Specification (N);
2725       Id := Defining_Entity (Spec);
2726       Generate_Definition (Id);
2727
2728       if Nkind (Id) = N_Defining_Operator_Symbol then
2729          Error_Msg_N
2730            ("operator symbol not allowed for generic subprogram", Id);
2731       end if;
2732
2733       Start_Generic;
2734
2735       Enter_Name (Id);
2736
2737       Set_Scope_Depth_Value (Id, Scope_Depth (Current_Scope) + 1);
2738       Push_Scope (Id);
2739       Enter_Generic_Scope (Id);
2740       Set_Inner_Instances (Id, New_Elmt_List);
2741       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2742
2743       Analyze_Generic_Formal_Part (N);
2744
2745       Formals := Parameter_Specifications (Spec);
2746
2747       if Present (Formals) then
2748          Process_Formals (Formals, Spec);
2749       end if;
2750
2751       if Nkind (Spec) = N_Function_Specification then
2752          Set_Ekind (Id, E_Generic_Function);
2753
2754          if Nkind (Result_Definition (Spec)) = N_Access_Definition then
2755             Result_Type := Access_Definition (Spec, Result_Definition (Spec));
2756             Set_Etype (Id, Result_Type);
2757          else
2758             Find_Type (Result_Definition (Spec));
2759             Set_Etype (Id, Entity (Result_Definition (Spec)));
2760          end if;
2761
2762       else
2763          Set_Ekind (Id, E_Generic_Procedure);
2764          Set_Etype (Id, Standard_Void_Type);
2765       end if;
2766
2767       --  For a library unit, we have reconstructed the entity for the unit,
2768       --  and must reset it in the library tables. We also make sure that
2769       --  Body_Required is set properly in the original compilation unit node.
2770
2771       if Nkind (Parent (N)) = N_Compilation_Unit then
2772          Set_Cunit_Entity (Current_Sem_Unit, Id);
2773          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2774       end if;
2775
2776       Set_Categorization_From_Pragmas (N);
2777       Validate_Categorization_Dependency (N, Id);
2778
2779       Save_Global_References (Original_Node (N));
2780
2781       End_Generic;
2782       End_Scope;
2783       Exit_Generic_Scope (Id);
2784       Generate_Reference_To_Formals (Id);
2785    end Analyze_Generic_Subprogram_Declaration;
2786
2787    -----------------------------------
2788    -- Analyze_Package_Instantiation --
2789    -----------------------------------
2790
2791    procedure Analyze_Package_Instantiation (N : Node_Id) is
2792       Loc    : constant Source_Ptr := Sloc (N);
2793       Gen_Id : constant Node_Id    := Name (N);
2794
2795       Act_Decl      : Node_Id;
2796       Act_Decl_Name : Node_Id;
2797       Act_Decl_Id   : Entity_Id;
2798       Act_Spec      : Node_Id;
2799       Act_Tree      : Node_Id;
2800
2801       Gen_Decl : Node_Id;
2802       Gen_Unit : Entity_Id;
2803
2804       Is_Actual_Pack : constant Boolean :=
2805                          Is_Internal (Defining_Entity (N));
2806
2807       Env_Installed    : Boolean := False;
2808       Parent_Installed : Boolean := False;
2809       Renaming_List    : List_Id;
2810       Unit_Renaming    : Node_Id;
2811       Needs_Body       : Boolean;
2812       Inline_Now       : Boolean := False;
2813
2814       procedure Delay_Descriptors (E : Entity_Id);
2815       --  Delay generation of subprogram descriptors for given entity
2816
2817       function Might_Inline_Subp return Boolean;
2818       --  If inlining is active and the generic contains inlined subprograms,
2819       --  we instantiate the body. This may cause superfluous instantiations,
2820       --  but it is simpler than detecting the need for the body at the point
2821       --  of inlining, when the context of the instance is not available.
2822
2823       -----------------------
2824       -- Delay_Descriptors --
2825       -----------------------
2826
2827       procedure Delay_Descriptors (E : Entity_Id) is
2828       begin
2829          if not Delay_Subprogram_Descriptors (E) then
2830             Set_Delay_Subprogram_Descriptors (E);
2831             Pending_Descriptor.Increment_Last;
2832             Pending_Descriptor.Table (Pending_Descriptor.Last) := E;
2833          end if;
2834       end Delay_Descriptors;
2835
2836       -----------------------
2837       -- Might_Inline_Subp --
2838       -----------------------
2839
2840       function Might_Inline_Subp return Boolean is
2841          E : Entity_Id;
2842
2843       begin
2844          if not Inline_Processing_Required then
2845             return False;
2846
2847          else
2848             E := First_Entity (Gen_Unit);
2849             while Present (E) loop
2850                if Is_Subprogram (E)
2851                  and then Is_Inlined (E)
2852                then
2853                   return True;
2854                end if;
2855
2856                Next_Entity (E);
2857             end loop;
2858          end if;
2859
2860          return False;
2861       end Might_Inline_Subp;
2862
2863    --  Start of processing for Analyze_Package_Instantiation
2864
2865    begin
2866       --  Very first thing: apply the special kludge for Text_IO processing
2867       --  in case we are instantiating one of the children of [Wide_]Text_IO.
2868
2869       Text_IO_Kludge (Name (N));
2870
2871       --  Make node global for error reporting
2872
2873       Instantiation_Node := N;
2874
2875       --  Case of instantiation of a generic package
2876
2877       if Nkind (N) = N_Package_Instantiation then
2878          Act_Decl_Id := New_Copy (Defining_Entity (N));
2879          Set_Comes_From_Source (Act_Decl_Id, True);
2880
2881          if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name then
2882             Act_Decl_Name :=
2883               Make_Defining_Program_Unit_Name (Loc,
2884                 Name => New_Copy_Tree (Name (Defining_Unit_Name (N))),
2885                 Defining_Identifier => Act_Decl_Id);
2886          else
2887             Act_Decl_Name :=  Act_Decl_Id;
2888          end if;
2889
2890       --  Case of instantiation of a formal package
2891
2892       else
2893          Act_Decl_Id   := Defining_Identifier (N);
2894          Act_Decl_Name := Act_Decl_Id;
2895       end if;
2896
2897       Generate_Definition (Act_Decl_Id);
2898       Pre_Analyze_Actuals (N);
2899
2900       Init_Env;
2901       Env_Installed := True;
2902       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
2903       Gen_Unit := Entity (Gen_Id);
2904
2905       --  Verify that it is the name of a generic package
2906
2907       if Etype (Gen_Unit) = Any_Type then
2908          Restore_Env;
2909          return;
2910
2911       elsif Ekind (Gen_Unit) /= E_Generic_Package then
2912
2913          --  Ada 2005 (AI-50217): Cannot use instance in limited with_clause
2914
2915          if From_With_Type (Gen_Unit) then
2916             Error_Msg_N
2917               ("cannot instantiate a limited withed package", Gen_Id);
2918          else
2919             Error_Msg_N
2920               ("expect name of generic package in instantiation", Gen_Id);
2921          end if;
2922
2923          Restore_Env;
2924          return;
2925       end if;
2926
2927       if In_Extended_Main_Source_Unit (N) then
2928          Set_Is_Instantiated (Gen_Unit);
2929          Generate_Reference  (Gen_Unit, N);
2930
2931          if Present (Renamed_Object (Gen_Unit)) then
2932             Set_Is_Instantiated (Renamed_Object (Gen_Unit));
2933             Generate_Reference  (Renamed_Object (Gen_Unit), N);
2934          end if;
2935       end if;
2936
2937       if Nkind (Gen_Id) = N_Identifier
2938         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
2939       then
2940          Error_Msg_NE
2941            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
2942
2943       elsif Nkind (Gen_Id) = N_Expanded_Name
2944         and then Is_Child_Unit (Gen_Unit)
2945         and then Nkind (Prefix (Gen_Id)) = N_Identifier
2946         and then Chars (Act_Decl_Id) = Chars (Prefix (Gen_Id))
2947       then
2948          Error_Msg_N
2949            ("& is hidden within declaration of instance ", Prefix (Gen_Id));
2950       end if;
2951
2952       Set_Entity (Gen_Id, Gen_Unit);
2953
2954       --  If generic is a renaming, get original generic unit
2955
2956       if Present (Renamed_Object (Gen_Unit))
2957         and then Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Package
2958       then
2959          Gen_Unit := Renamed_Object (Gen_Unit);
2960       end if;
2961
2962       --  Verify that there are no circular instantiations
2963
2964       if In_Open_Scopes (Gen_Unit) then
2965          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
2966          Restore_Env;
2967          return;
2968
2969       elsif Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
2970          Error_Msg_Node_2 := Current_Scope;
2971          Error_Msg_NE
2972            ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
2973          Circularity_Detected := True;
2974          Restore_Env;
2975          return;
2976
2977       else
2978          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
2979
2980          --  Initialize renamings map, for error checking, and the list that
2981          --  holds private entities whose views have changed between generic
2982          --  definition and instantiation. If this is the instance created to
2983          --  validate an actual package, the instantiation environment is that
2984          --  of the enclosing instance.
2985
2986          Generic_Renamings.Set_Last (0);
2987          Generic_Renamings_HTable.Reset;
2988
2989          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
2990
2991          --  Copy original generic tree, to produce text for instantiation
2992
2993          Act_Tree :=
2994            Copy_Generic_Node
2995              (Original_Node (Gen_Decl), Empty, Instantiating => True);
2996
2997          Act_Spec := Specification (Act_Tree);
2998
2999          --  If this is the instance created to validate an actual package,
3000          --  only the formals matter, do not examine the package spec itself.
3001
3002          if Is_Actual_Pack then
3003             Set_Visible_Declarations (Act_Spec, New_List);
3004             Set_Private_Declarations (Act_Spec, New_List);
3005          end if;
3006
3007          Renaming_List :=
3008            Analyze_Associations
3009              (N,
3010               Generic_Formal_Declarations (Act_Tree),
3011               Generic_Formal_Declarations (Gen_Decl));
3012
3013          Set_Instance_Env (Gen_Unit, Act_Decl_Id);
3014          Set_Defining_Unit_Name (Act_Spec, Act_Decl_Name);
3015          Set_Is_Generic_Instance (Act_Decl_Id);
3016
3017          Set_Generic_Parent (Act_Spec, Gen_Unit);
3018
3019          --  References to the generic in its own declaration or its body are
3020          --  references to the instance. Add a renaming declaration for the
3021          --  generic unit itself. This declaration, as well as the renaming
3022          --  declarations for the generic formals, must remain private to the
3023          --  unit: the formals, because this is the language semantics, and
3024          --  the unit because its use is an artifact of the implementation.
3025
3026          Unit_Renaming :=
3027            Make_Package_Renaming_Declaration (Loc,
3028              Defining_Unit_Name =>
3029                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
3030              Name => New_Reference_To (Act_Decl_Id, Loc));
3031
3032          Append (Unit_Renaming, Renaming_List);
3033
3034          --  The renaming declarations are the first local declarations of
3035          --  the new unit.
3036
3037          if Is_Non_Empty_List (Visible_Declarations (Act_Spec)) then
3038             Insert_List_Before
3039               (First (Visible_Declarations (Act_Spec)), Renaming_List);
3040          else
3041             Set_Visible_Declarations (Act_Spec, Renaming_List);
3042          end if;
3043
3044          Act_Decl :=
3045            Make_Package_Declaration (Loc,
3046              Specification => Act_Spec);
3047
3048          --  Save the instantiation node, for subsequent instantiation of the
3049          --  body, if there is one and we are generating code for the current
3050          --  unit. Mark the unit as having a body, to avoid a premature error
3051          --  message.
3052
3053          --  We instantiate the body if we are generating code, if we are
3054          --  generating cross-reference information, or if we are building
3055          --  trees for ASIS use.
3056
3057          declare
3058             Enclosing_Body_Present : Boolean := False;
3059             --  If the generic unit is not a compilation unit, then a body may
3060             --  be present in its parent even if none is required. We create a
3061             --  tentative pending instantiation for the body, which will be
3062             --  discarded if none is actually present.
3063
3064             Scop : Entity_Id;
3065
3066          begin
3067             if Scope (Gen_Unit) /= Standard_Standard
3068               and then not Is_Child_Unit (Gen_Unit)
3069             then
3070                Scop := Scope (Gen_Unit);
3071
3072                while Present (Scop)
3073                  and then Scop /= Standard_Standard
3074                loop
3075                   if Unit_Requires_Body (Scop) then
3076                      Enclosing_Body_Present := True;
3077                      exit;
3078
3079                   elsif In_Open_Scopes (Scop)
3080                     and then In_Package_Body (Scop)
3081                   then
3082                      Enclosing_Body_Present := True;
3083                      exit;
3084                   end if;
3085
3086                   exit when Is_Compilation_Unit (Scop);
3087                   Scop := Scope (Scop);
3088                end loop;
3089             end if;
3090
3091             --  If front-end inlining is enabled, and this is a unit for which
3092             --  code will be generated, we instantiate the body at once.
3093
3094             --  This is done if the instance is not the main unit, and if the
3095             --  generic is not a child unit of another generic, to avoid scope
3096             --  problems and the reinstallation of parent instances.
3097
3098             if Expander_Active
3099               and then (not Is_Child_Unit (Gen_Unit)
3100                          or else not Is_Generic_Unit (Scope (Gen_Unit)))
3101               and then Might_Inline_Subp
3102               and then not Is_Actual_Pack
3103             then
3104                if Front_End_Inlining
3105                  and then (Is_In_Main_Unit (N)
3106                             or else In_Main_Context (Current_Scope))
3107                  and then Nkind (Parent (N)) /= N_Compilation_Unit
3108                then
3109                   Inline_Now := True;
3110
3111                --  In configurable_run_time mode we force the inlining of
3112                --  predefined subprogram marked Inline_Always, to minimize
3113                --  the use of the run-time library.
3114
3115                elsif Is_Predefined_File_Name
3116                        (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
3117                  and then Configurable_Run_Time_Mode
3118                  and then Nkind (Parent (N)) /= N_Compilation_Unit
3119                then
3120                   Inline_Now := True;
3121                end if;
3122
3123                --  If the current scope is itself an instance within a child
3124                --  unit,there will be duplications in the scope stack, and the
3125                --  unstacking mechanism in Inline_Instance_Body will fail.
3126                --  This loses some rare cases of optimization, and might be
3127                --  improved some day, if we can find a proper abstraction for
3128                --  "the complete compilation context" that can be saved and
3129                --  restored ???
3130
3131                if Is_Generic_Instance (Current_Scope) then
3132                   declare
3133                      Curr_Unit : constant Entity_Id :=
3134                                    Cunit_Entity (Current_Sem_Unit);
3135                   begin
3136                      if Curr_Unit /= Current_Scope
3137                        and then Is_Child_Unit (Curr_Unit)
3138                      then
3139                         Inline_Now := False;
3140                      end if;
3141                   end;
3142                end if;
3143             end if;
3144
3145             Needs_Body :=
3146               (Unit_Requires_Body (Gen_Unit)
3147                   or else Enclosing_Body_Present
3148                   or else Present (Corresponding_Body (Gen_Decl)))
3149                 and then (Is_In_Main_Unit (N)
3150                            or else Might_Inline_Subp)
3151                 and then not Is_Actual_Pack
3152                 and then not Inline_Now
3153                 and then (Operating_Mode = Generate_Code
3154                             or else (Operating_Mode = Check_Semantics
3155                                       and then ASIS_Mode));
3156
3157             --  If front_end_inlining is enabled, do not instantiate body if
3158             --  within a generic context.
3159
3160             if (Front_End_Inlining
3161                   and then not Expander_Active)
3162               or else Is_Generic_Unit (Cunit_Entity (Main_Unit))
3163             then
3164                Needs_Body := False;
3165             end if;
3166
3167             --  If the current context is generic, and the package being
3168             --  instantiated is declared within a formal package, there is no
3169             --  body to instantiate until the enclosing generic is instantiated
3170             --  and there is an actual for the formal package. If the formal
3171             --  package has parameters, we build regular package instance for
3172             --  it, that preceeds the original formal package declaration.
3173
3174             if In_Open_Scopes (Scope (Scope (Gen_Unit))) then
3175                declare
3176                   Decl : constant Node_Id :=
3177                            Original_Node
3178                              (Unit_Declaration_Node (Scope (Gen_Unit)));
3179                begin
3180                   if Nkind (Decl) = N_Formal_Package_Declaration
3181                     or else (Nkind (Decl) = N_Package_Declaration
3182                       and then Is_List_Member (Decl)
3183                       and then Present (Next (Decl))
3184                       and then
3185                         Nkind (Next (Decl)) = N_Formal_Package_Declaration)
3186                   then
3187                      Needs_Body := False;
3188                   end if;
3189                end;
3190             end if;
3191          end;
3192
3193          --  If we are generating the calling stubs from the instantiation of
3194          --  a generic RCI package, we will not use the body of the generic
3195          --  package.
3196
3197          if Distribution_Stub_Mode = Generate_Caller_Stub_Body
3198            and then Is_Compilation_Unit (Defining_Entity (N))
3199          then
3200             Needs_Body := False;
3201          end if;
3202
3203          if Needs_Body then
3204
3205             --  Here is a defence against a ludicrous number of instantiations
3206             --  caused by a circular set of instantiation attempts.
3207
3208             if Pending_Instantiations.Last >
3209                  Hostparm.Max_Instantiations
3210             then
3211                Error_Msg_N ("too many instantiations", N);
3212                raise Unrecoverable_Error;
3213             end if;
3214
3215             --  Indicate that the enclosing scopes contain an instantiation,
3216             --  and that cleanup actions should be delayed until after the
3217             --  instance body is expanded.
3218
3219             Check_Forward_Instantiation (Gen_Decl);
3220             if Nkind (N) = N_Package_Instantiation then
3221                declare
3222                   Enclosing_Master : Entity_Id;
3223
3224                begin
3225                   --  Loop to search enclosing masters
3226
3227                   Enclosing_Master := Current_Scope;
3228                   Scope_Loop : while Enclosing_Master /= Standard_Standard loop
3229                      if Ekind (Enclosing_Master) = E_Package then
3230                         if Is_Compilation_Unit (Enclosing_Master) then
3231                            if In_Package_Body (Enclosing_Master) then
3232                               Delay_Descriptors
3233                                 (Body_Entity (Enclosing_Master));
3234                            else
3235                               Delay_Descriptors
3236                                 (Enclosing_Master);
3237                            end if;
3238
3239                            exit Scope_Loop;
3240
3241                         else
3242                            Enclosing_Master := Scope (Enclosing_Master);
3243                         end if;
3244
3245                      elsif Ekind (Enclosing_Master) = E_Generic_Package then
3246                         Enclosing_Master := Scope (Enclosing_Master);
3247
3248                      elsif Is_Generic_Subprogram (Enclosing_Master)
3249                        or else Ekind (Enclosing_Master) = E_Void
3250                      then
3251                         --  Cleanup actions will eventually be performed on
3252                         --  the enclosing instance, if any. enclosing scope
3253                         --  is void in the formal part of a generic subp.
3254
3255                         exit Scope_Loop;
3256
3257                      else
3258                         if Ekind (Enclosing_Master) = E_Entry
3259                           and then
3260                             Ekind (Scope (Enclosing_Master)) = E_Protected_Type
3261                         then
3262                            if not Expander_Active then
3263                               exit Scope_Loop;
3264                            else
3265                               Enclosing_Master :=
3266                                 Protected_Body_Subprogram (Enclosing_Master);
3267                            end if;
3268                         end if;
3269
3270                         Set_Delay_Cleanups (Enclosing_Master);
3271
3272                         while Ekind (Enclosing_Master) = E_Block loop
3273                            Enclosing_Master := Scope (Enclosing_Master);
3274                         end loop;
3275
3276                         if Is_Subprogram (Enclosing_Master) then
3277                            Delay_Descriptors (Enclosing_Master);
3278
3279                         elsif Is_Task_Type (Enclosing_Master) then
3280                            declare
3281                               TBP : constant Node_Id :=
3282                                       Get_Task_Body_Procedure
3283                                         (Enclosing_Master);
3284                            begin
3285                               if Present (TBP) then
3286                                  Delay_Descriptors  (TBP);
3287                                  Set_Delay_Cleanups (TBP);
3288                               end if;
3289                            end;
3290                         end if;
3291
3292                         exit Scope_Loop;
3293                      end if;
3294                   end loop Scope_Loop;
3295                end;
3296
3297                --  Make entry in table
3298
3299                Pending_Instantiations.Increment_Last;
3300                Pending_Instantiations.Table (Pending_Instantiations.Last) :=
3301                  (N, Act_Decl, Expander_Active, Current_Sem_Unit);
3302             end if;
3303          end if;
3304
3305          Set_Categorization_From_Pragmas (Act_Decl);
3306
3307          if Parent_Installed then
3308             Hide_Current_Scope;
3309          end if;
3310
3311          Set_Instance_Spec (N, Act_Decl);
3312
3313          --  If not a compilation unit, insert the package declaration
3314          --  before the original instantiation node.
3315
3316          if Nkind (Parent (N)) /= N_Compilation_Unit then
3317             Mark_Rewrite_Insertion (Act_Decl);
3318             Insert_Before (N, Act_Decl);
3319             Analyze (Act_Decl);
3320
3321          --  For an instantiation that is a compilation unit, place declaration
3322          --  on current node so context is complete for analysis (including
3323          --  nested instantiations). It this is the main unit, the declaration
3324          --  eventually replaces the instantiation node. If the instance body
3325          --  is later created, it replaces the instance node, and the declation
3326          --  is attached to it (see Build_Instance_Compilation_Unit_Nodes).
3327
3328          else
3329             if Cunit_Entity (Current_Sem_Unit) = Defining_Entity (N) then
3330
3331                --  The entity for the current unit is the newly created one,
3332                --  and all semantic information is attached to it.
3333
3334                Set_Cunit_Entity (Current_Sem_Unit, Act_Decl_Id);
3335
3336                --  If this is the main unit, replace the main entity as well
3337
3338                if Current_Sem_Unit = Main_Unit then
3339                   Main_Unit_Entity := Act_Decl_Id;
3340                end if;
3341             end if;
3342
3343             Set_Unit (Parent (N), Act_Decl);
3344             Set_Parent_Spec (Act_Decl, Parent_Spec (N));
3345             Set_Package_Instantiation (Act_Decl_Id, N);
3346             Analyze (Act_Decl);
3347             Set_Unit (Parent (N), N);
3348             Set_Body_Required (Parent (N), False);
3349
3350             --  We never need elaboration checks on instantiations, since by
3351             --  definition, the body instantiation is elaborated at the same
3352             --  time as the spec instantiation.
3353
3354             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
3355             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
3356          end if;
3357
3358          Check_Elab_Instantiation (N);
3359
3360          if ABE_Is_Certain (N) and then Needs_Body then
3361             Pending_Instantiations.Decrement_Last;
3362          end if;
3363          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
3364
3365          Set_First_Private_Entity (Defining_Unit_Name (Unit_Renaming),
3366            First_Private_Entity (Act_Decl_Id));
3367
3368          --  If the instantiation will receive a body, the unit will be
3369          --  transformed into a package body, and receive its own elaboration
3370          --  entity. Otherwise, the nature of the unit is now a package
3371          --  declaration.
3372
3373          if Nkind (Parent (N)) = N_Compilation_Unit
3374            and then not Needs_Body
3375          then
3376             Rewrite (N, Act_Decl);
3377          end if;
3378
3379          if Present (Corresponding_Body (Gen_Decl))
3380            or else Unit_Requires_Body (Gen_Unit)
3381          then
3382             Set_Has_Completion (Act_Decl_Id);
3383          end if;
3384
3385          Check_Formal_Packages (Act_Decl_Id);
3386
3387          Restore_Private_Views (Act_Decl_Id);
3388
3389          if not Generic_Separately_Compiled (Gen_Unit) then
3390             Inherit_Context (Gen_Decl, N);
3391          end if;
3392
3393          if Parent_Installed then
3394             Remove_Parent;
3395          end if;
3396
3397          Restore_Env;
3398          Env_Installed := False;
3399       end if;
3400
3401       Validate_Categorization_Dependency (N, Act_Decl_Id);
3402
3403       --  Check restriction, but skip this if something went wrong in the above
3404       --  analysis, indicated by Act_Decl_Id being void.
3405
3406       if Ekind (Act_Decl_Id) /= E_Void
3407         and then not Is_Library_Level_Entity (Act_Decl_Id)
3408       then
3409          Check_Restriction (No_Local_Allocators, N);
3410       end if;
3411
3412       if Inline_Now then
3413          Inline_Instance_Body (N, Gen_Unit, Act_Decl);
3414       end if;
3415
3416       --  The following is a tree patch for ASIS: ASIS needs separate nodes to
3417       --  be used as defining identifiers for a formal package and for the
3418       --  corresponding expanded package
3419
3420       if Nkind (N) = N_Formal_Package_Declaration then
3421          Act_Decl_Id := New_Copy (Defining_Entity (N));
3422          Set_Comes_From_Source (Act_Decl_Id, True);
3423          Set_Is_Generic_Instance (Act_Decl_Id, False);
3424          Set_Defining_Identifier (N, Act_Decl_Id);
3425       end if;
3426
3427    exception
3428       when Instantiation_Error =>
3429          if Parent_Installed then
3430             Remove_Parent;
3431          end if;
3432
3433          if Env_Installed then
3434             Restore_Env;
3435          end if;
3436    end Analyze_Package_Instantiation;
3437
3438    --------------------------
3439    -- Inline_Instance_Body --
3440    --------------------------
3441
3442    procedure Inline_Instance_Body
3443      (N        : Node_Id;
3444       Gen_Unit : Entity_Id;
3445       Act_Decl : Node_Id)
3446    is
3447       Vis          : Boolean;
3448       Gen_Comp     : constant Entity_Id :=
3449                       Cunit_Entity (Get_Source_Unit (Gen_Unit));
3450       Curr_Comp    : constant Node_Id := Cunit (Current_Sem_Unit);
3451       Curr_Scope   : Entity_Id := Empty;
3452       Curr_Unit    : constant Entity_Id :=
3453                        Cunit_Entity (Current_Sem_Unit);
3454       Removed      : Boolean := False;
3455       Num_Scopes   : Int := 0;
3456
3457       Scope_Stack_Depth : constant Int :=
3458                             Scope_Stack.Last - Scope_Stack.First + 1;
3459
3460       Use_Clauses  : array (1 .. Scope_Stack_Depth) of Node_Id;
3461       Instances    : array (1 .. Scope_Stack_Depth) of Entity_Id;
3462       Inner_Scopes : array (1 .. Scope_Stack_Depth) of Entity_Id;
3463       Num_Inner    : Int := 0;
3464       N_Instances  : Int := 0;
3465       S            : Entity_Id;
3466
3467    begin
3468       --  Case of generic unit defined in another unit. We must remove the
3469       --  complete context of the current unit to install that of the generic.
3470
3471       if Gen_Comp /= Cunit_Entity (Current_Sem_Unit) then
3472
3473          --  Add some comments for the following two loops ???
3474
3475          S := Current_Scope;
3476          while Present (S) and then S /= Standard_Standard loop
3477             loop
3478                Num_Scopes := Num_Scopes + 1;
3479
3480                Use_Clauses (Num_Scopes) :=
3481                  (Scope_Stack.Table
3482                     (Scope_Stack.Last - Num_Scopes + 1).
3483                        First_Use_Clause);
3484                End_Use_Clauses (Use_Clauses (Num_Scopes));
3485
3486                exit when Scope_Stack.Last - Num_Scopes + 1 = Scope_Stack.First
3487                  or else Scope_Stack.Table
3488                            (Scope_Stack.Last - Num_Scopes).Entity
3489                              = Scope (S);
3490             end loop;
3491
3492             exit when Is_Generic_Instance (S)
3493               and then (In_Package_Body (S)
3494                           or else Ekind (S) = E_Procedure
3495                           or else Ekind (S) = E_Function);
3496             S := Scope (S);
3497          end loop;
3498
3499          Vis := Is_Immediately_Visible (Gen_Comp);
3500
3501          --  Find and save all enclosing instances
3502
3503          S := Current_Scope;
3504
3505          while Present (S)
3506            and then S /= Standard_Standard
3507          loop
3508             if Is_Generic_Instance (S) then
3509                N_Instances := N_Instances + 1;
3510                Instances (N_Instances) := S;
3511
3512                exit when In_Package_Body (S);
3513             end if;
3514
3515             S := Scope (S);
3516          end loop;
3517
3518          --  Remove context of current compilation unit, unless we are within a
3519          --  nested package instantiation, in which case the context has been
3520          --  removed previously.
3521
3522          --  If current scope is the body of a child unit, remove context of
3523          --  spec as well. If an enclosing scope is an instance body. the
3524          --  context has already been removed, but the entities in the body
3525          --  must be made invisible as well.
3526
3527          S := Current_Scope;
3528
3529          while Present (S)
3530            and then S /= Standard_Standard
3531          loop
3532             if Is_Generic_Instance (S)
3533               and then (In_Package_Body (S)
3534                           or else Ekind (S) = E_Procedure
3535                             or else Ekind (S) = E_Function)
3536             then
3537                --  We still have to remove the entities of the enclosing
3538                --  instance from direct visibility.
3539
3540                declare
3541                   E : Entity_Id;
3542                begin
3543                   E := First_Entity (S);
3544                   while Present (E) loop
3545                      Set_Is_Immediately_Visible (E, False);
3546                      Next_Entity (E);
3547                   end loop;
3548                end;
3549
3550                exit;
3551             end if;
3552
3553             if S = Curr_Unit
3554               or else (Ekind (Curr_Unit) = E_Package_Body
3555                         and then S = Spec_Entity (Curr_Unit))
3556               or else (Ekind (Curr_Unit) = E_Subprogram_Body
3557                         and then S =
3558                           Corresponding_Spec
3559                             (Unit_Declaration_Node (Curr_Unit)))
3560             then
3561                Removed := True;
3562
3563                --  Remove entities in current scopes from visibility, so that
3564                --  instance body is compiled in a clean environment.
3565
3566                Save_Scope_Stack (Handle_Use => False);
3567
3568                if Is_Child_Unit (S) then
3569
3570                   --  Remove child unit from stack, as well as inner scopes.
3571                   --  Removing the context of a child unit removes parent units
3572                   --  as well.
3573
3574                   while Current_Scope /= S loop
3575                      Num_Inner := Num_Inner + 1;
3576                      Inner_Scopes (Num_Inner) := Current_Scope;
3577                      Pop_Scope;
3578                   end loop;
3579
3580                   Pop_Scope;
3581                   Remove_Context (Curr_Comp);
3582                   Curr_Scope := S;
3583
3584                else
3585                   Remove_Context (Curr_Comp);
3586                end if;
3587
3588                if Ekind (Curr_Unit) = E_Package_Body then
3589                   Remove_Context (Library_Unit (Curr_Comp));
3590                end if;
3591             end if;
3592
3593             S := Scope (S);
3594          end loop;
3595          pragma Assert (Num_Inner < Num_Scopes);
3596
3597          Push_Scope (Standard_Standard);
3598          Scope_Stack.Table (Scope_Stack.Last).Is_Active_Stack_Base := True;
3599          Instantiate_Package_Body
3600            ((N, Act_Decl, Expander_Active, Current_Sem_Unit), True);
3601          Pop_Scope;
3602
3603          --  Restore context
3604
3605          Set_Is_Immediately_Visible (Gen_Comp, Vis);
3606
3607          --  Reset Generic_Instance flag so that use clauses can be installed
3608          --  in the proper order. (See Use_One_Package for effect of enclosing
3609          --  instances on processing of use clauses).
3610
3611          for J in 1 .. N_Instances loop
3612             Set_Is_Generic_Instance (Instances (J), False);
3613          end loop;
3614
3615          if Removed then
3616             Install_Context (Curr_Comp);
3617
3618             if Present (Curr_Scope)
3619               and then Is_Child_Unit (Curr_Scope)
3620             then
3621                Push_Scope (Curr_Scope);
3622                Set_Is_Immediately_Visible (Curr_Scope);
3623
3624                --  Finally, restore inner scopes as well
3625
3626                for J in reverse 1 .. Num_Inner loop
3627                   Push_Scope (Inner_Scopes (J));
3628                end loop;
3629             end if;
3630
3631             Restore_Scope_Stack (Handle_Use => False);
3632
3633             if Present (Curr_Scope)
3634               and then
3635                 (In_Private_Part (Curr_Scope)
3636                   or else In_Package_Body (Curr_Scope))
3637             then
3638                --  Install private declaration of ancestor units, which are
3639                --  currently available. Restore_Scope_Stack and Install_Context
3640                --  only install the visible part of parents.
3641
3642                declare
3643                   Par : Entity_Id;
3644                begin
3645                   Par := Scope (Curr_Scope);
3646                   while (Present (Par))
3647                     and then Par /= Standard_Standard
3648                   loop
3649                      Install_Private_Declarations (Par);
3650                      Par := Scope (Par);
3651                   end loop;
3652                end;
3653             end if;
3654          end if;
3655
3656          --  Restore use clauses. For a child unit, use clauses in the parents
3657          --  are restored when installing the context, so only those in inner
3658          --  scopes (and those local to the child unit itself) need to be
3659          --  installed explicitly.
3660
3661          if Is_Child_Unit (Curr_Unit)
3662            and then Removed
3663          then
3664             for J in reverse 1 .. Num_Inner + 1 loop
3665                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3666                  Use_Clauses (J);
3667                Install_Use_Clauses (Use_Clauses (J));
3668             end  loop;
3669
3670          else
3671             for J in reverse 1 .. Num_Scopes loop
3672                Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
3673                  Use_Clauses (J);
3674                Install_Use_Clauses (Use_Clauses (J));
3675             end  loop;
3676          end if;
3677
3678          --  Restore status of instances. If one of them is a body, make
3679          --  its local entities visible again.
3680
3681          declare
3682             E    : Entity_Id;
3683             Inst : Entity_Id;
3684
3685          begin
3686             for J in 1 .. N_Instances loop
3687                Inst := Instances (J);
3688                Set_Is_Generic_Instance (Inst, True);
3689
3690                if In_Package_Body (Inst)
3691                  or else Ekind (S) = E_Procedure
3692                  or else Ekind (S) = E_Function
3693                then
3694                   E := First_Entity (Instances (J));
3695                   while Present (E) loop
3696                      Set_Is_Immediately_Visible (E);
3697                      Next_Entity (E);
3698                   end loop;
3699                end if;
3700             end loop;
3701          end;
3702
3703       --  If generic unit is in current unit, current context is correct
3704
3705       else
3706          Instantiate_Package_Body
3707            ((N, Act_Decl, Expander_Active, Current_Sem_Unit), True);
3708       end if;
3709    end Inline_Instance_Body;
3710
3711    -------------------------------------
3712    -- Analyze_Procedure_Instantiation --
3713    -------------------------------------
3714
3715    procedure Analyze_Procedure_Instantiation (N : Node_Id) is
3716    begin
3717       Analyze_Subprogram_Instantiation (N, E_Procedure);
3718    end Analyze_Procedure_Instantiation;
3719
3720    --------------------------------------
3721    -- Analyze_Subprogram_Instantiation --
3722    --------------------------------------
3723
3724    procedure Analyze_Subprogram_Instantiation
3725      (N : Node_Id;
3726       K : Entity_Kind)
3727    is
3728       Loc    : constant Source_Ptr := Sloc (N);
3729       Gen_Id : constant Node_Id    := Name (N);
3730
3731       Anon_Id : constant Entity_Id :=
3732                   Make_Defining_Identifier (Sloc (Defining_Entity (N)),
3733                     Chars => New_External_Name
3734                                (Chars (Defining_Entity (N)), 'R'));
3735
3736       Act_Decl_Id : Entity_Id;
3737       Act_Decl    : Node_Id;
3738       Act_Spec    : Node_Id;
3739       Act_Tree    : Node_Id;
3740
3741       Env_Installed    : Boolean := False;
3742       Gen_Unit         : Entity_Id;
3743       Gen_Decl         : Node_Id;
3744       Pack_Id          : Entity_Id;
3745       Parent_Installed : Boolean := False;
3746       Renaming_List    : List_Id;
3747
3748       procedure Analyze_Instance_And_Renamings;
3749       --  The instance must be analyzed in a context that includes the mappings
3750       --  of generic parameters into actuals. We create a package declaration
3751       --  for this purpose, and a subprogram with an internal name within the
3752       --  package. The subprogram instance is simply an alias for the internal
3753       --  subprogram, declared in the current scope.
3754
3755       ------------------------------------
3756       -- Analyze_Instance_And_Renamings --
3757       ------------------------------------
3758
3759       procedure Analyze_Instance_And_Renamings is
3760          Def_Ent   : constant Entity_Id := Defining_Entity (N);
3761          Pack_Decl : Node_Id;
3762
3763       begin
3764          if Nkind (Parent (N)) = N_Compilation_Unit then
3765
3766             --  For the case of a compilation unit, the container package has
3767             --  the same name as the instantiation, to insure that the binder
3768             --  calls the elaboration procedure with the right name. Copy the
3769             --  entity of the instance, which may have compilation level flags
3770             --  (e.g. Is_Child_Unit) set.
3771
3772             Pack_Id := New_Copy (Def_Ent);
3773
3774          else
3775             --  Otherwise we use the name of the instantiation concatenated
3776             --  with its source position to ensure uniqueness if there are
3777             --  several instantiations with the same name.
3778
3779             Pack_Id :=
3780               Make_Defining_Identifier (Loc,
3781                 Chars => New_External_Name
3782                            (Related_Id   => Chars (Def_Ent),
3783                             Suffix       => "GP",
3784                             Suffix_Index => Source_Offset (Sloc (Def_Ent))));
3785          end if;
3786
3787          Pack_Decl := Make_Package_Declaration (Loc,
3788            Specification => Make_Package_Specification (Loc,
3789              Defining_Unit_Name   => Pack_Id,
3790              Visible_Declarations => Renaming_List,
3791              End_Label            => Empty));
3792
3793          Set_Instance_Spec (N, Pack_Decl);
3794          Set_Is_Generic_Instance (Pack_Id);
3795          Set_Needs_Debug_Info (Pack_Id);
3796
3797          --  Case of not a compilation unit
3798
3799          if Nkind (Parent (N)) /= N_Compilation_Unit then
3800             Mark_Rewrite_Insertion (Pack_Decl);
3801             Insert_Before (N, Pack_Decl);
3802             Set_Has_Completion (Pack_Id);
3803
3804          --  Case of an instantiation that is a compilation unit
3805
3806          --  Place declaration on current node so context is complete for
3807          --  analysis (including nested instantiations), and for use in a
3808          --  context_clause (see Analyze_With_Clause).
3809
3810          else
3811             Set_Unit (Parent (N), Pack_Decl);
3812             Set_Parent_Spec (Pack_Decl, Parent_Spec (N));
3813          end if;
3814
3815          Analyze (Pack_Decl);
3816          Check_Formal_Packages (Pack_Id);
3817          Set_Is_Generic_Instance (Pack_Id, False);
3818
3819          --  Body of the enclosing package is supplied when instantiating the
3820          --  subprogram body, after semantic analysis is completed.
3821
3822          if Nkind (Parent (N)) = N_Compilation_Unit then
3823
3824             --  Remove package itself from visibility, so it does not
3825             --  conflict with subprogram.
3826
3827             Set_Name_Entity_Id (Chars (Pack_Id), Homonym (Pack_Id));
3828
3829             --  Set name and scope of internal subprogram so that the proper
3830             --  external name will be generated. The proper scope is the scope
3831             --  of the wrapper package. We need to generate debugging info for
3832             --  the internal subprogram, so set flag accordingly.
3833
3834             Set_Chars (Anon_Id, Chars (Defining_Entity (N)));
3835             Set_Scope (Anon_Id, Scope (Pack_Id));
3836
3837             --  Mark wrapper package as referenced, to avoid spurious warnings
3838             --  if the instantiation appears in various with_ clauses of
3839             --  subunits of the main unit.
3840
3841             Set_Referenced (Pack_Id);
3842          end if;
3843
3844          Set_Is_Generic_Instance (Anon_Id);
3845          Set_Needs_Debug_Info    (Anon_Id);
3846          Act_Decl_Id := New_Copy (Anon_Id);
3847
3848          Set_Parent            (Act_Decl_Id, Parent (Anon_Id));
3849          Set_Chars             (Act_Decl_Id, Chars (Defining_Entity (N)));
3850          Set_Sloc              (Act_Decl_Id, Sloc (Defining_Entity (N)));
3851          Set_Comes_From_Source (Act_Decl_Id, True);
3852
3853          --  The signature may involve types that are not frozen yet, but the
3854          --  subprogram will be frozen at the point the wrapper package is
3855          --  frozen, so it does not need its own freeze node. In fact, if one
3856          --  is created, it might conflict with the freezing actions from the
3857          --  wrapper package (see 7206-013).
3858
3859          --  Should not really reference non-public TN's in comments ???
3860
3861          Set_Has_Delayed_Freeze (Anon_Id, False);
3862
3863          --  If the instance is a child unit, mark the Id accordingly. Mark
3864          --  the anonymous entity as well, which is the real subprogram and
3865          --  which is used when the instance appears in a context clause.
3866
3867          Set_Is_Child_Unit (Act_Decl_Id, Is_Child_Unit (Defining_Entity (N)));
3868          Set_Is_Child_Unit (Anon_Id, Is_Child_Unit (Defining_Entity (N)));
3869          New_Overloaded_Entity (Act_Decl_Id);
3870          Check_Eliminated  (Act_Decl_Id);
3871
3872          --  In compilation unit case, kill elaboration checks on the
3873          --  instantiation, since they are never needed -- the body is
3874          --  instantiated at the same point as the spec.
3875
3876          if Nkind (Parent (N)) = N_Compilation_Unit then
3877             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
3878             Set_Kill_Elaboration_Checks       (Act_Decl_Id);
3879             Set_Is_Compilation_Unit (Anon_Id);
3880
3881             Set_Cunit_Entity (Current_Sem_Unit, Pack_Id);
3882          end if;
3883
3884          --  The instance is not a freezing point for the new subprogram
3885
3886          Set_Is_Frozen (Act_Decl_Id, False);
3887
3888          if Nkind (Defining_Entity (N)) = N_Defining_Operator_Symbol then
3889             Valid_Operator_Definition (Act_Decl_Id);
3890          end if;
3891
3892          Set_Alias  (Act_Decl_Id, Anon_Id);
3893          Set_Parent (Act_Decl_Id, Parent (Anon_Id));
3894          Set_Has_Completion (Act_Decl_Id);
3895          Set_Related_Instance (Pack_Id, Act_Decl_Id);
3896
3897          if Nkind (Parent (N)) = N_Compilation_Unit then
3898             Set_Body_Required (Parent (N), False);
3899          end if;
3900
3901       end Analyze_Instance_And_Renamings;
3902
3903    --  Start of processing for Analyze_Subprogram_Instantiation
3904
3905    begin
3906       --  Very first thing: apply the special kludge for Text_IO processing
3907       --  in case we are instantiating one of the children of [Wide_]Text_IO.
3908       --  Of course such an instantiation is bogus (these are packages, not
3909       --  subprograms), but we get a better error message if we do this.
3910
3911       Text_IO_Kludge (Gen_Id);
3912
3913       --  Make node global for error reporting
3914
3915       Instantiation_Node := N;
3916       Pre_Analyze_Actuals (N);
3917
3918       Init_Env;
3919       Env_Installed := True;
3920       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
3921       Gen_Unit := Entity (Gen_Id);
3922
3923       Generate_Reference (Gen_Unit, Gen_Id);
3924
3925       if Nkind (Gen_Id) = N_Identifier
3926         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
3927       then
3928          Error_Msg_NE
3929            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
3930       end if;
3931
3932       if Etype (Gen_Unit) = Any_Type then
3933          Restore_Env;
3934          return;
3935       end if;
3936
3937       --  Verify that it is a generic subprogram of the right kind, and that
3938       --  it does not lead to a circular instantiation.
3939
3940       if Ekind (Gen_Unit) /= E_Generic_Procedure
3941         and then Ekind (Gen_Unit) /= E_Generic_Function
3942       then
3943          Error_Msg_N ("expect generic subprogram in instantiation", Gen_Id);
3944
3945       elsif In_Open_Scopes (Gen_Unit) then
3946          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
3947
3948       elsif K = E_Procedure
3949         and then Ekind (Gen_Unit) /= E_Generic_Procedure
3950       then
3951          if Ekind (Gen_Unit) = E_Generic_Function then
3952             Error_Msg_N
3953               ("cannot instantiate generic function as procedure", Gen_Id);
3954          else
3955             Error_Msg_N
3956               ("expect name of generic procedure in instantiation", Gen_Id);
3957          end if;
3958
3959       elsif K = E_Function
3960         and then Ekind (Gen_Unit) /= E_Generic_Function
3961       then
3962          if Ekind (Gen_Unit) = E_Generic_Procedure then
3963             Error_Msg_N
3964               ("cannot instantiate generic procedure as function", Gen_Id);
3965          else
3966             Error_Msg_N
3967               ("expect name of generic function in instantiation", Gen_Id);
3968          end if;
3969
3970       else
3971          Set_Entity (Gen_Id, Gen_Unit);
3972          Set_Is_Instantiated (Gen_Unit);
3973
3974          if In_Extended_Main_Source_Unit (N) then
3975             Generate_Reference (Gen_Unit, N);
3976          end if;
3977
3978          --  If renaming, get original unit
3979
3980          if Present (Renamed_Object (Gen_Unit))
3981            and then (Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Procedure
3982                        or else
3983                      Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Function)
3984          then
3985             Gen_Unit := Renamed_Object (Gen_Unit);
3986             Set_Is_Instantiated (Gen_Unit);
3987             Generate_Reference  (Gen_Unit, N);
3988          end if;
3989
3990          if Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
3991             Error_Msg_Node_2 := Current_Scope;
3992             Error_Msg_NE
3993               ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
3994             Circularity_Detected := True;
3995             return;
3996          end if;
3997
3998          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
3999
4000          --  Initialize renamings map, for error checking
4001
4002          Generic_Renamings.Set_Last (0);
4003          Generic_Renamings_HTable.Reset;
4004
4005          Create_Instantiation_Source (N, Gen_Unit, False, S_Adjustment);
4006
4007          --  Copy original generic tree, to produce text for instantiation
4008
4009          Act_Tree :=
4010            Copy_Generic_Node
4011              (Original_Node (Gen_Decl), Empty, Instantiating => True);
4012
4013          Act_Spec := Specification (Act_Tree);
4014          Renaming_List :=
4015            Analyze_Associations
4016              (N,
4017               Generic_Formal_Declarations (Act_Tree),
4018               Generic_Formal_Declarations (Gen_Decl));
4019
4020          --  The subprogram itself cannot contain a nested instance, so the
4021          --  current parent is left empty.
4022
4023          Set_Instance_Env (Gen_Unit, Empty);
4024
4025          --  Build the subprogram declaration, which does not appear in the
4026          --  generic template, and give it a sloc consistent with that of the
4027          --  template.
4028
4029          Set_Defining_Unit_Name (Act_Spec, Anon_Id);
4030          Set_Generic_Parent (Act_Spec, Gen_Unit);
4031          Act_Decl :=
4032            Make_Subprogram_Declaration (Sloc (Act_Spec),
4033              Specification => Act_Spec);
4034
4035          Set_Categorization_From_Pragmas (Act_Decl);
4036
4037          if Parent_Installed then
4038             Hide_Current_Scope;
4039          end if;
4040
4041          Append (Act_Decl, Renaming_List);
4042          Analyze_Instance_And_Renamings;
4043
4044          --  If the generic is marked Import (Intrinsic), then so is the
4045          --  instance. This indicates that there is no body to instantiate. If
4046          --  generic is marked inline, so it the instance, and the anonymous
4047          --  subprogram it renames. If inlined, or else if inlining is enabled
4048          --  for the compilation, we generate the instance body even if it is
4049          --  not within the main unit.
4050
4051          --  Any other  pragmas might also be inherited ???
4052
4053          if Is_Intrinsic_Subprogram (Gen_Unit) then
4054             Set_Is_Intrinsic_Subprogram (Anon_Id);
4055             Set_Is_Intrinsic_Subprogram (Act_Decl_Id);
4056
4057             if Chars (Gen_Unit) = Name_Unchecked_Conversion then
4058                Validate_Unchecked_Conversion (N, Act_Decl_Id);
4059             end if;
4060          end if;
4061
4062          Generate_Definition (Act_Decl_Id);
4063
4064          Set_Is_Inlined (Act_Decl_Id, Is_Inlined (Gen_Unit));
4065          Set_Is_Inlined (Anon_Id,     Is_Inlined (Gen_Unit));
4066
4067          if not Is_Intrinsic_Subprogram (Gen_Unit) then
4068             Check_Elab_Instantiation (N);
4069          end if;
4070
4071          if Is_Dispatching_Operation (Act_Decl_Id)
4072            and then Ada_Version >= Ada_05
4073          then
4074             declare
4075                Formal : Entity_Id;
4076
4077             begin
4078                Formal := First_Formal (Act_Decl_Id);
4079                while Present (Formal) loop
4080                   if Ekind (Etype (Formal)) = E_Anonymous_Access_Type
4081                     and then Is_Controlling_Formal (Formal)
4082                     and then not Can_Never_Be_Null (Formal)
4083                   then
4084                      Error_Msg_NE ("access parameter& is controlling,",
4085                        N, Formal);
4086                      Error_Msg_NE ("\corresponding parameter of & must be"
4087                        & " explicitly null-excluding", N, Gen_Id);
4088                   end if;
4089
4090                   Next_Formal (Formal);
4091                end loop;
4092             end;
4093          end if;
4094
4095          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
4096
4097          --  Subject to change, pending on if other pragmas are inherited ???
4098
4099          Validate_Categorization_Dependency (N, Act_Decl_Id);
4100
4101          if not Is_Intrinsic_Subprogram (Act_Decl_Id) then
4102             if not Generic_Separately_Compiled (Gen_Unit) then
4103                Inherit_Context (Gen_Decl, N);
4104             end if;
4105
4106             Restore_Private_Views (Pack_Id, False);
4107
4108             --  If the context requires a full instantiation, mark node for
4109             --  subsequent construction of the body.
4110
4111             if (Is_In_Main_Unit (N)
4112                   or else Is_Inlined (Act_Decl_Id))
4113               and then (Operating_Mode = Generate_Code
4114                           or else (Operating_Mode = Check_Semantics
4115                                      and then ASIS_Mode))
4116               and then (Expander_Active or else ASIS_Mode)
4117               and then not ABE_Is_Certain (N)
4118               and then not Is_Eliminated (Act_Decl_Id)
4119             then
4120                Pending_Instantiations.Increment_Last;
4121                Pending_Instantiations.Table (Pending_Instantiations.Last) :=
4122                  (N, Act_Decl, Expander_Active, Current_Sem_Unit);
4123                Check_Forward_Instantiation (Gen_Decl);
4124
4125                --  The wrapper package is always delayed, because it does not
4126                --  constitute a freeze point, but to insure that the freeze
4127                --  node is placed properly, it is created directly when
4128                --  instantiating the body (otherwise the freeze node might
4129                --  appear to early for nested instantiations).
4130
4131             elsif Nkind (Parent (N)) = N_Compilation_Unit then
4132
4133                --  For ASIS purposes, indicate that the wrapper package has
4134                --  replaced the instantiation node.
4135
4136                Rewrite (N, Unit (Parent (N)));
4137                Set_Unit (Parent (N), N);
4138             end if;
4139
4140          elsif Nkind (Parent (N)) = N_Compilation_Unit then
4141
4142                --  Replace instance node for library-level instantiations of
4143                --  intrinsic subprograms, for ASIS use.
4144
4145                Rewrite (N, Unit (Parent (N)));
4146                Set_Unit (Parent (N), N);
4147          end if;
4148
4149          if Parent_Installed then
4150             Remove_Parent;
4151          end if;
4152
4153          Restore_Env;
4154          Env_Installed := False;
4155          Generic_Renamings.Set_Last (0);
4156          Generic_Renamings_HTable.Reset;
4157       end if;
4158
4159    exception
4160       when Instantiation_Error =>
4161          if Parent_Installed then
4162             Remove_Parent;
4163          end if;
4164
4165          if Env_Installed then
4166             Restore_Env;
4167          end if;
4168    end Analyze_Subprogram_Instantiation;
4169
4170    -------------------------
4171    -- Get_Associated_Node --
4172    -------------------------
4173
4174    function Get_Associated_Node (N : Node_Id) return Node_Id is
4175       Assoc : Node_Id := Associated_Node (N);
4176
4177    begin
4178       if Nkind (Assoc) /= Nkind (N) then
4179          return Assoc;
4180
4181       elsif Nkind (Assoc) = N_Aggregate
4182         or else Nkind (Assoc) = N_Extension_Aggregate
4183       then
4184          return Assoc;
4185
4186       else
4187          --  If the node is part of an inner generic, it may itself have been
4188          --  remapped into a further generic copy. Associated_Node is otherwise
4189          --  used for the entity of the node, and will be of a different node
4190          --  kind, or else N has been rewritten as a literal or function call.
4191
4192          while Present (Associated_Node (Assoc))
4193            and then Nkind (Associated_Node (Assoc)) = Nkind (Assoc)
4194          loop
4195             Assoc := Associated_Node (Assoc);
4196          end loop;
4197
4198          --  Follow and additional link in case the final node was rewritten.
4199          --  This can only happen with nested generic units.
4200
4201          if (Nkind (Assoc) = N_Identifier or else Nkind (Assoc) in N_Op)
4202            and then Present (Associated_Node (Assoc))
4203            and then (Nkind (Associated_Node (Assoc)) = N_Function_Call
4204                        or else
4205                      Nkind (Associated_Node (Assoc)) = N_Explicit_Dereference
4206                        or else
4207                      Nkind (Associated_Node (Assoc)) = N_Integer_Literal
4208                        or else
4209                      Nkind (Associated_Node (Assoc)) = N_Real_Literal
4210                        or else
4211                      Nkind (Associated_Node (Assoc)) = N_String_Literal)
4212          then
4213             Assoc := Associated_Node (Assoc);
4214          end if;
4215
4216          return Assoc;
4217       end if;
4218    end Get_Associated_Node;
4219
4220    -------------------------------------------
4221    -- Build_Instance_Compilation_Unit_Nodes --
4222    -------------------------------------------
4223
4224    procedure Build_Instance_Compilation_Unit_Nodes
4225      (N        : Node_Id;
4226       Act_Body : Node_Id;
4227       Act_Decl : Node_Id)
4228    is
4229       Decl_Cunit : Node_Id;
4230       Body_Cunit : Node_Id;
4231       Citem      : Node_Id;
4232       New_Main   : constant Entity_Id := Defining_Entity (Act_Decl);
4233       Old_Main   : constant Entity_Id := Cunit_Entity (Main_Unit);
4234
4235    begin
4236       --  A new compilation unit node is built for the instance declaration
4237
4238       Decl_Cunit :=
4239         Make_Compilation_Unit (Sloc (N),
4240           Context_Items  => Empty_List,
4241           Unit           => Act_Decl,
4242           Aux_Decls_Node =>
4243             Make_Compilation_Unit_Aux (Sloc (N)));
4244
4245       Set_Parent_Spec   (Act_Decl, Parent_Spec (N));
4246       Set_Body_Required (Decl_Cunit, True);
4247
4248       --  We use the original instantiation compilation unit as the resulting
4249       --  compilation unit of the instance, since this is the main unit.
4250
4251       Rewrite (N, Act_Body);
4252       Body_Cunit := Parent (N);
4253
4254       --  The two compilation unit nodes are linked by the Library_Unit field
4255
4256       Set_Library_Unit  (Decl_Cunit, Body_Cunit);
4257       Set_Library_Unit  (Body_Cunit, Decl_Cunit);
4258
4259       --  Preserve the private nature of the package if needed
4260
4261       Set_Private_Present (Decl_Cunit, Private_Present (Body_Cunit));
4262
4263       --  If the instance is not the main unit, its context, categorization,
4264       --  and elaboration entity are not relevant to the compilation.
4265
4266       if Parent (N) /= Cunit (Main_Unit) then
4267          return;
4268       end if;
4269
4270       --  The context clause items on the instantiation, which are now attached
4271       --  to the body compilation unit (since the body overwrote the original
4272       --  instantiation node), semantically belong on the spec, so copy them
4273       --  there. It's harmless to leave them on the body as well. In fact one
4274       --  could argue that they belong in both places.
4275
4276       Citem := First (Context_Items (Body_Cunit));
4277       while Present (Citem) loop
4278          Append (New_Copy (Citem), Context_Items (Decl_Cunit));
4279          Next (Citem);
4280       end loop;
4281
4282       --  Propagate categorization flags on packages, so that they appear in
4283       --  the ali file for the spec of the unit.
4284
4285       if Ekind (New_Main) = E_Package then
4286          Set_Is_Pure           (Old_Main, Is_Pure (New_Main));
4287          Set_Is_Preelaborated  (Old_Main, Is_Preelaborated (New_Main));
4288          Set_Is_Remote_Types   (Old_Main, Is_Remote_Types (New_Main));
4289          Set_Is_Shared_Passive (Old_Main, Is_Shared_Passive (New_Main));
4290          Set_Is_Remote_Call_Interface
4291            (Old_Main, Is_Remote_Call_Interface (New_Main));
4292       end if;
4293
4294       --  Make entry in Units table, so that binder can generate call to
4295       --  elaboration procedure for body, if any.
4296
4297       Make_Instance_Unit (Body_Cunit);
4298       Main_Unit_Entity := New_Main;
4299       Set_Cunit_Entity (Main_Unit, Main_Unit_Entity);
4300
4301       --  Build elaboration entity, since the instance may certainly generate
4302       --  elaboration code requiring a flag for protection.
4303
4304       Build_Elaboration_Entity (Decl_Cunit, New_Main);
4305    end Build_Instance_Compilation_Unit_Nodes;
4306
4307    -----------------------------
4308    -- Check_Access_Definition --
4309    -----------------------------
4310
4311    procedure Check_Access_Definition (N : Node_Id) is
4312    begin
4313       pragma Assert
4314         (Ada_Version >= Ada_05
4315            and then Present (Access_Definition (N)));
4316       null;
4317    end Check_Access_Definition;
4318
4319    -----------------------------------
4320    -- Check_Formal_Package_Instance --
4321    -----------------------------------
4322
4323    --  If the formal has specific parameters, they must match those of the
4324    --  actual. Both of them are instances, and the renaming declarations for
4325    --  their formal parameters appear in the same order in both. The analyzed
4326    --  formal has been analyzed in the context of the current instance.
4327
4328    procedure Check_Formal_Package_Instance
4329      (Formal_Pack : Entity_Id;
4330       Actual_Pack : Entity_Id)
4331    is
4332       E1 : Entity_Id := First_Entity (Actual_Pack);
4333       E2 : Entity_Id := First_Entity (Formal_Pack);
4334
4335       Expr1 : Node_Id;
4336       Expr2 : Node_Id;
4337
4338       procedure Check_Mismatch (B : Boolean);
4339       --  Common error routine for mismatch between the parameters of the
4340       --  actual instance and those of the formal package.
4341
4342       function Same_Instantiated_Constant (E1, E2 : Entity_Id) return Boolean;
4343       --  The formal may come from a nested formal package, and the actual may
4344       --  have been constant-folded. To determine whether the two denote the
4345       --  same entity we may have to traverse several definitions to recover
4346       --  the ultimate entity that they refer to.
4347
4348       function Same_Instantiated_Variable (E1, E2 : Entity_Id) return Boolean;
4349       --  Similarly, if the formal comes from a nested formal package, the
4350       --  actual may designate the formal through multiple renamings, which
4351       --  have to be followed to determine the original variable in question.
4352
4353       --------------------
4354       -- Check_Mismatch --
4355       --------------------
4356
4357       procedure Check_Mismatch (B : Boolean) is
4358          Kind : constant Node_Kind := Nkind (Parent (E2));
4359
4360       begin
4361          if Kind = N_Formal_Type_Declaration then
4362             return;
4363
4364          elsif Kind = N_Formal_Object_Declaration
4365            or else Kind in N_Formal_Subprogram_Declaration
4366            or else Kind = N_Formal_Package_Declaration
4367          then
4368             null;
4369
4370          elsif B then
4371             Error_Msg_NE
4372               ("actual for & in actual instance does not match formal",
4373                Parent (Actual_Pack), E1);
4374          end if;
4375       end Check_Mismatch;
4376
4377       --------------------------------
4378       -- Same_Instantiated_Constant --
4379       --------------------------------
4380
4381       function Same_Instantiated_Constant
4382         (E1, E2 : Entity_Id) return Boolean
4383       is
4384          Ent : Entity_Id;
4385
4386       begin
4387          Ent := E2;
4388          while Present (Ent) loop
4389             if E1 = Ent then
4390                return True;
4391
4392             elsif Ekind (Ent) /= E_Constant then
4393                return False;
4394
4395             elsif Is_Entity_Name (Constant_Value (Ent)) then
4396                if  Entity (Constant_Value (Ent)) = E1 then
4397                   return True;
4398                else
4399                   Ent := Entity (Constant_Value (Ent));
4400                end if;
4401
4402             --  The actual may be a constant that has been folded. Recover
4403             --  original name.
4404
4405             elsif Is_Entity_Name (Original_Node (Constant_Value (Ent))) then
4406                   Ent := Entity (Original_Node (Constant_Value (Ent)));
4407             else
4408                return False;
4409             end if;
4410          end loop;
4411
4412          return False;
4413       end Same_Instantiated_Constant;
4414
4415       --------------------------------
4416       -- Same_Instantiated_Variable --
4417       --------------------------------
4418
4419       function Same_Instantiated_Variable
4420         (E1, E2 : Entity_Id) return Boolean
4421       is
4422          function Original_Entity (E : Entity_Id) return Entity_Id;
4423          --  Follow chain of renamings to the ultimate ancestor
4424
4425          ---------------------
4426          -- Original_Entity --
4427          ---------------------
4428
4429          function Original_Entity (E : Entity_Id) return Entity_Id is
4430             Orig : Entity_Id;
4431
4432          begin
4433             Orig := E;
4434             while Nkind (Parent (Orig)) = N_Object_Renaming_Declaration
4435               and then Present (Renamed_Object (Orig))
4436               and then Is_Entity_Name (Renamed_Object (Orig))
4437             loop
4438                Orig := Entity (Renamed_Object (Orig));
4439             end loop;
4440
4441             return Orig;
4442          end Original_Entity;
4443
4444       --  Start of processing for Same_Instantiated_Variable
4445
4446       begin
4447          return Ekind (E1) = Ekind (E2)
4448            and then Original_Entity (E1) = Original_Entity (E2);
4449       end Same_Instantiated_Variable;
4450
4451    --  Start of processing for Check_Formal_Package_Instance
4452
4453    begin
4454       while Present (E1)
4455         and then Present (E2)
4456       loop
4457          exit when Ekind (E1) = E_Package
4458            and then Renamed_Entity (E1) = Renamed_Entity (Actual_Pack);
4459
4460          --  If the formal is the renaming of the formal package, this
4461          --  is the end of its formal part, which may occur before the
4462          --  end of the formal part in the actual in the presence of
4463          --  defaulted parameters in the formal package.
4464
4465          exit when Nkind (Parent (E2)) = N_Package_Renaming_Declaration
4466            and then Renamed_Entity (E2) = Scope (E2);
4467
4468          --  The analysis of the actual may generate additional internal
4469          --  entities. If the formal is defaulted, there is no corresponding
4470          --  analysis and the internal entities must be skipped, until we
4471          --  find corresponding entities again.
4472
4473          if Comes_From_Source (E2)
4474            and then not Comes_From_Source (E1)
4475            and then Chars (E1) /= Chars (E2)
4476          then
4477             while Present (E1)
4478               and then  Chars (E1) /= Chars (E2)
4479             loop
4480                Next_Entity (E1);
4481             end loop;
4482          end if;
4483
4484          if No (E1) then
4485             return;
4486
4487          --  If the formal entity comes from a formal declaration. it was
4488          --  defaulted in the formal package, and no check is needed on it.
4489
4490          elsif Nkind (Parent (E2)) =  N_Formal_Object_Declaration then
4491             goto Next_E;
4492
4493          elsif Is_Type (E1) then
4494
4495             --  Subtypes must statically match. E1, E2 are the local entities
4496             --  that are subtypes of the actuals. Itypes generated for other
4497             --  parameters need not be checked, the check will be performed
4498             --  on the parameters themselves.
4499
4500             --  If E2 is a formal type declaration, it is a defaulted parameter
4501             --  and needs no checking.
4502
4503             if not Is_Itype (E1)
4504               and then not Is_Itype (E2)
4505             then
4506                Check_Mismatch
4507                  (not Is_Type (E2)
4508                    or else Etype (E1) /= Etype (E2)
4509                    or else not Subtypes_Statically_Match (E1, E2));
4510             end if;
4511
4512          elsif Ekind (E1) = E_Constant then
4513
4514             --  IN parameters must denote the same static value, or the same
4515             --  constant, or the literal null.
4516
4517             Expr1 := Expression (Parent (E1));
4518
4519             if Ekind (E2) /= E_Constant then
4520                Check_Mismatch (True);
4521                goto Next_E;
4522             else
4523                Expr2 := Expression (Parent (E2));
4524             end if;
4525
4526             if Is_Static_Expression (Expr1) then
4527
4528                if not Is_Static_Expression (Expr2) then
4529                   Check_Mismatch (True);
4530
4531                elsif Is_Discrete_Type (Etype (E1)) then
4532                   declare
4533                      V1 : constant Uint := Expr_Value (Expr1);
4534                      V2 : constant Uint := Expr_Value (Expr2);
4535                   begin
4536                      Check_Mismatch (V1 /= V2);
4537                   end;
4538
4539                elsif Is_Real_Type (Etype (E1)) then
4540                   declare
4541                      V1 : constant Ureal := Expr_Value_R (Expr1);
4542                      V2 : constant Ureal := Expr_Value_R (Expr2);
4543                   begin
4544                      Check_Mismatch (V1 /= V2);
4545                   end;
4546
4547                elsif Is_String_Type (Etype (E1))
4548                  and then Nkind (Expr1) = N_String_Literal
4549                then
4550                   if Nkind (Expr2) /= N_String_Literal then
4551                      Check_Mismatch (True);
4552                   else
4553                      Check_Mismatch
4554                        (not String_Equal (Strval (Expr1), Strval (Expr2)));
4555                   end if;
4556                end if;
4557
4558             elsif Is_Entity_Name (Expr1) then
4559                if Is_Entity_Name (Expr2) then
4560                   if Entity (Expr1) = Entity (Expr2) then
4561                      null;
4562                   else
4563                      Check_Mismatch
4564                        (not Same_Instantiated_Constant
4565                          (Entity (Expr1), Entity (Expr2)));
4566                   end if;
4567                else
4568                   Check_Mismatch (True);
4569                end if;
4570
4571             elsif Is_Entity_Name (Original_Node (Expr1))
4572               and then Is_Entity_Name (Expr2)
4573             and then
4574               Same_Instantiated_Constant
4575                 (Entity (Original_Node (Expr1)), Entity (Expr2))
4576             then
4577                null;
4578
4579             elsif Nkind (Expr1) = N_Null then
4580                Check_Mismatch (Nkind (Expr1) /= N_Null);
4581
4582             else
4583                Check_Mismatch (True);
4584             end if;
4585
4586          elsif Ekind (E1) = E_Variable then
4587             Check_Mismatch (not Same_Instantiated_Variable (E1, E2));
4588
4589          elsif Ekind (E1) = E_Package then
4590             Check_Mismatch
4591               (Ekind (E1) /= Ekind (E2)
4592                 or else Renamed_Object (E1) /= Renamed_Object (E2));
4593
4594          elsif Is_Overloadable (E1) then
4595
4596             --  Verify that the names of the entities match. Note that actuals
4597             --  that are attributes are rewritten as subprograms.
4598
4599             Check_Mismatch
4600               (Ekind (E2) /= Ekind (E1) or else (Alias (E1)) /= Alias (E2));
4601
4602          else
4603             raise Program_Error;
4604          end if;
4605
4606          <<Next_E>>
4607             Next_Entity (E1);
4608             Next_Entity (E2);
4609       end loop;
4610    end Check_Formal_Package_Instance;
4611
4612    ---------------------------
4613    -- Check_Formal_Packages --
4614    ---------------------------
4615
4616    procedure Check_Formal_Packages (P_Id : Entity_Id) is
4617       E        : Entity_Id;
4618       Formal_P : Entity_Id;
4619
4620    begin
4621       --  Iterate through the declarations in the instance, looking for package
4622       --  renaming declarations that denote instances of formal packages. Stop
4623       --  when we find the renaming of the current package itself. The
4624       --  declaration for a formal package without a box is followed by an
4625       --  internal entity that repeats the instantiation.
4626
4627       E := First_Entity (P_Id);
4628       while Present (E) loop
4629          if Ekind (E) = E_Package then
4630             if Renamed_Object (E) = P_Id then
4631                exit;
4632
4633             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
4634                null;
4635
4636             elsif not Box_Present (Parent (Associated_Formal_Package (E))) then
4637                Formal_P := Next_Entity (E);
4638                Check_Formal_Package_Instance (Formal_P, E);
4639
4640                --  After checking, remove the internal validating package. It
4641                --  is only needed for semantic checks, and as it may contain
4642                --  generic formal declarations it should not reach gigi.
4643
4644                Remove (Unit_Declaration_Node (Formal_P));
4645             end if;
4646          end if;
4647
4648          Next_Entity (E);
4649       end loop;
4650    end Check_Formal_Packages;
4651
4652    ---------------------------------
4653    -- Check_Forward_Instantiation --
4654    ---------------------------------
4655
4656    procedure Check_Forward_Instantiation (Decl : Node_Id) is
4657       S        : Entity_Id;
4658       Gen_Comp : Entity_Id := Cunit_Entity (Get_Source_Unit (Decl));
4659
4660    begin
4661       --  The instantiation appears before the generic body if we are in the
4662       --  scope of the unit containing the generic, either in its spec or in
4663       --  the package body. and before the generic body.
4664
4665       if Ekind (Gen_Comp) = E_Package_Body then
4666          Gen_Comp := Spec_Entity (Gen_Comp);
4667       end if;
4668
4669       if In_Open_Scopes (Gen_Comp)
4670         and then No (Corresponding_Body (Decl))
4671       then
4672          S := Current_Scope;
4673
4674          while Present (S)
4675            and then not Is_Compilation_Unit (S)
4676            and then not Is_Child_Unit (S)
4677          loop
4678             if Ekind (S) = E_Package then
4679                Set_Has_Forward_Instantiation (S);
4680             end if;
4681
4682             S := Scope (S);
4683          end loop;
4684       end if;
4685    end Check_Forward_Instantiation;
4686
4687    ---------------------------
4688    -- Check_Generic_Actuals --
4689    ---------------------------
4690
4691    --  The visibility of the actuals may be different between the point of
4692    --  generic instantiation and the instantiation of the body.
4693
4694    procedure Check_Generic_Actuals
4695      (Instance      : Entity_Id;
4696       Is_Formal_Box : Boolean)
4697    is
4698       E      : Entity_Id;
4699       Astype : Entity_Id;
4700
4701       function Denotes_Previous_Actual (Typ : Entity_Id) return Boolean;
4702       --  For a formal that is an array type, the component type is often a
4703       --  previous formal in the same unit. The privacy status of the component
4704       --  type will have been examined earlier in the traversal of the
4705       --  corresponding actuals, and this status should not be modified for the
4706       --  array type itself.
4707       --
4708       --  To detect this case we have to rescan the list of formals, which
4709       --  is usually short enough to ignore the resulting inefficiency.
4710
4711       function Denotes_Previous_Actual (Typ : Entity_Id) return Boolean is
4712          Prev : Entity_Id;
4713       begin
4714          Prev := First_Entity (Instance);
4715          while Present (Prev) loop
4716             if Is_Type (Prev)
4717               and then Nkind (Parent (Prev)) = N_Subtype_Declaration
4718               and then Is_Entity_Name (Subtype_Indication (Parent (Prev)))
4719               and then Entity (Subtype_Indication (Parent (Prev))) = Typ
4720             then
4721                return True;
4722             elsif Prev = E then
4723                return False;
4724             else
4725                Next_Entity (Prev);
4726             end if;
4727          end loop;
4728          return False;
4729       end Denotes_Previous_Actual;
4730
4731    --  Start of processing for Check_Generic_Actuals
4732
4733    begin
4734       E := First_Entity (Instance);
4735       while Present (E) loop
4736          if Is_Type (E)
4737            and then Nkind (Parent (E)) = N_Subtype_Declaration
4738            and then Scope (Etype (E)) /= Instance
4739            and then Is_Entity_Name (Subtype_Indication (Parent (E)))
4740          then
4741             if Is_Array_Type (E)
4742               and then Denotes_Previous_Actual (Component_Type (E))
4743             then
4744                null;
4745             else
4746                Check_Private_View (Subtype_Indication (Parent (E)));
4747             end if;
4748             Set_Is_Generic_Actual_Type (E, True);
4749             Set_Is_Hidden (E, False);
4750             Set_Is_Potentially_Use_Visible (E,
4751               In_Use (Instance));
4752
4753             --  We constructed the generic actual type as a subtype of the
4754             --  supplied type. This means that it normally would not inherit
4755             --  subtype specific attributes of the actual, which is wrong for
4756             --  the generic case.
4757
4758             Astype := Ancestor_Subtype (E);
4759
4760             if No (Astype) then
4761
4762                --  This can happen when E is an itype that is the full view of
4763                --  a private type completed, e.g. with a constrained array. In
4764                --  that case, use the first subtype, which will carry size
4765                --  information. The base type itself is unconstrained and will
4766                --  not carry it.
4767
4768                Astype := First_Subtype (E);
4769             end if;
4770
4771             Set_Size_Info      (E,                (Astype));
4772             Set_RM_Size        (E, RM_Size        (Astype));
4773             Set_First_Rep_Item (E, First_Rep_Item (Astype));
4774
4775             if Is_Discrete_Or_Fixed_Point_Type (E) then
4776                Set_RM_Size (E, RM_Size (Astype));
4777
4778             --  In  nested instances, the base type of an access actual
4779             --  may itself be private, and need to be exchanged.
4780
4781             elsif Is_Access_Type (E)
4782               and then Is_Private_Type (Etype (E))
4783             then
4784                Check_Private_View
4785                  (New_Occurrence_Of (Etype (E), Sloc (Instance)));
4786             end if;
4787
4788          elsif Ekind (E) = E_Package then
4789
4790             --  If this is the renaming for the current instance, we're done.
4791             --  Otherwise it is a formal package. If the corresponding formal
4792             --  was declared with a box, the (instantiations of the) generic
4793             --  formal part are also visible. Otherwise, ignore the entity
4794             --  created to validate the actuals.
4795
4796             if Renamed_Object (E) = Instance then
4797                exit;
4798
4799             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
4800                null;
4801
4802             --  The visibility of a formal of an enclosing generic is already
4803             --  correct.
4804
4805             elsif Denotes_Formal_Package (E) then
4806                null;
4807
4808             elsif Present (Associated_Formal_Package (E))
4809               and then not Is_Generic_Formal (E)
4810             then
4811                if Box_Present (Parent (Associated_Formal_Package (E))) then
4812                   Check_Generic_Actuals (Renamed_Object (E), True);
4813
4814                else
4815                   Check_Generic_Actuals (Renamed_Object (E), False);
4816                end if;
4817
4818                Set_Is_Hidden (E, False);
4819             end if;
4820
4821          --  If this is a subprogram instance (in a wrapper package) the
4822          --  actual is fully visible.
4823
4824          elsif Is_Wrapper_Package (Instance) then
4825             Set_Is_Hidden (E, False);
4826
4827          --  If the formal package is declared with a box, or if the formal
4828          --  parameter is defaulted, it is visible in the body.
4829
4830          elsif Is_Formal_Box
4831            or else Is_Visible_Formal (E)
4832          then
4833             Set_Is_Hidden (E, False);
4834          end if;
4835
4836          Next_Entity (E);
4837       end loop;
4838    end Check_Generic_Actuals;
4839
4840    ------------------------------
4841    -- Check_Generic_Child_Unit --
4842    ------------------------------
4843
4844    procedure Check_Generic_Child_Unit
4845      (Gen_Id           : Node_Id;
4846       Parent_Installed : in out Boolean)
4847    is
4848       Loc      : constant Source_Ptr := Sloc (Gen_Id);
4849       Gen_Par  : Entity_Id := Empty;
4850       Inst_Par : Entity_Id;
4851       E        : Entity_Id;
4852       S        : Node_Id;
4853
4854       function Find_Generic_Child
4855         (Scop : Entity_Id;
4856          Id   : Node_Id) return Entity_Id;
4857       --  Search generic parent for possible child unit with the given name
4858
4859       function In_Enclosing_Instance return Boolean;
4860       --  Within an instance of the parent, the child unit may be denoted
4861       --  by a simple name, or an abbreviated expanded name. Examine enclosing
4862       --  scopes to locate a possible parent instantiation.
4863
4864       ------------------------
4865       -- Find_Generic_Child --
4866       ------------------------
4867
4868       function Find_Generic_Child
4869         (Scop : Entity_Id;
4870          Id   : Node_Id) return Entity_Id
4871       is
4872          E : Entity_Id;
4873
4874       begin
4875          --  If entity of name is already set, instance has already been
4876          --  resolved, e.g. in an enclosing instantiation.
4877
4878          if Present (Entity (Id)) then
4879             if Scope (Entity (Id)) = Scop then
4880                return Entity (Id);
4881             else
4882                return Empty;
4883             end if;
4884
4885          else
4886             E := First_Entity (Scop);
4887             while Present (E) loop
4888                if Chars (E) = Chars (Id)
4889                  and then Is_Child_Unit (E)
4890                then
4891                   if Is_Child_Unit (E)
4892                     and then not Is_Visible_Child_Unit (E)
4893                   then
4894                      Error_Msg_NE
4895                        ("generic child unit& is not visible", Gen_Id, E);
4896                   end if;
4897
4898                   Set_Entity (Id, E);
4899                   return E;
4900                end if;
4901
4902                Next_Entity (E);
4903             end loop;
4904
4905             return Empty;
4906          end if;
4907       end Find_Generic_Child;
4908
4909       ---------------------------
4910       -- In_Enclosing_Instance --
4911       ---------------------------
4912
4913       function In_Enclosing_Instance return Boolean is
4914          Enclosing_Instance : Node_Id;
4915          Instance_Decl      : Node_Id;
4916
4917       begin
4918          --  We do not inline any call that contains instantiations, except
4919          --  for instantiations of Unchecked_Conversion, so if we are within
4920          --  an inlined body the current instance does not require parents.
4921
4922          if In_Inlined_Body then
4923             pragma Assert (Chars (Gen_Id) = Name_Unchecked_Conversion);
4924             return False;
4925          end if;
4926
4927          --  Loop to check enclosing scopes
4928
4929          Enclosing_Instance := Current_Scope;
4930          while Present (Enclosing_Instance) loop
4931             Instance_Decl := Unit_Declaration_Node (Enclosing_Instance);
4932
4933             if Ekind (Enclosing_Instance) = E_Package
4934               and then Is_Generic_Instance (Enclosing_Instance)
4935               and then Present
4936                 (Generic_Parent (Specification (Instance_Decl)))
4937             then
4938                --  Check whether the generic we are looking for is a child of
4939                --  this instance.
4940
4941                E := Find_Generic_Child
4942                       (Generic_Parent (Specification (Instance_Decl)), Gen_Id);
4943                exit when Present (E);
4944
4945             else
4946                E := Empty;
4947             end if;
4948
4949             Enclosing_Instance := Scope (Enclosing_Instance);
4950          end loop;
4951
4952          if No (E) then
4953
4954             --  Not a child unit
4955
4956             Analyze (Gen_Id);
4957             return False;
4958
4959          else
4960             Rewrite (Gen_Id,
4961               Make_Expanded_Name (Loc,
4962                 Chars         => Chars (E),
4963                 Prefix        => New_Occurrence_Of (Enclosing_Instance, Loc),
4964                 Selector_Name => New_Occurrence_Of (E, Loc)));
4965
4966             Set_Entity (Gen_Id, E);
4967             Set_Etype  (Gen_Id, Etype (E));
4968             Parent_Installed := False;      -- Already in scope.
4969             return True;
4970          end if;
4971       end In_Enclosing_Instance;
4972
4973    --  Start of processing for Check_Generic_Child_Unit
4974
4975    begin
4976       --  If the name of the generic is given by a selected component, it may
4977       --  be the name of a generic child unit, and the prefix is the name of an
4978       --  instance of the parent, in which case the child unit must be visible.
4979       --  If this instance is not in scope, it must be placed there and removed
4980       --  after instantiation, because what is being instantiated is not the
4981       --  original child, but the corresponding child present in the instance
4982       --  of the parent.
4983
4984       --  If the child is instantiated within the parent, it can be given by
4985       --  a simple name. In this case the instance is already in scope, but
4986       --  the child generic must be recovered from the generic parent as well.
4987
4988       if Nkind (Gen_Id) = N_Selected_Component then
4989          S := Selector_Name (Gen_Id);
4990          Analyze (Prefix (Gen_Id));
4991          Inst_Par := Entity (Prefix (Gen_Id));
4992
4993          if Ekind (Inst_Par) = E_Package
4994            and then Present (Renamed_Object (Inst_Par))
4995          then
4996             Inst_Par := Renamed_Object (Inst_Par);
4997          end if;
4998
4999          if Ekind (Inst_Par) = E_Package then
5000             if Nkind (Parent (Inst_Par)) = N_Package_Specification then
5001                Gen_Par := Generic_Parent (Parent (Inst_Par));
5002
5003             elsif Nkind (Parent (Inst_Par)) = N_Defining_Program_Unit_Name
5004               and then
5005                 Nkind (Parent (Parent (Inst_Par))) = N_Package_Specification
5006             then
5007                Gen_Par := Generic_Parent (Parent (Parent (Inst_Par)));
5008             end if;
5009
5010          elsif Ekind (Inst_Par) = E_Generic_Package
5011            and then Nkind (Parent (Gen_Id)) = N_Formal_Package_Declaration
5012          then
5013             --  A formal package may be a real child package, and not the
5014             --  implicit instance within a parent. In this case the child is
5015             --  not visible and has to be retrieved explicitly as well.
5016
5017             Gen_Par := Inst_Par;
5018          end if;
5019
5020          if Present (Gen_Par) then
5021
5022             --  The prefix denotes an instantiation. The entity itself may be a
5023             --  nested generic, or a child unit.
5024
5025             E := Find_Generic_Child (Gen_Par, S);
5026
5027             if Present (E) then
5028                Change_Selected_Component_To_Expanded_Name (Gen_Id);
5029                Set_Entity (Gen_Id, E);
5030                Set_Etype (Gen_Id, Etype (E));
5031                Set_Entity (S, E);
5032                Set_Etype (S, Etype (E));
5033
5034                --  Indicate that this is a reference to the parent
5035
5036                if In_Extended_Main_Source_Unit (Gen_Id) then
5037                   Set_Is_Instantiated (Inst_Par);
5038                end if;
5039
5040                --  A common mistake is to replicate the naming scheme of a
5041                --  hierarchy by instantiating a generic child directly, rather
5042                --  than the implicit child in a parent instance:
5043
5044                --  generic .. package Gpar is ..
5045                --  generic .. package Gpar.Child is ..
5046                --  package Par is new Gpar ();
5047
5048                --  with Gpar.Child;
5049                --  package Par.Child is new Gpar.Child ();
5050                --                           rather than Par.Child
5051
5052                --  In this case the instantiation is within Par, which is an
5053                --  instance, but Gpar does not denote Par because we are not IN
5054                --  the instance of Gpar, so this is illegal. The test below
5055                --  recognizes this particular case.
5056
5057                if Is_Child_Unit (E)
5058                  and then not Comes_From_Source (Entity (Prefix (Gen_Id)))
5059                  and then (not In_Instance
5060                              or else Nkind (Parent (Parent (Gen_Id))) =
5061                                                          N_Compilation_Unit)
5062                then
5063                   Error_Msg_N
5064                     ("prefix of generic child unit must be instance of parent",
5065                       Gen_Id);
5066                end if;
5067
5068                if not In_Open_Scopes (Inst_Par)
5069                  and then Nkind (Parent (Gen_Id)) not in
5070                                            N_Generic_Renaming_Declaration
5071                then
5072                   Install_Parent (Inst_Par);
5073                   Parent_Installed := True;
5074
5075                elsif In_Open_Scopes (Inst_Par) then
5076
5077                   --  If the parent is already installed verify that the
5078                   --  actuals for its formal packages declared with a box
5079                   --  are already installed. This is necessary when the
5080                   --  child instance is a child of the parent instance.
5081                   --  In this case the parent is placed on the scope stack
5082                   --  but the formal packages are not made visible.
5083
5084                   Install_Formal_Packages (Inst_Par);
5085                end if;
5086
5087             else
5088                --  If the generic parent does not contain an entity that
5089                --  corresponds to the selector, the instance doesn't either.
5090                --  Analyzing the node will yield the appropriate error message.
5091                --  If the entity is not a child unit, then it is an inner
5092                --  generic in the parent.
5093
5094                Analyze (Gen_Id);
5095             end if;
5096
5097          else
5098             Analyze (Gen_Id);
5099
5100             if Is_Child_Unit (Entity (Gen_Id))
5101               and then
5102                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
5103               and then not In_Open_Scopes (Inst_Par)
5104             then
5105                Install_Parent (Inst_Par);
5106                Parent_Installed := True;
5107             end if;
5108          end if;
5109
5110       elsif Nkind (Gen_Id) = N_Expanded_Name then
5111
5112          --  Entity already present, analyze prefix, whose meaning may be
5113          --  an instance in the current context. If it is an instance of
5114          --  a relative within another, the proper parent may still have
5115          --  to be installed, if they are not of the same generation.
5116
5117          Analyze (Prefix (Gen_Id));
5118          Inst_Par := Entity (Prefix (Gen_Id));
5119
5120          if In_Enclosing_Instance then
5121             null;
5122
5123          elsif Present (Entity (Gen_Id))
5124            and then Is_Child_Unit (Entity (Gen_Id))
5125            and then not In_Open_Scopes (Inst_Par)
5126          then
5127             Install_Parent (Inst_Par);
5128             Parent_Installed := True;
5129          end if;
5130
5131       elsif In_Enclosing_Instance then
5132
5133          --  The child unit is found in some enclosing scope
5134
5135          null;
5136
5137       else
5138          Analyze (Gen_Id);
5139
5140          --  If this is the renaming of the implicit child in a parent
5141          --  instance, recover the parent name and install it.
5142
5143          if Is_Entity_Name (Gen_Id) then
5144             E := Entity (Gen_Id);
5145
5146             if Is_Generic_Unit (E)
5147               and then Nkind (Parent (E)) in N_Generic_Renaming_Declaration
5148               and then Is_Child_Unit (Renamed_Object (E))
5149               and then Is_Generic_Unit (Scope (Renamed_Object (E)))
5150               and then Nkind (Name (Parent (E))) = N_Expanded_Name
5151             then
5152                Rewrite (Gen_Id,
5153                  New_Copy_Tree (Name (Parent (E))));
5154                Inst_Par := Entity (Prefix (Gen_Id));
5155
5156                if not In_Open_Scopes (Inst_Par) then
5157                   Install_Parent (Inst_Par);
5158                   Parent_Installed := True;
5159                end if;
5160
5161             --  If it is a child unit of a non-generic parent, it may be
5162             --  use-visible and given by a direct name. Install parent as
5163             --  for other cases.
5164
5165             elsif Is_Generic_Unit (E)
5166               and then Is_Child_Unit (E)
5167               and then
5168                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
5169               and then not Is_Generic_Unit (Scope (E))
5170             then
5171                if not In_Open_Scopes (Scope (E)) then
5172                   Install_Parent (Scope (E));
5173                   Parent_Installed := True;
5174                end if;
5175             end if;
5176          end if;
5177       end if;
5178    end Check_Generic_Child_Unit;
5179
5180    -----------------------------
5181    -- Check_Hidden_Child_Unit --
5182    -----------------------------
5183
5184    procedure Check_Hidden_Child_Unit
5185      (N           : Node_Id;
5186       Gen_Unit    : Entity_Id;
5187       Act_Decl_Id : Entity_Id)
5188    is
5189       Gen_Id : constant Node_Id := Name (N);
5190
5191    begin
5192       if Is_Child_Unit (Gen_Unit)
5193         and then Is_Child_Unit (Act_Decl_Id)
5194         and then Nkind (Gen_Id) = N_Expanded_Name
5195         and then Entity (Prefix (Gen_Id)) = Scope (Act_Decl_Id)
5196         and then Chars (Gen_Unit) = Chars (Act_Decl_Id)
5197       then
5198          Error_Msg_Node_2 := Scope (Act_Decl_Id);
5199          Error_Msg_NE
5200            ("generic unit & is implicitly declared in &",
5201              Defining_Unit_Name (N), Gen_Unit);
5202          Error_Msg_N ("\instance must have different name",
5203            Defining_Unit_Name (N));
5204       end if;
5205    end Check_Hidden_Child_Unit;
5206
5207    ------------------------
5208    -- Check_Private_View --
5209    ------------------------
5210
5211    procedure Check_Private_View (N : Node_Id) is
5212       T : constant Entity_Id := Etype (N);
5213       BT : Entity_Id;
5214
5215    begin
5216       --  Exchange views if the type was not private in the generic but is
5217       --  private at the point of instantiation. Do not exchange views if
5218       --  the scope of the type is in scope. This can happen if both generic
5219       --  and instance are sibling units, or if type is defined in a parent.
5220       --  In this case the visibility of the type will be correct for all
5221       --  semantic checks.
5222
5223       if Present (T) then
5224          BT := Base_Type (T);
5225
5226          if Is_Private_Type (T)
5227            and then not Has_Private_View (N)
5228            and then Present (Full_View (T))
5229            and then not In_Open_Scopes (Scope (T))
5230          then
5231             --  In the generic, the full type was visible. Save the private
5232             --  entity, for subsequent exchange.
5233
5234             Switch_View (T);
5235
5236          elsif Has_Private_View (N)
5237            and then not Is_Private_Type (T)
5238            and then not Has_Been_Exchanged (T)
5239            and then Etype (Get_Associated_Node (N)) /= T
5240          then
5241             --  Only the private declaration was visible in the generic. If
5242             --  the type appears in a subtype declaration, the subtype in the
5243             --  instance must have a view compatible with that of its parent,
5244             --  which must be exchanged (see corresponding code in Restore_
5245             --  Private_Views). Otherwise, if the type is defined in a parent
5246             --  unit, leave full visibility within instance, which is safe.
5247
5248             if In_Open_Scopes (Scope (Base_Type (T)))
5249               and then not Is_Private_Type (Base_Type (T))
5250               and then Comes_From_Source (Base_Type (T))
5251             then
5252                null;
5253
5254             elsif Nkind (Parent (N)) = N_Subtype_Declaration
5255               or else not In_Private_Part (Scope (Base_Type (T)))
5256             then
5257                Prepend_Elmt (T, Exchanged_Views);
5258                Exchange_Declarations (Etype (Get_Associated_Node (N)));
5259             end if;
5260
5261          --  For composite types with inconsistent representation exchange
5262          --  component types accordingly.
5263
5264          elsif Is_Access_Type (T)
5265            and then Is_Private_Type (Designated_Type (T))
5266            and then not Has_Private_View (N)
5267            and then Present (Full_View (Designated_Type (T)))
5268          then
5269             Switch_View (Designated_Type (T));
5270
5271          elsif Is_Array_Type (T) then
5272             if Is_Private_Type (Component_Type (T))
5273               and then not Has_Private_View (N)
5274               and then Present (Full_View (Component_Type (T)))
5275             then
5276                Switch_View (Component_Type (T));
5277             end if;
5278
5279             --  The normal exchange mechanism relies on the setting of a
5280             --  flag on the reference in the generic. However, an additional
5281             --  mechanism is needed for types that are not explicitly mentioned
5282             --  in the generic, but may be needed in expanded code in the
5283             --  instance. This includes component types of arrays and
5284             --  designated types of access types. This processing must also
5285             --  include the index types of arrays which we take care of here.
5286
5287             declare
5288                Indx : Node_Id;
5289                Typ  : Entity_Id;
5290
5291             begin
5292                Indx := First_Index (T);
5293                Typ  := Base_Type (Etype (Indx));
5294                while Present (Indx) loop
5295                   if Is_Private_Type (Typ)
5296                     and then Present (Full_View (Typ))
5297                   then
5298                      Switch_View (Typ);
5299                   end if;
5300
5301                   Next_Index (Indx);
5302                end loop;
5303             end;
5304
5305          elsif Is_Private_Type (T)
5306            and then Present (Full_View (T))
5307            and then Is_Array_Type (Full_View (T))
5308            and then Is_Private_Type (Component_Type (Full_View (T)))
5309          then
5310             Switch_View (T);
5311
5312          --  Finally, a non-private subtype may have a private base type, which
5313          --  must be exchanged for consistency. This can happen when a package
5314          --  body is instantiated, when the scope stack is empty but in fact
5315          --  the subtype and the base type are declared in an enclosing scope.
5316
5317          --  Note that in this case we introduce an inconsistency in the view
5318          --  set, because we switch the base type BT, but there could be some
5319          --  private dependent subtypes of BT which remain unswitched. Such
5320          --  subtypes might need to be switched at a later point (see specific
5321          --  provision for that case in Switch_View).
5322
5323          elsif not Is_Private_Type (T)
5324            and then not Has_Private_View (N)
5325            and then Is_Private_Type (BT)
5326            and then Present (Full_View (BT))
5327            and then not Is_Generic_Type (BT)
5328            and then not In_Open_Scopes (BT)
5329          then
5330             Prepend_Elmt (Full_View (BT), Exchanged_Views);
5331             Exchange_Declarations (BT);
5332          end if;
5333       end if;
5334    end Check_Private_View;
5335
5336    --------------------------
5337    -- Contains_Instance_Of --
5338    --------------------------
5339
5340    function Contains_Instance_Of
5341      (Inner : Entity_Id;
5342       Outer : Entity_Id;
5343       N     : Node_Id) return Boolean
5344    is
5345       Elmt : Elmt_Id;
5346       Scop : Entity_Id;
5347
5348    begin
5349       Scop := Outer;
5350
5351       --  Verify that there are no circular instantiations. We check whether
5352       --  the unit contains an instance of the current scope or some enclosing
5353       --  scope (in case one of the instances appears in a subunit). Longer
5354       --  circularities involving subunits might seem too pathological to
5355       --  consider, but they were not too pathological for the authors of
5356       --  DEC bc30vsq, so we loop over all enclosing scopes, and mark all
5357       --  enclosing generic scopes as containing an instance.
5358
5359       loop
5360          --  Within a generic subprogram body, the scope is not generic, to
5361          --  allow for recursive subprograms. Use the declaration to determine
5362          --  whether this is a generic unit.
5363
5364          if Ekind (Scop) = E_Generic_Package
5365            or else (Is_Subprogram (Scop)
5366                       and then Nkind (Unit_Declaration_Node (Scop)) =
5367                                         N_Generic_Subprogram_Declaration)
5368          then
5369             Elmt := First_Elmt (Inner_Instances (Inner));
5370
5371             while Present (Elmt) loop
5372                if Node (Elmt) = Scop then
5373                   Error_Msg_Node_2 := Inner;
5374                   Error_Msg_NE
5375                     ("circular Instantiation: & instantiated within &!",
5376                        N, Scop);
5377                   return True;
5378
5379                elsif Node (Elmt) = Inner then
5380                   return True;
5381
5382                elsif Contains_Instance_Of (Node (Elmt), Scop, N) then
5383                   Error_Msg_Node_2 := Inner;
5384                   Error_Msg_NE
5385                     ("circular Instantiation: & instantiated within &!",
5386                       N, Node (Elmt));
5387                   return True;
5388                end if;
5389
5390                Next_Elmt (Elmt);
5391             end loop;
5392
5393             --  Indicate that Inner is being instantiated within Scop
5394
5395             Append_Elmt (Inner, Inner_Instances (Scop));
5396          end if;
5397
5398          if Scop = Standard_Standard then
5399             exit;
5400          else
5401             Scop := Scope (Scop);
5402          end if;
5403       end loop;
5404
5405       return False;
5406    end Contains_Instance_Of;
5407
5408    -----------------------
5409    -- Copy_Generic_Node --
5410    -----------------------
5411
5412    function Copy_Generic_Node
5413      (N             : Node_Id;
5414       Parent_Id     : Node_Id;
5415       Instantiating : Boolean) return Node_Id
5416    is
5417       Ent   : Entity_Id;
5418       New_N : Node_Id;
5419
5420       function Copy_Generic_Descendant (D : Union_Id) return Union_Id;
5421       --  Check the given value of one of the Fields referenced by the
5422       --  current node to determine whether to copy it recursively. The
5423       --  field may hold a Node_Id, a List_Id, or an Elist_Id, or a plain
5424       --  value (Sloc, Uint, Char) in which case it need not be copied.
5425
5426       procedure Copy_Descendants;
5427       --  Common utility for various nodes
5428
5429       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id;
5430       --  Make copy of element list
5431
5432       function Copy_Generic_List
5433         (L         : List_Id;
5434          Parent_Id : Node_Id) return List_Id;
5435       --  Apply Copy_Node recursively to the members of a node list
5436
5437       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean;
5438       --  True if an identifier is part of the defining program unit name
5439       --  of a child unit. The entity of such an identifier must be kept
5440       --  (for ASIS use) even though as the name of an enclosing generic
5441       --   it would otherwise not be preserved in the generic tree.
5442
5443       ----------------------
5444       -- Copy_Descendants --
5445       ----------------------
5446
5447       procedure Copy_Descendants is
5448
5449          use Atree.Unchecked_Access;
5450          --  This code section is part of the implementation of an untyped
5451          --  tree traversal, so it needs direct access to node fields.
5452
5453       begin
5454          Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
5455          Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
5456          Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
5457          Set_Field4 (New_N, Copy_Generic_Descendant (Field4 (N)));
5458          Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
5459       end Copy_Descendants;
5460
5461       -----------------------------
5462       -- Copy_Generic_Descendant --
5463       -----------------------------
5464
5465       function Copy_Generic_Descendant (D : Union_Id) return Union_Id is
5466       begin
5467          if D = Union_Id (Empty) then
5468             return D;
5469
5470          elsif D in Node_Range then
5471             return Union_Id
5472               (Copy_Generic_Node (Node_Id (D), New_N, Instantiating));
5473
5474          elsif D in List_Range then
5475             return Union_Id (Copy_Generic_List (List_Id (D), New_N));
5476
5477          elsif D in Elist_Range then
5478             return Union_Id (Copy_Generic_Elist (Elist_Id (D)));
5479
5480          --  Nothing else is copyable (e.g. Uint values), return as is
5481
5482          else
5483             return D;
5484          end if;
5485       end Copy_Generic_Descendant;
5486
5487       ------------------------
5488       -- Copy_Generic_Elist --
5489       ------------------------
5490
5491       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id is
5492          M : Elmt_Id;
5493          L : Elist_Id;
5494
5495       begin
5496          if Present (E) then
5497             L := New_Elmt_List;
5498             M := First_Elmt (E);
5499             while Present (M) loop
5500                Append_Elmt
5501                  (Copy_Generic_Node (Node (M), Empty, Instantiating), L);
5502                Next_Elmt (M);
5503             end loop;
5504
5505             return L;
5506
5507          else
5508             return No_Elist;
5509          end if;
5510       end Copy_Generic_Elist;
5511
5512       -----------------------
5513       -- Copy_Generic_List --
5514       -----------------------
5515
5516       function Copy_Generic_List
5517         (L         : List_Id;
5518          Parent_Id : Node_Id) return List_Id
5519       is
5520          N     : Node_Id;
5521          New_L : List_Id;
5522
5523       begin
5524          if Present (L) then
5525             New_L := New_List;
5526             Set_Parent (New_L, Parent_Id);
5527
5528             N := First (L);
5529             while Present (N) loop
5530                Append (Copy_Generic_Node (N, Empty, Instantiating), New_L);
5531                Next (N);
5532             end loop;
5533
5534             return New_L;
5535
5536          else
5537             return No_List;
5538          end if;
5539       end Copy_Generic_List;
5540
5541       ---------------------------
5542       -- In_Defining_Unit_Name --
5543       ---------------------------
5544
5545       function In_Defining_Unit_Name (Nam : Node_Id) return Boolean is
5546       begin
5547          return Present (Parent (Nam))
5548            and then (Nkind (Parent (Nam)) = N_Defining_Program_Unit_Name
5549                       or else
5550                         (Nkind (Parent (Nam)) = N_Expanded_Name
5551                           and then In_Defining_Unit_Name (Parent (Nam))));
5552       end In_Defining_Unit_Name;
5553
5554    --  Start of processing for Copy_Generic_Node
5555
5556    begin
5557       if N = Empty then
5558          return N;
5559       end if;
5560
5561       New_N := New_Copy (N);
5562
5563       if Instantiating then
5564          Adjust_Instantiation_Sloc (New_N, S_Adjustment);
5565       end if;
5566
5567       if not Is_List_Member (N) then
5568          Set_Parent (New_N, Parent_Id);
5569       end if;
5570
5571       --  If defining identifier, then all fields have been copied already
5572
5573       if Nkind (New_N) in N_Entity then
5574          null;
5575
5576       --  Special casing for identifiers and other entity names and operators
5577
5578       elsif     Nkind (New_N) = N_Identifier
5579         or else Nkind (New_N) = N_Character_Literal
5580         or else Nkind (New_N) = N_Expanded_Name
5581         or else Nkind (New_N) = N_Operator_Symbol
5582         or else Nkind (New_N) in N_Op
5583       then
5584          if not Instantiating then
5585
5586             --  Link both nodes in order to assign subsequently the
5587             --  entity of the copy to the original node, in case this
5588             --  is a global reference.
5589
5590             Set_Associated_Node (N, New_N);
5591
5592             --  If we are within an instantiation, this is a nested generic
5593             --  that has already been analyzed at the point of definition. We
5594             --  must preserve references that were global to the enclosing
5595             --  parent at that point. Other occurrences, whether global or
5596             --  local to the current generic, must be resolved anew, so we
5597             --  reset the entity in the generic copy. A global reference has a
5598             --  smaller depth than the parent, or else the same depth in case
5599             --  both are distinct compilation units.
5600
5601             --  It is also possible for Current_Instantiated_Parent to be
5602             --  defined, and for this not to be a nested generic, namely if the
5603             --  unit is loaded through Rtsfind. In that case, the entity of
5604             --  New_N is only a link to the associated node, and not a defining
5605             --  occurrence.
5606
5607             --  The entities for parent units in the defining_program_unit of a
5608             --  generic child unit are established when the context of the unit
5609             --  is first analyzed, before the generic copy is made. They are
5610             --  preserved in the copy for use in ASIS queries.
5611
5612             Ent := Entity (New_N);
5613
5614             if No (Current_Instantiated_Parent.Gen_Id) then
5615                if No (Ent)
5616                  or else Nkind (Ent) /= N_Defining_Identifier
5617                  or else not In_Defining_Unit_Name (N)
5618                then
5619                   Set_Associated_Node (New_N, Empty);
5620                end if;
5621
5622             elsif No (Ent)
5623               or else
5624                 not (Nkind (Ent) = N_Defining_Identifier
5625                        or else
5626                      Nkind (Ent) = N_Defining_Character_Literal
5627                        or else
5628                      Nkind (Ent) = N_Defining_Operator_Symbol)
5629               or else No (Scope (Ent))
5630               or else Scope (Ent) = Current_Instantiated_Parent.Gen_Id
5631               or else (Scope_Depth (Scope (Ent)) >
5632                              Scope_Depth (Current_Instantiated_Parent.Gen_Id)
5633                          and then
5634                        Get_Source_Unit (Ent) =
5635                        Get_Source_Unit (Current_Instantiated_Parent.Gen_Id))
5636             then
5637                Set_Associated_Node (New_N, Empty);
5638             end if;
5639
5640          --  Case of instantiating identifier or some other name or operator
5641
5642          else
5643             --  If the associated node is still defined, the entity in it is
5644             --  global, and must be copied to the instance. If this copy is
5645             --  being made for a body to inline, it is applied to an
5646             --  instantiated tree, and the entity is already present and must
5647             --  be also preserved.
5648
5649             declare
5650                Assoc : constant Node_Id := Get_Associated_Node (N);
5651             begin
5652                if Present (Assoc) then
5653                   if Nkind (Assoc) = Nkind (N) then
5654                      Set_Entity (New_N, Entity (Assoc));
5655                      Check_Private_View (N);
5656
5657                   elsif Nkind (Assoc) = N_Function_Call then
5658                      Set_Entity (New_N, Entity (Name (Assoc)));
5659
5660                   elsif (Nkind (Assoc) = N_Defining_Identifier
5661                           or else Nkind (Assoc) = N_Defining_Character_Literal
5662                           or else Nkind (Assoc) = N_Defining_Operator_Symbol)
5663                     and then Expander_Active
5664                   then
5665                      --  Inlining case: we are copying a tree that contains
5666                      --  global entities, which are preserved in the copy to be
5667                      --  used for subsequent inlining.
5668
5669                      null;
5670
5671                   else
5672                      Set_Entity (New_N, Empty);
5673                   end if;
5674                end if;
5675             end;
5676          end if;
5677
5678          --  For expanded name, we must copy the Prefix and Selector_Name
5679
5680          if Nkind (N) = N_Expanded_Name then
5681             Set_Prefix
5682               (New_N, Copy_Generic_Node (Prefix (N), New_N, Instantiating));
5683
5684             Set_Selector_Name (New_N,
5685               Copy_Generic_Node (Selector_Name (N), New_N, Instantiating));
5686
5687          --  For operators, we must copy the right operand
5688
5689          elsif Nkind (N) in N_Op then
5690             Set_Right_Opnd (New_N,
5691               Copy_Generic_Node (Right_Opnd (N), New_N, Instantiating));
5692
5693             --  And for binary operators, the left operand as well
5694
5695             if Nkind (N) in N_Binary_Op then
5696                Set_Left_Opnd (New_N,
5697                  Copy_Generic_Node (Left_Opnd (N), New_N, Instantiating));
5698             end if;
5699          end if;
5700
5701       --  Special casing for stubs
5702
5703       elsif Nkind (N) in N_Body_Stub then
5704
5705          --  In any case, we must copy the specification or defining
5706          --  identifier as appropriate.
5707
5708          if Nkind (N) = N_Subprogram_Body_Stub then
5709             Set_Specification (New_N,
5710               Copy_Generic_Node (Specification (N), New_N, Instantiating));
5711
5712          else
5713             Set_Defining_Identifier (New_N,
5714               Copy_Generic_Node
5715                 (Defining_Identifier (N), New_N, Instantiating));
5716          end if;
5717
5718          --  If we are not instantiating, then this is where we load and
5719          --  analyze subunits, i.e. at the point where the stub occurs. A
5720          --  more permissivle system might defer this analysis to the point
5721          --  of instantiation, but this seems to complicated for now.
5722
5723          if not Instantiating then
5724             declare
5725                Subunit_Name : constant Unit_Name_Type := Get_Unit_Name (N);
5726                Subunit      : Node_Id;
5727                Unum         : Unit_Number_Type;
5728                New_Body     : Node_Id;
5729
5730             begin
5731                Unum :=
5732                  Load_Unit
5733                    (Load_Name  => Subunit_Name,
5734                     Required   => False,
5735                     Subunit    => True,
5736                     Error_Node => N);
5737
5738                --  If the proper body is not found, a warning message will be
5739                --  emitted when analyzing the stub, or later at the the point
5740                --  of instantiation. Here we just leave the stub as is.
5741
5742                if Unum = No_Unit then
5743                   Subunits_Missing := True;
5744                   goto Subunit_Not_Found;
5745                end if;
5746
5747                Subunit := Cunit (Unum);
5748
5749                if Nkind (Unit (Subunit)) /= N_Subunit then
5750                   Error_Msg_Sloc := Sloc (N);
5751                   Error_Msg_N
5752                     ("expected SEPARATE subunit to complete stub at#,"
5753                        & " found child unit", Subunit);
5754                   goto Subunit_Not_Found;
5755                end if;
5756
5757                --  We must create a generic copy of the subunit, in order to
5758                --  perform semantic analysis on it, and we must replace the
5759                --  stub in the original generic unit with the subunit, in order
5760                --  to preserve non-local references within.
5761
5762                --  Only the proper body needs to be copied. Library_Unit and
5763                --  context clause are simply inherited by the generic copy.
5764                --  Note that the copy (which may be recursive if there are
5765                --  nested subunits) must be done first, before attaching it to
5766                --  the enclosing generic.
5767
5768                New_Body :=
5769                  Copy_Generic_Node
5770                    (Proper_Body (Unit (Subunit)),
5771                     Empty, Instantiating => False);
5772
5773                --  Now place the original proper body in the original generic
5774                --  unit. This is a body, not a compilation unit.
5775
5776                Rewrite (N, Proper_Body (Unit (Subunit)));
5777                Set_Is_Compilation_Unit (Defining_Entity (N), False);
5778                Set_Was_Originally_Stub (N);
5779
5780                --  Finally replace the body of the subunit with its copy, and
5781                --  make this new subunit into the library unit of the generic
5782                --  copy, which does not have stubs any longer.
5783
5784                Set_Proper_Body (Unit (Subunit), New_Body);
5785                Set_Library_Unit (New_N, Subunit);
5786                Inherit_Context (Unit (Subunit), N);
5787             end;
5788
5789          --  If we are instantiating, this must be an error case, since
5790          --  otherwise we would have replaced the stub node by the proper body
5791          --  that corresponds. So just ignore it in the copy (i.e. we have
5792          --  copied it, and that is good enough).
5793
5794          else
5795             null;
5796          end if;
5797
5798          <<Subunit_Not_Found>> null;
5799
5800       --  If the node is a compilation unit, it is the subunit of a stub, which
5801       --  has been loaded already (see code below). In this case, the library
5802       --  unit field of N points to the parent unit (which is a compilation
5803       --  unit) and need not (and cannot!) be copied.
5804
5805       --  When the proper body of the stub is analyzed, thie library_unit link
5806       --  is used to establish the proper context (see sem_ch10).
5807
5808       --  The other fields of a compilation unit are copied as usual
5809
5810       elsif Nkind (N) = N_Compilation_Unit then
5811
5812          --  This code can only be executed when not instantiating, because in
5813          --  the copy made for an instantiation, the compilation unit node has
5814          --  disappeared at the point that a stub is replaced by its proper
5815          --  body.
5816
5817          pragma Assert (not Instantiating);
5818
5819          Set_Context_Items (New_N,
5820            Copy_Generic_List (Context_Items (N), New_N));
5821
5822          Set_Unit (New_N,
5823            Copy_Generic_Node (Unit (N), New_N, False));
5824
5825          Set_First_Inlined_Subprogram (New_N,
5826            Copy_Generic_Node
5827              (First_Inlined_Subprogram (N), New_N, False));
5828
5829          Set_Aux_Decls_Node (New_N,
5830            Copy_Generic_Node (Aux_Decls_Node (N), New_N, False));
5831
5832       --  For an assignment node, the assignment is known to be semantically
5833       --  legal if we are instantiating the template. This avoids incorrect
5834       --  diagnostics in generated code.
5835
5836       elsif Nkind (N) = N_Assignment_Statement then
5837
5838          --  Copy name and expression fields in usual manner
5839
5840          Set_Name (New_N,
5841            Copy_Generic_Node (Name (N), New_N, Instantiating));
5842
5843          Set_Expression (New_N,
5844            Copy_Generic_Node (Expression (N), New_N, Instantiating));
5845
5846          if Instantiating then
5847             Set_Assignment_OK (Name (New_N), True);
5848          end if;
5849
5850       elsif Nkind (N) = N_Aggregate
5851               or else Nkind (N) = N_Extension_Aggregate
5852       then
5853
5854          if not Instantiating then
5855             Set_Associated_Node (N, New_N);
5856
5857          else
5858             if Present (Get_Associated_Node (N))
5859               and then Nkind (Get_Associated_Node (N)) = Nkind (N)
5860             then
5861                --  In the generic the aggregate has some composite type. If at
5862                --  the point of instantiation the type has a private view,
5863                --  install the full view (and that of its ancestors, if any).
5864
5865                declare
5866                   T   : Entity_Id := (Etype (Get_Associated_Node (New_N)));
5867                   Rt  : Entity_Id;
5868
5869                begin
5870                   if Present (T)
5871                     and then Is_Private_Type (T)
5872                   then
5873                      Switch_View (T);
5874                   end if;
5875
5876                   if Present (T)
5877                     and then Is_Tagged_Type (T)
5878                     and then Is_Derived_Type (T)
5879                   then
5880                      Rt := Root_Type (T);
5881
5882                      loop
5883                         T := Etype (T);
5884
5885                         if Is_Private_Type (T) then
5886                            Switch_View (T);
5887                         end if;
5888
5889                         exit when T = Rt;
5890                      end loop;
5891                   end if;
5892                end;
5893             end if;
5894          end if;
5895
5896          --  Do not copy the associated node, which points to
5897          --  the generic copy of the aggregate.
5898
5899          declare
5900             use Atree.Unchecked_Access;
5901             --  This code section is part of the implementation of an untyped
5902             --  tree traversal, so it needs direct access to node fields.
5903
5904          begin
5905             Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
5906             Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
5907             Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
5908             Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
5909          end;
5910
5911       --  Allocators do not have an identifier denoting the access type,
5912       --  so we must locate it through the expression to check whether
5913       --  the views are consistent.
5914
5915       elsif Nkind (N) = N_Allocator
5916         and then Nkind (Expression (N)) = N_Qualified_Expression
5917         and then Is_Entity_Name (Subtype_Mark (Expression (N)))
5918         and then Instantiating
5919       then
5920          declare
5921             T     : constant Node_Id :=
5922                       Get_Associated_Node (Subtype_Mark (Expression (N)));
5923             Acc_T : Entity_Id;
5924
5925          begin
5926             if Present (T) then
5927
5928                --  Retrieve the allocator node in the generic copy
5929
5930                Acc_T := Etype (Parent (Parent (T)));
5931                if Present (Acc_T)
5932                  and then Is_Private_Type (Acc_T)
5933                then
5934                   Switch_View (Acc_T);
5935                end if;
5936             end if;
5937
5938             Copy_Descendants;
5939          end;
5940
5941       --  For a proper body, we must catch the case of a proper body that
5942       --  replaces a stub. This represents the point at which a separate
5943       --  compilation unit, and hence template file, may be referenced, so we
5944       --  must make a new source instantiation entry for the template of the
5945       --  subunit, and ensure that all nodes in the subunit are adjusted using
5946       --  this new source instantiation entry.
5947
5948       elsif Nkind (N) in N_Proper_Body then
5949          declare
5950             Save_Adjustment : constant Sloc_Adjustment := S_Adjustment;
5951
5952          begin
5953             if Instantiating and then Was_Originally_Stub (N) then
5954                Create_Instantiation_Source
5955                  (Instantiation_Node,
5956                   Defining_Entity (N),
5957                   False,
5958                   S_Adjustment);
5959             end if;
5960
5961             --  Now copy the fields of the proper body, using the new
5962             --  adjustment factor if one was needed as per test above.
5963
5964             Copy_Descendants;
5965
5966             --  Restore the original adjustment factor in case changed
5967
5968             S_Adjustment := Save_Adjustment;
5969          end;
5970
5971       --  Don't copy Ident or Comment pragmas, since the comment belongs to the
5972       --  generic unit, not to the instantiating unit.
5973
5974       elsif Nkind (N) = N_Pragma
5975         and then Instantiating
5976       then
5977          declare
5978             Prag_Id : constant Pragma_Id := Get_Pragma_Id (Chars (N));
5979
5980          begin
5981             if Prag_Id = Pragma_Ident
5982               or else Prag_Id = Pragma_Comment
5983             then
5984                New_N := Make_Null_Statement (Sloc (N));
5985
5986             else
5987                Copy_Descendants;
5988             end if;
5989          end;
5990
5991       elsif Nkind (N) = N_Integer_Literal
5992         or else Nkind (N) = N_Real_Literal
5993         or else Nkind (N) = N_String_Literal
5994       then
5995          --  No descendant fields need traversing
5996
5997          null;
5998
5999       --  For the remaining nodes, copy recursively their descendants
6000
6001       else
6002          Copy_Descendants;
6003
6004          if Instantiating
6005            and then Nkind (N) = N_Subprogram_Body
6006          then
6007             Set_Generic_Parent (Specification (New_N), N);
6008          end if;
6009       end if;
6010
6011       return New_N;
6012    end Copy_Generic_Node;
6013
6014    ----------------------------
6015    -- Denotes_Formal_Package --
6016    ----------------------------
6017
6018    function Denotes_Formal_Package
6019      (Pack    : Entity_Id;
6020       On_Exit : Boolean := False) return Boolean
6021    is
6022       Par  : Entity_Id;
6023       Scop : constant Entity_Id := Scope (Pack);
6024       E    : Entity_Id;
6025
6026    begin
6027       if On_Exit then
6028          Par :=
6029            Instance_Envs.Table
6030              (Instance_Envs.Last).Instantiated_Parent.Act_Id;
6031       else
6032          Par  := Current_Instantiated_Parent.Act_Id;
6033       end if;
6034
6035       if Ekind (Scop) = E_Generic_Package
6036         or else Nkind (Unit_Declaration_Node (Scop)) =
6037                                          N_Generic_Subprogram_Declaration
6038       then
6039          return True;
6040
6041       elsif Nkind (Original_Node (Unit_Declaration_Node (Pack))) =
6042         N_Formal_Package_Declaration
6043       then
6044          return True;
6045
6046       elsif No (Par) then
6047          return False;
6048
6049       else
6050          --  Check whether this package is associated with a formal package of
6051          --  the enclosing instantiation. Iterate over the list of renamings.
6052
6053          E := First_Entity (Par);
6054          while Present (E) loop
6055             if Ekind (E) /= E_Package
6056               or else Nkind (Parent (E)) /= N_Package_Renaming_Declaration
6057             then
6058                null;
6059
6060             elsif Renamed_Object (E) = Par then
6061                return False;
6062
6063             elsif Renamed_Object (E) = Pack then
6064                return True;
6065             end if;
6066
6067             Next_Entity (E);
6068          end loop;
6069
6070          return False;
6071       end if;
6072    end Denotes_Formal_Package;
6073
6074    -----------------
6075    -- End_Generic --
6076    -----------------
6077
6078    procedure End_Generic is
6079    begin
6080       --  ??? More things could be factored out in this routine. Should
6081       --  probably be done at a later stage.
6082
6083       Inside_A_Generic := Generic_Flags.Table (Generic_Flags.Last);
6084       Generic_Flags.Decrement_Last;
6085
6086       Expander_Mode_Restore;
6087    end End_Generic;
6088
6089    ----------------------
6090    -- Find_Actual_Type --
6091    ----------------------
6092
6093    function Find_Actual_Type
6094      (Typ       : Entity_Id;
6095       Gen_Scope : Entity_Id) return Entity_Id
6096    is
6097       T : Entity_Id;
6098
6099    begin
6100       if not Is_Child_Unit (Gen_Scope) then
6101          return Get_Instance_Of (Typ);
6102
6103       elsif not Is_Generic_Type (Typ)
6104         or else Scope (Typ) = Gen_Scope
6105       then
6106          return Get_Instance_Of (Typ);
6107
6108       else
6109          T := Current_Entity (Typ);
6110          while Present (T) loop
6111             if In_Open_Scopes (Scope (T)) then
6112                return T;
6113
6114             elsif Is_Generic_Actual_Type (T) then
6115                return T;
6116             end if;
6117
6118             T := Homonym (T);
6119          end loop;
6120
6121          return Typ;
6122       end if;
6123    end Find_Actual_Type;
6124
6125    ----------------------------
6126    -- Freeze_Subprogram_Body --
6127    ----------------------------
6128
6129    procedure Freeze_Subprogram_Body
6130      (Inst_Node : Node_Id;
6131       Gen_Body  : Node_Id;
6132       Pack_Id   : Entity_Id)
6133   is
6134       F_Node   : Node_Id;
6135       Gen_Unit : constant Entity_Id := Get_Generic_Entity (Inst_Node);
6136       Par      : constant Entity_Id := Scope (Gen_Unit);
6137       Enc_G    : Entity_Id;
6138       Enc_I    : Node_Id;
6139       E_G_Id   : Entity_Id;
6140
6141       function Earlier (N1, N2 : Node_Id) return Boolean;
6142       --  Yields True if N1 and N2 appear in the same compilation unit,
6143       --  ignoring subunits, and if N1 is to the left of N2 in a left-to-right
6144       --  traversal of the tree for the unit.
6145
6146       function Enclosing_Body (N : Node_Id) return Node_Id;
6147       --  Find innermost package body that encloses the given node, and which
6148       --  is not a compilation unit. Freeze nodes for the instance, or for its
6149       --  enclosing body, may be inserted after the enclosing_body of the
6150       --  generic unit.
6151
6152       function Package_Freeze_Node (B : Node_Id) return Node_Id;
6153       --  Find entity for given package body, and locate or create a freeze
6154       --  node for it.
6155
6156       function True_Parent (N : Node_Id) return Node_Id;
6157       --  For a subunit, return parent of corresponding stub
6158
6159       -------------
6160       -- Earlier --
6161       -------------
6162
6163       function Earlier (N1, N2 : Node_Id) return Boolean is
6164          D1 : Integer := 0;
6165          D2 : Integer := 0;
6166          P1 : Node_Id := N1;
6167          P2 : Node_Id := N2;
6168
6169          procedure Find_Depth (P : in out Node_Id; D : in out Integer);
6170          --  Find distance from given node to enclosing compilation unit
6171
6172          ----------------
6173          -- Find_Depth --
6174          ----------------
6175
6176          procedure Find_Depth (P : in out Node_Id; D : in out Integer) is
6177          begin
6178             while Present (P)
6179               and then Nkind (P) /= N_Compilation_Unit
6180             loop
6181                P := True_Parent (P);
6182                D := D + 1;
6183             end loop;
6184          end Find_Depth;
6185
6186       --  Start of procesing for Earlier
6187
6188       begin
6189          Find_Depth (P1, D1);
6190          Find_Depth (P2, D2);
6191
6192          if P1 /= P2 then
6193             return False;
6194          else
6195             P1 := N1;
6196             P2 := N2;
6197          end if;
6198
6199          while D1 > D2 loop
6200             P1 := True_Parent (P1);
6201             D1 := D1 - 1;
6202          end loop;
6203
6204          while D2 > D1 loop
6205             P2 := True_Parent (P2);
6206             D2 := D2 - 1;
6207          end loop;
6208
6209          --  At this point P1 and P2 are at the same distance from the root.
6210          --  We examine their parents until we find a common declarative
6211          --  list, at which point we can establish their relative placement
6212          --  by comparing their ultimate slocs. If we reach the root,
6213          --  N1 and N2 do not descend from the same declarative list (e.g.
6214          --  one is nested in the declarative part and the other is in a block
6215          --  in the statement part) and the earlier one is already frozen.
6216
6217          while not Is_List_Member (P1)
6218            or else not Is_List_Member (P2)
6219            or else List_Containing (P1) /= List_Containing (P2)
6220          loop
6221             P1 := True_Parent (P1);
6222             P2 := True_Parent (P2);
6223
6224             if Nkind (Parent (P1)) = N_Subunit then
6225                P1 := Corresponding_Stub (Parent (P1));
6226             end if;
6227
6228             if Nkind (Parent (P2)) = N_Subunit then
6229                P2 := Corresponding_Stub (Parent (P2));
6230             end if;
6231
6232             if P1 = P2 then
6233                return False;
6234             end if;
6235          end loop;
6236
6237          return
6238            Top_Level_Location (Sloc (P1)) < Top_Level_Location (Sloc (P2));
6239       end Earlier;
6240
6241       --------------------
6242       -- Enclosing_Body --
6243       --------------------
6244
6245       function Enclosing_Body (N : Node_Id) return Node_Id is
6246          P : Node_Id := Parent (N);
6247
6248       begin
6249          while Present (P)
6250            and then Nkind (Parent (P)) /= N_Compilation_Unit
6251          loop
6252             if Nkind (P) = N_Package_Body then
6253
6254                if Nkind (Parent (P)) = N_Subunit then
6255                   return Corresponding_Stub (Parent (P));
6256                else
6257                   return P;
6258                end if;
6259             end if;
6260
6261             P := True_Parent (P);
6262          end loop;
6263
6264          return Empty;
6265       end Enclosing_Body;
6266
6267       -------------------------
6268       -- Package_Freeze_Node --
6269       -------------------------
6270
6271       function Package_Freeze_Node (B : Node_Id) return Node_Id is
6272          Id : Entity_Id;
6273
6274       begin
6275          if Nkind (B) = N_Package_Body then
6276             Id := Corresponding_Spec (B);
6277
6278          else pragma Assert (Nkind (B) = N_Package_Body_Stub);
6279             Id := Corresponding_Spec (Proper_Body (Unit (Library_Unit (B))));
6280          end if;
6281
6282          Ensure_Freeze_Node (Id);
6283          return Freeze_Node (Id);
6284       end Package_Freeze_Node;
6285
6286       -----------------
6287       -- True_Parent --
6288       -----------------
6289
6290       function True_Parent (N : Node_Id) return Node_Id is
6291       begin
6292          if Nkind (Parent (N)) = N_Subunit then
6293             return Parent (Corresponding_Stub (Parent (N)));
6294          else
6295             return Parent (N);
6296          end if;
6297       end True_Parent;
6298
6299    --  Start of processing of Freeze_Subprogram_Body
6300
6301    begin
6302       --  If the instance and the generic body appear within the same unit, and
6303       --  the instance preceeds the generic, the freeze node for the instance
6304       --  must appear after that of the generic. If the generic is nested
6305       --  within another instance I2, then current instance must be frozen
6306       --  after I2. In both cases, the freeze nodes are those of enclosing
6307       --  packages. Otherwise, the freeze node is placed at the end of the
6308       --  current declarative part.
6309
6310       Enc_G  := Enclosing_Body (Gen_Body);
6311       Enc_I  := Enclosing_Body (Inst_Node);
6312       Ensure_Freeze_Node (Pack_Id);
6313       F_Node := Freeze_Node (Pack_Id);
6314
6315       if Is_Generic_Instance (Par)
6316         and then Present (Freeze_Node (Par))
6317         and then
6318           In_Same_Declarative_Part (Freeze_Node (Par), Inst_Node)
6319       then
6320          if ABE_Is_Certain (Get_Package_Instantiation_Node (Par)) then
6321
6322             --  The parent was a premature instantiation. Insert freeze node at
6323             --  the end the current declarative part.
6324
6325             Insert_After_Last_Decl (Inst_Node, F_Node);
6326
6327          else
6328             Insert_After (Freeze_Node (Par), F_Node);
6329          end if;
6330
6331       --  The body enclosing the instance should be frozen after the body that
6332       --  includes the generic, because the body of the instance may make
6333       --  references to entities therein. If the two are not in the same
6334       --  declarative part, or if the one enclosing the instance is frozen
6335       --  already, freeze the instance at the end of the current declarative
6336       --  part.
6337
6338       elsif Is_Generic_Instance (Par)
6339         and then Present (Freeze_Node (Par))
6340         and then Present (Enc_I)
6341       then
6342          if In_Same_Declarative_Part (Freeze_Node (Par), Enc_I)
6343            or else
6344              (Nkind (Enc_I) = N_Package_Body
6345                and then
6346              In_Same_Declarative_Part (Freeze_Node (Par), Parent (Enc_I)))
6347          then
6348             --  The enclosing package may contain several instances. Rather
6349             --  than computing the earliest point at which to insert its
6350             --  freeze node, we place it at the end of the declarative part
6351             --  of the parent of the generic.
6352
6353             Insert_After_Last_Decl
6354               (Freeze_Node (Par), Package_Freeze_Node (Enc_I));
6355          end if;
6356
6357          Insert_After_Last_Decl (Inst_Node, F_Node);
6358
6359       elsif Present (Enc_G)
6360         and then Present (Enc_I)
6361         and then Enc_G /= Enc_I
6362         and then Earlier (Inst_Node, Gen_Body)
6363       then
6364          if Nkind (Enc_G) = N_Package_Body then
6365             E_G_Id := Corresponding_Spec (Enc_G);
6366          else pragma Assert (Nkind (Enc_G) = N_Package_Body_Stub);
6367             E_G_Id :=
6368               Corresponding_Spec (Proper_Body (Unit (Library_Unit (Enc_G))));
6369          end if;
6370
6371          --  Freeze package that encloses instance, and place node after
6372          --  package that encloses generic. If enclosing package is already
6373          --  frozen we have to assume it is at the proper place. This may be
6374          --  a potential ABE that requires dynamic checking.
6375
6376          Insert_After_Last_Decl (Enc_G, Package_Freeze_Node (Enc_I));
6377
6378          --  Freeze enclosing subunit before instance
6379
6380          Ensure_Freeze_Node (E_G_Id);
6381
6382          if not Is_List_Member (Freeze_Node (E_G_Id)) then
6383             Insert_After (Enc_G, Freeze_Node (E_G_Id));
6384          end if;
6385
6386          Insert_After_Last_Decl (Inst_Node, F_Node);
6387
6388       else
6389          --  If none of the above, insert freeze node at the end of the current
6390          --  declarative part.
6391
6392          Insert_After_Last_Decl (Inst_Node, F_Node);
6393       end if;
6394    end Freeze_Subprogram_Body;
6395
6396    ----------------
6397    -- Get_Gen_Id --
6398    ----------------
6399
6400    function Get_Gen_Id (E : Assoc_Ptr) return Entity_Id is
6401    begin
6402       return Generic_Renamings.Table (E).Gen_Id;
6403    end Get_Gen_Id;
6404
6405    ---------------------
6406    -- Get_Instance_Of --
6407    ---------------------
6408
6409    function Get_Instance_Of (A : Entity_Id) return Entity_Id is
6410       Res : constant Assoc_Ptr := Generic_Renamings_HTable.Get (A);
6411
6412    begin
6413       if Res /= Assoc_Null then
6414          return Generic_Renamings.Table (Res).Act_Id;
6415       else
6416          --  On exit, entity is not instantiated: not a generic parameter, or
6417          --  else parameter of an inner generic unit.
6418
6419          return A;
6420       end if;
6421    end Get_Instance_Of;
6422
6423    ------------------------------------
6424    -- Get_Package_Instantiation_Node --
6425    ------------------------------------
6426
6427    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id is
6428       Decl : Node_Id := Unit_Declaration_Node (A);
6429       Inst : Node_Id;
6430
6431    begin
6432       --  If the Package_Instantiation attribute has been set on the package
6433       --  entity, then use it directly when it (or its Original_Node) refers
6434       --  to an N_Package_Instantiation node. In principle it should be
6435       --  possible to have this field set in all cases, which should be
6436       --  investigated, and would allow this function to be significantly
6437       --  simplified. ???
6438
6439       if Present (Package_Instantiation (A)) then
6440          if Nkind (Package_Instantiation (A)) = N_Package_Instantiation then
6441             return Package_Instantiation (A);
6442
6443          elsif Nkind (Original_Node (Package_Instantiation (A)))
6444                  = N_Package_Instantiation
6445          then
6446             return Original_Node (Package_Instantiation (A));
6447          end if;
6448       end if;
6449
6450       --  If the instantiation is a compilation unit that does not need body
6451       --  then the instantiation node has been rewritten as a package
6452       --  declaration for the instance, and we return the original node.
6453
6454       --  If it is a compilation unit and the instance node has not been
6455       --  rewritten, then it is still the unit of the compilation. Finally, if
6456       --  a body is present, this is a parent of the main unit whose body has
6457       --  been compiled for inlining purposes, and the instantiation node has
6458       --  been rewritten with the instance body.
6459
6460       --  Otherwise the instantiation node appears after the declaration. If
6461       --  the entity is a formal package, the declaration may have been
6462       --  rewritten as a generic declaration (in the case of a formal with box)
6463       --  or left as a formal package declaration if it has actuals, and is
6464       --  found with a forward search.
6465
6466       if Nkind (Parent (Decl)) = N_Compilation_Unit then
6467          if Nkind (Decl) = N_Package_Declaration
6468            and then Present (Corresponding_Body (Decl))
6469          then
6470             Decl := Unit_Declaration_Node (Corresponding_Body (Decl));
6471          end if;
6472
6473          if Nkind (Original_Node (Decl)) = N_Package_Instantiation then
6474             return Original_Node (Decl);
6475          else
6476             return Unit (Parent (Decl));
6477          end if;
6478
6479       elsif Nkind (Decl) = N_Package_Declaration
6480         and then Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration
6481       then
6482          return Original_Node (Decl);
6483
6484       else
6485          Inst := Next (Decl);
6486          while Nkind (Inst) /= N_Package_Instantiation
6487            and then Nkind (Inst) /= N_Formal_Package_Declaration
6488          loop
6489             Next (Inst);
6490          end loop;
6491
6492          return Inst;
6493       end if;
6494    end Get_Package_Instantiation_Node;
6495
6496    ------------------------
6497    -- Has_Been_Exchanged --
6498    ------------------------
6499
6500    function Has_Been_Exchanged (E : Entity_Id) return Boolean is
6501       Next : Elmt_Id;
6502
6503    begin
6504       Next := First_Elmt (Exchanged_Views);
6505       while Present (Next) loop
6506          if Full_View (Node (Next)) = E then
6507             return True;
6508          end if;
6509
6510          Next_Elmt (Next);
6511       end loop;
6512
6513       return False;
6514    end Has_Been_Exchanged;
6515
6516    ----------
6517    -- Hash --
6518    ----------
6519
6520    function Hash (F : Entity_Id) return HTable_Range is
6521    begin
6522       return HTable_Range (F mod HTable_Size);
6523    end Hash;
6524
6525    ------------------------
6526    -- Hide_Current_Scope --
6527    ------------------------
6528
6529    procedure Hide_Current_Scope is
6530       C : constant Entity_Id := Current_Scope;
6531       E : Entity_Id;
6532
6533    begin
6534       Set_Is_Hidden_Open_Scope (C);
6535
6536       E := First_Entity (C);
6537       while Present (E) loop
6538          if Is_Immediately_Visible (E) then
6539             Set_Is_Immediately_Visible (E, False);
6540             Append_Elmt (E, Hidden_Entities);
6541          end if;
6542
6543          Next_Entity (E);
6544       end loop;
6545
6546       --  Make the scope name invisible as well. This is necessary, but might
6547       --  conflict with calls to Rtsfind later on, in case the scope is a
6548       --  predefined one. There is no clean solution to this problem, so for
6549       --  now we depend on the user not redefining Standard itself in one of
6550       --  the parent units.
6551
6552       if Is_Immediately_Visible (C)
6553         and then C /= Standard_Standard
6554       then
6555          Set_Is_Immediately_Visible (C, False);
6556          Append_Elmt (C, Hidden_Entities);
6557       end if;
6558
6559    end Hide_Current_Scope;
6560
6561    --------------
6562    -- Init_Env --
6563    --------------
6564
6565    procedure Init_Env is
6566       Saved : Instance_Env;
6567
6568    begin
6569       Saved.Instantiated_Parent  := Current_Instantiated_Parent;
6570       Saved.Exchanged_Views      := Exchanged_Views;
6571       Saved.Hidden_Entities      := Hidden_Entities;
6572       Saved.Current_Sem_Unit     := Current_Sem_Unit;
6573       Saved.Parent_Unit_Visible  := Parent_Unit_Visible;
6574       Saved.Instance_Parent_Unit := Instance_Parent_Unit;
6575
6576       --  Save configuration switches. These may be reset if the unit is a
6577       --  predefined unit, and the current mode is not Ada 2005.
6578
6579       Save_Opt_Config_Switches (Saved.Switches);
6580
6581       Instance_Envs.Increment_Last;
6582       Instance_Envs.Table (Instance_Envs.Last) := Saved;
6583
6584       Exchanged_Views := New_Elmt_List;
6585       Hidden_Entities := New_Elmt_List;
6586
6587       --  Make dummy entry for Instantiated parent. If generic unit is legal,
6588       --  this is set properly in Set_Instance_Env.
6589
6590       Current_Instantiated_Parent :=
6591         (Current_Scope, Current_Scope, Assoc_Null);
6592    end Init_Env;
6593
6594    ------------------------------
6595    -- In_Same_Declarative_Part --
6596    ------------------------------
6597
6598    function In_Same_Declarative_Part
6599      (F_Node : Node_Id;
6600       Inst   : Node_Id) return Boolean
6601    is
6602       Decls : constant Node_Id := Parent (F_Node);
6603       Nod   : Node_Id := Parent (Inst);
6604
6605    begin
6606       while Present (Nod) loop
6607          if Nod = Decls then
6608             return True;
6609
6610          elsif Nkind (Nod) = N_Subprogram_Body
6611            or else Nkind (Nod) = N_Package_Body
6612            or else Nkind (Nod) = N_Task_Body
6613            or else Nkind (Nod) = N_Protected_Body
6614            or else Nkind (Nod) = N_Block_Statement
6615          then
6616             return False;
6617
6618          elsif Nkind (Nod) = N_Subunit then
6619             Nod :=  Corresponding_Stub (Nod);
6620
6621          elsif Nkind (Nod) = N_Compilation_Unit then
6622             return False;
6623          else
6624             Nod := Parent (Nod);
6625          end if;
6626       end loop;
6627
6628       return False;
6629    end In_Same_Declarative_Part;
6630
6631    ---------------------
6632    -- In_Main_Context --
6633    ---------------------
6634
6635    function In_Main_Context (E : Entity_Id) return Boolean is
6636       Context : List_Id;
6637       Clause  : Node_Id;
6638       Nam     : Node_Id;
6639
6640    begin
6641       if not Is_Compilation_Unit (E)
6642         or else Ekind (E) /= E_Package
6643         or else In_Private_Part (E)
6644       then
6645          return False;
6646       end if;
6647
6648       Context := Context_Items (Cunit (Main_Unit));
6649
6650       Clause  := First (Context);
6651       while Present (Clause) loop
6652          if Nkind (Clause) = N_With_Clause then
6653             Nam := Name (Clause);
6654
6655             --  If the current scope is part of the context of the main unit,
6656             --  analysis of the corresponding with_clause is not complete, and
6657             --  the entity is not set. We use the Chars field directly, which
6658             --  might produce false positives in rare cases, but guarantees
6659             --  that we produce all the instance bodies we will need.
6660
6661             if (Nkind (Nam) = N_Identifier
6662                  and then Chars (Nam) = Chars (E))
6663               or else (Nkind (Nam) = N_Selected_Component
6664                         and then Chars (Selector_Name (Nam)) = Chars (E))
6665             then
6666                return True;
6667             end if;
6668          end if;
6669
6670          Next (Clause);
6671       end loop;
6672
6673       return False;
6674    end In_Main_Context;
6675
6676    ---------------------
6677    -- Inherit_Context --
6678    ---------------------
6679
6680    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id) is
6681       Current_Context : List_Id;
6682       Current_Unit    : Node_Id;
6683       Item            : Node_Id;
6684       New_I           : Node_Id;
6685
6686    begin
6687       if Nkind (Parent (Gen_Decl)) = N_Compilation_Unit then
6688
6689          --  The inherited context is attached to the enclosing compilation
6690          --  unit. This is either the main unit, or the declaration for the
6691          --  main unit (in case the instantation appears within the package
6692          --  declaration and the main unit is its body).
6693
6694          Current_Unit := Parent (Inst);
6695          while Present (Current_Unit)
6696            and then Nkind (Current_Unit) /= N_Compilation_Unit
6697          loop
6698             Current_Unit := Parent (Current_Unit);
6699          end loop;
6700
6701          Current_Context := Context_Items (Current_Unit);
6702
6703          Item := First (Context_Items (Parent (Gen_Decl)));
6704          while Present (Item) loop
6705             if Nkind (Item) = N_With_Clause then
6706                New_I := New_Copy (Item);
6707                Set_Implicit_With (New_I, True);
6708                Append (New_I, Current_Context);
6709             end if;
6710
6711             Next (Item);
6712          end loop;
6713       end if;
6714    end Inherit_Context;
6715
6716    ----------------
6717    -- Initialize --
6718    ----------------
6719
6720    procedure Initialize is
6721    begin
6722       Generic_Renamings.Init;
6723       Instance_Envs.Init;
6724       Generic_Flags.Init;
6725       Generic_Renamings_HTable.Reset;
6726       Circularity_Detected := False;
6727       Exchanged_Views      := No_Elist;
6728       Hidden_Entities      := No_Elist;
6729    end Initialize;
6730
6731    ----------------------------
6732    -- Insert_After_Last_Decl --
6733    ----------------------------
6734
6735    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id) is
6736       L : List_Id          := List_Containing (N);
6737       P : constant Node_Id := Parent (L);
6738
6739    begin
6740       if not Is_List_Member (F_Node) then
6741          if Nkind (P) = N_Package_Specification
6742            and then L = Visible_Declarations (P)
6743            and then Present (Private_Declarations (P))
6744            and then not Is_Empty_List (Private_Declarations (P))
6745          then
6746             L := Private_Declarations (P);
6747          end if;
6748
6749          Insert_After (Last (L), F_Node);
6750       end if;
6751    end Insert_After_Last_Decl;
6752
6753    ------------------
6754    -- Install_Body --
6755    ------------------
6756
6757    procedure Install_Body
6758      (Act_Body : Node_Id;
6759       N        : Node_Id;
6760       Gen_Body : Node_Id;
6761       Gen_Decl : Node_Id)
6762    is
6763       Act_Id    : constant Entity_Id := Corresponding_Spec (Act_Body);
6764       Act_Unit  : constant Node_Id   := Unit (Cunit (Get_Source_Unit (N)));
6765       Gen_Id    : constant Entity_Id := Corresponding_Spec (Gen_Body);
6766       Par       : constant Entity_Id := Scope (Gen_Id);
6767       Gen_Unit  : constant Node_Id   :=
6768                     Unit (Cunit (Get_Source_Unit (Gen_Decl)));
6769       Orig_Body : Node_Id := Gen_Body;
6770       F_Node    : Node_Id;
6771       Body_Unit : Node_Id;
6772
6773       Must_Delay : Boolean;
6774
6775       function Enclosing_Subp (Id : Entity_Id) return Entity_Id;
6776       --  Find subprogram (if any) that encloses instance and/or generic body
6777
6778       function True_Sloc (N : Node_Id) return Source_Ptr;
6779       --  If the instance is nested inside a generic unit, the Sloc of the
6780       --  instance indicates the place of the original definition, not the
6781       --  point of the current enclosing instance. Pending a better usage of
6782       --  Slocs to indicate instantiation places, we determine the place of
6783       --  origin of a node by finding the maximum sloc of any ancestor node.
6784       --  Why is this not equivalent to Top_Level_Location ???
6785
6786       --------------------
6787       -- Enclosing_Subp --
6788       --------------------
6789
6790       function Enclosing_Subp (Id : Entity_Id) return Entity_Id is
6791          Scop : Entity_Id := Scope (Id);
6792
6793       begin
6794          while Scop /= Standard_Standard
6795            and then not Is_Overloadable (Scop)
6796          loop
6797             Scop := Scope (Scop);
6798          end loop;
6799
6800          return Scop;
6801       end Enclosing_Subp;
6802
6803       ---------------
6804       -- True_Sloc --
6805       ---------------
6806
6807       function True_Sloc (N : Node_Id) return Source_Ptr is
6808          Res : Source_Ptr;
6809          N1  : Node_Id;
6810
6811       begin
6812          Res := Sloc (N);
6813          N1 := N;
6814          while Present (N1) and then N1 /= Act_Unit loop
6815             if Sloc (N1) > Res then
6816                Res := Sloc (N1);
6817             end if;
6818
6819             N1 := Parent (N1);
6820          end loop;
6821
6822          return Res;
6823       end True_Sloc;
6824
6825    --  Start of processing for Install_Body
6826
6827    begin
6828       --  If the body is a subunit, the freeze point is the corresponding
6829       --  stub in the current compilation, not the subunit itself.
6830
6831       if Nkind (Parent (Gen_Body)) = N_Subunit then
6832          Orig_Body :=  Corresponding_Stub (Parent (Gen_Body));
6833       else
6834          Orig_Body := Gen_Body;
6835       end if;
6836
6837       Body_Unit := Unit (Cunit (Get_Source_Unit (Orig_Body)));
6838
6839       --  If the instantiation and the generic definition appear in the same
6840       --  package declaration, this is an early instantiation. If they appear
6841       --  in the same declarative part, it is an early instantiation only if
6842       --  the generic body appears textually later, and the generic body is
6843       --  also in the main unit.
6844
6845       --  If instance is nested within a subprogram, and the generic body is
6846       --  not, the instance is delayed because the enclosing body is. If
6847       --  instance and body are within the same scope, or the same sub-
6848       --  program body, indicate explicitly that the instance is delayed.
6849
6850       Must_Delay :=
6851         (Gen_Unit = Act_Unit
6852           and then ((Nkind (Gen_Unit) = N_Package_Declaration)
6853                       or else Nkind (Gen_Unit) = N_Generic_Package_Declaration
6854                       or else (Gen_Unit = Body_Unit
6855                                 and then True_Sloc (N) < Sloc (Orig_Body)))
6856           and then Is_In_Main_Unit (Gen_Unit)
6857           and then (Scope (Act_Id) = Scope (Gen_Id)
6858                       or else
6859                     Enclosing_Subp (Act_Id) = Enclosing_Subp (Gen_Id)));
6860
6861       --  If this is an early instantiation, the freeze node is placed after
6862       --  the generic body. Otherwise, if the generic appears in an instance,
6863       --  we cannot freeze the current instance until the outer one is frozen.
6864       --  This is only relevant if the current instance is nested within some
6865       --  inner scope not itself within the outer instance. If this scope is
6866       --  a package body in the same declarative part as the outer instance,
6867       --  then that body needs to be frozen after the outer instance. Finally,
6868       --  if no delay is needed, we place the freeze node at the end of the
6869       --  current declarative part.
6870
6871       if Expander_Active then
6872          Ensure_Freeze_Node (Act_Id);
6873          F_Node := Freeze_Node (Act_Id);
6874
6875          if Must_Delay then
6876             Insert_After (Orig_Body, F_Node);
6877
6878          elsif Is_Generic_Instance (Par)
6879            and then Present (Freeze_Node (Par))
6880            and then Scope (Act_Id) /= Par
6881          then
6882             --  Freeze instance of inner generic after instance of enclosing
6883             --  generic.
6884
6885             if In_Same_Declarative_Part (Freeze_Node (Par), N) then
6886                Insert_After (Freeze_Node (Par), F_Node);
6887
6888             --  Freeze package enclosing instance of inner generic after
6889             --  instance of enclosing generic.
6890
6891             elsif Nkind (Parent (N)) = N_Package_Body
6892               and then In_Same_Declarative_Part (Freeze_Node (Par), Parent (N))
6893             then
6894
6895                declare
6896                   Enclosing : constant Entity_Id :=
6897                                 Corresponding_Spec (Parent (N));
6898
6899                begin
6900                   Insert_After_Last_Decl (N, F_Node);
6901                   Ensure_Freeze_Node (Enclosing);
6902
6903                   if not Is_List_Member (Freeze_Node (Enclosing)) then
6904                      Insert_After (Freeze_Node (Par), Freeze_Node (Enclosing));
6905                   end if;
6906                end;
6907
6908             else
6909                Insert_After_Last_Decl (N, F_Node);
6910             end if;
6911
6912          else
6913             Insert_After_Last_Decl (N, F_Node);
6914          end if;
6915       end if;
6916
6917       Set_Is_Frozen (Act_Id);
6918       Insert_Before (N, Act_Body);
6919       Mark_Rewrite_Insertion (Act_Body);
6920    end Install_Body;
6921
6922    -----------------------------
6923    -- Install_Formal_Packages --
6924    -----------------------------
6925
6926    procedure Install_Formal_Packages (Par : Entity_Id) is
6927       E : Entity_Id;
6928
6929    begin
6930       E := First_Entity (Par);
6931       while Present (E) loop
6932          if Ekind (E) = E_Package
6933            and then Nkind (Parent (E)) = N_Package_Renaming_Declaration
6934          then
6935             --  If this is the renaming for the parent instance, done
6936
6937             if Renamed_Object (E) = Par then
6938                exit;
6939
6940             --  The visibility of a formal of an enclosing generic is
6941             --  already correct.
6942
6943             elsif Denotes_Formal_Package (E) then
6944                null;
6945
6946             elsif Present (Associated_Formal_Package (E))
6947               and then Box_Present (Parent (Associated_Formal_Package (E)))
6948             then
6949                Check_Generic_Actuals (Renamed_Object (E), True);
6950                Set_Is_Hidden (E, False);
6951             end if;
6952          end if;
6953
6954          Next_Entity (E);
6955       end loop;
6956    end Install_Formal_Packages;
6957
6958    --------------------
6959    -- Install_Parent --
6960    --------------------
6961
6962    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False) is
6963       Ancestors : constant Elist_Id  := New_Elmt_List;
6964       S         : constant Entity_Id := Current_Scope;
6965       Inst_Par  : Entity_Id;
6966       First_Par : Entity_Id;
6967       Inst_Node : Node_Id;
6968       Gen_Par   : Entity_Id;
6969       First_Gen : Entity_Id;
6970       Elmt      : Elmt_Id;
6971
6972       procedure Install_Noninstance_Specs (Par : Entity_Id);
6973       --  Install the scopes of noninstance parent units ending with Par
6974
6975       procedure Install_Spec (Par : Entity_Id);
6976       --  The child unit is within the declarative part of the parent, so
6977       --  the declarations within the parent are immediately visible.
6978
6979       -------------------------------
6980       -- Install_Noninstance_Specs --
6981       -------------------------------
6982
6983       procedure Install_Noninstance_Specs (Par : Entity_Id) is
6984       begin
6985          if Present (Par)
6986            and then Par /= Standard_Standard
6987            and then not In_Open_Scopes (Par)
6988          then
6989             Install_Noninstance_Specs (Scope (Par));
6990             Install_Spec (Par);
6991          end if;
6992       end Install_Noninstance_Specs;
6993
6994       ------------------
6995       -- Install_Spec --
6996       ------------------
6997
6998       procedure Install_Spec (Par : Entity_Id) is
6999          Spec : constant Node_Id :=
7000                   Specification (Unit_Declaration_Node (Par));
7001
7002       begin
7003          --  If this parent of the child instance is a top-level unit,
7004          --  then record the unit and its visibility for later resetting
7005          --  in Remove_Parent. We exclude units that are generic instances,
7006          --  as we only want to record this information for the ultimate
7007          --  top-level noninstance parent (is that always correct???).
7008
7009          if Scope (Par) = Standard_Standard
7010            and then not Is_Generic_Instance (Par)
7011          then
7012             Parent_Unit_Visible := Is_Immediately_Visible (Par);
7013             Instance_Parent_Unit := Par;
7014          end if;
7015
7016          --  Open the parent scope and make it and its declarations visible.
7017          --  If this point is not within a body, then only the visible
7018          --  declarations should be made visible, and installation of the
7019          --  private declarations is deferred until the appropriate point
7020          --  within analysis of the spec being instantiated (see the handling
7021          --  of parent visibility in Analyze_Package_Specification). This is
7022          --  relaxed in the case where the parent unit is Ada.Tags, to avoid
7023          --  private view problems that occur when compiling instantiations of
7024          --  a generic child of that package (Generic_Dispatching_Constructor).
7025          --  If the instance freezes a tagged type, inlinings of operations
7026          --  from Ada.Tags may need the full view of type Tag. If inlining took
7027          --  proper account of establishing visibility of inlined subprograms'
7028          --  parents then it should be possible to remove this
7029          --  special check. ???
7030
7031          Push_Scope (Par);
7032          Set_Is_Immediately_Visible   (Par);
7033          Install_Visible_Declarations (Par);
7034          Set_Use (Visible_Declarations (Spec));
7035
7036          if In_Body or else Is_RTU (Par, Ada_Tags) then
7037             Install_Private_Declarations (Par);
7038             Set_Use (Private_Declarations (Spec));
7039          end if;
7040       end Install_Spec;
7041
7042    --  Start of processing for Install_Parent
7043
7044    begin
7045       --  We need to install the parent instance to compile the instantiation
7046       --  of the child, but the child instance must appear in the current
7047       --  scope. Given that we cannot place the parent above the current scope
7048       --  in the scope stack, we duplicate the current scope and unstack both
7049       --  after the instantiation is complete.
7050
7051       --  If the parent is itself the instantiation of a child unit, we must
7052       --  also stack the instantiation of its parent, and so on. Each such
7053       --  ancestor is the prefix of the name in a prior instantiation.
7054
7055       --  If this is a nested instance, the parent unit itself resolves to
7056       --  a renaming of the parent instance, whose declaration we need.
7057
7058       --  Finally, the parent may be a generic (not an instance) when the
7059       --  child unit appears as a formal package.
7060
7061       Inst_Par := P;
7062
7063       if Present (Renamed_Entity (Inst_Par)) then
7064          Inst_Par := Renamed_Entity (Inst_Par);
7065       end if;
7066
7067       First_Par := Inst_Par;
7068
7069       Gen_Par :=
7070         Generic_Parent (Specification (Unit_Declaration_Node (Inst_Par)));
7071
7072       First_Gen := Gen_Par;
7073
7074       while Present (Gen_Par)
7075         and then Is_Child_Unit (Gen_Par)
7076       loop
7077          --  Load grandparent instance as well
7078
7079          Inst_Node := Get_Package_Instantiation_Node (Inst_Par);
7080
7081          if Nkind (Name (Inst_Node)) = N_Expanded_Name then
7082             Inst_Par := Entity (Prefix (Name (Inst_Node)));
7083
7084             if Present (Renamed_Entity (Inst_Par)) then
7085                Inst_Par := Renamed_Entity (Inst_Par);
7086             end if;
7087
7088             Gen_Par :=
7089               Generic_Parent
7090                 (Specification (Unit_Declaration_Node (Inst_Par)));
7091
7092             if Present (Gen_Par) then
7093                Prepend_Elmt (Inst_Par, Ancestors);
7094
7095             else
7096                --  Parent is not the name of an instantiation
7097
7098                Install_Noninstance_Specs (Inst_Par);
7099
7100                exit;
7101             end if;
7102
7103          else
7104             --  Previous error
7105
7106             exit;
7107          end if;
7108       end loop;
7109
7110       if Present (First_Gen) then
7111          Append_Elmt (First_Par, Ancestors);
7112
7113       else
7114          Install_Noninstance_Specs (First_Par);
7115       end if;
7116
7117       if not Is_Empty_Elmt_List (Ancestors) then
7118          Elmt := First_Elmt (Ancestors);
7119
7120          while Present (Elmt) loop
7121             Install_Spec (Node (Elmt));
7122             Install_Formal_Packages (Node (Elmt));
7123
7124             Next_Elmt (Elmt);
7125          end loop;
7126       end if;
7127
7128       if not In_Body then
7129          Push_Scope (S);
7130       end if;
7131    end Install_Parent;
7132
7133    --------------------------------
7134    -- Instantiate_Formal_Package --
7135    --------------------------------
7136
7137    function Instantiate_Formal_Package
7138      (Formal          : Node_Id;
7139       Actual          : Node_Id;
7140       Analyzed_Formal : Node_Id) return List_Id
7141    is
7142       Loc         : constant Source_Ptr := Sloc (Actual);
7143       Actual_Pack : Entity_Id;
7144       Formal_Pack : Entity_Id;
7145       Gen_Parent  : Entity_Id;
7146       Decls       : List_Id;
7147       Nod         : Node_Id;
7148       Parent_Spec : Node_Id;
7149
7150       procedure Find_Matching_Actual
7151        (F    : Node_Id;
7152         Act  : in out Entity_Id);
7153       --  We need to associate each formal entity in the formal package
7154       --  with the corresponding entity in the actual package. The actual
7155       --  package has been analyzed and possibly expanded, and as a result
7156       --  there is no one-to-one correspondence between the two lists (for
7157       --  example, the actual may include subtypes, itypes, and inherited
7158       --  primitive operations, interspersed among the renaming declarations
7159       --  for the actuals) . We retrieve the corresponding actual by name
7160       --  because each actual has the same name as the formal, and they do
7161       --  appear in the same order.
7162
7163       function Get_Formal_Entity (N : Node_Id) return Entity_Id;
7164       --  Retrieve entity of defining entity of  generic formal parameter.
7165       --  Only the declarations of formals need to be considered when
7166       --  linking them to actuals, but the declarative list may include
7167       --  internal entities generated during analysis, and those are ignored.
7168
7169       procedure Match_Formal_Entity
7170         (Formal_Node : Node_Id;
7171          Formal_Ent  : Entity_Id;
7172          Actual_Ent  : Entity_Id);
7173       --  Associates the formal entity with the actual. In the case
7174       --  where Formal_Ent is a formal package, this procedure iterates
7175       --  through all of its formals and enters associations betwen the
7176       --  actuals occurring in the formal package's corresponding actual
7177       --  package (given by Actual_Ent) and the formal package's formal
7178       --  parameters. This procedure recurses if any of the parameters is
7179       --  itself a package.
7180
7181       function Is_Instance_Of
7182         (Act_Spec : Entity_Id;
7183          Gen_Anc  : Entity_Id) return Boolean;
7184       --  The actual can be an instantiation of a generic within another
7185       --  instance, in which case there is no direct link from it to the
7186       --  original generic ancestor. In that case, we recognize that the
7187       --  ultimate ancestor is the same by examining names and scopes.
7188
7189       procedure Map_Entities (Form : Entity_Id; Act : Entity_Id);
7190       --  Within the generic part, entities in the formal package are
7191       --  visible. To validate subsequent type declarations, indicate
7192       --  the correspondence betwen the entities in the analyzed formal,
7193       --  and the entities in  the actual package. There are three packages
7194       --  involved in the instantiation of a formal package: the parent
7195       --  generic P1 which appears in the generic declaration, the fake
7196       --  instantiation P2 which appears in the analyzed generic, and whose
7197       --  visible entities may be used in subsequent formals, and the actual
7198       --  P3 in the instance. To validate subsequent formals, me indicate
7199       --  that the entities in P2 are mapped into those of P3. The mapping of
7200       --  entities has to be done recursively for nested packages.
7201
7202       procedure Process_Nested_Formal (Formal : Entity_Id);
7203       --  If the current formal is declared with a box, its own formals are
7204       --  visible in the instance, as they were in the generic, and their
7205       --  Hidden flag must be reset. If some of these formals are themselves
7206       --  packages declared with a box, the processing must be recursive.
7207
7208       --------------------------
7209       -- Find_Matching_Actual --
7210       --------------------------
7211
7212       procedure Find_Matching_Actual
7213         (F   : Node_Id;
7214          Act : in out Entity_Id)
7215      is
7216          Formal_Ent : Entity_Id;
7217
7218       begin
7219          case Nkind (Original_Node (F)) is
7220             when N_Formal_Object_Declaration |
7221                  N_Formal_Type_Declaration   =>
7222                Formal_Ent := Defining_Identifier (F);
7223
7224                while Chars (Act) /= Chars (Formal_Ent) loop
7225                   Next_Entity (Act);
7226                end loop;
7227
7228             when N_Formal_Subprogram_Declaration |
7229                  N_Formal_Package_Declaration    |
7230                  N_Package_Declaration           |
7231                  N_Generic_Package_Declaration   =>
7232                Formal_Ent := Defining_Entity (F);
7233
7234                while Chars (Act) /= Chars (Formal_Ent) loop
7235                   Next_Entity (Act);
7236                end loop;
7237
7238             when others =>
7239                raise Program_Error;
7240          end case;
7241       end Find_Matching_Actual;
7242
7243       -------------------------
7244       -- Match_Formal_Entity --
7245       -------------------------
7246
7247       procedure Match_Formal_Entity
7248         (Formal_Node : Node_Id;
7249          Formal_Ent  : Entity_Id;
7250          Actual_Ent  : Entity_Id)
7251       is
7252          Act_Pkg   : Entity_Id;
7253
7254       begin
7255          Set_Instance_Of (Formal_Ent, Actual_Ent);
7256
7257          if Ekind (Actual_Ent) = E_Package then
7258
7259             --  Record associations for each parameter
7260
7261             Act_Pkg := Actual_Ent;
7262
7263             declare
7264                A_Ent  : Entity_Id := First_Entity (Act_Pkg);
7265                F_Ent  : Entity_Id;
7266                F_Node : Node_Id;
7267
7268                Gen_Decl : Node_Id;
7269                Formals  : List_Id;
7270                Actual   : Entity_Id;
7271
7272             begin
7273                --  Retrieve the actual given in the formal package declaration
7274
7275                Actual := Entity (Name (Original_Node (Formal_Node)));
7276
7277                --  The actual in the formal package declaration  may be a
7278                --  renamed generic package, in which case we want to retrieve
7279                --  the original generic in order to traverse its formal part.
7280
7281                if Present (Renamed_Entity (Actual)) then
7282                   Gen_Decl := Unit_Declaration_Node (Renamed_Entity (Actual));
7283                else
7284                   Gen_Decl := Unit_Declaration_Node (Actual);
7285                end if;
7286
7287                Formals := Generic_Formal_Declarations (Gen_Decl);
7288
7289                if Present (Formals) then
7290                   F_Node := First_Non_Pragma (Formals);
7291                else
7292                   F_Node := Empty;
7293                end if;
7294
7295                while Present (A_Ent)
7296                  and then Present (F_Node)
7297                  and then A_Ent /= First_Private_Entity (Act_Pkg)
7298                loop
7299                   F_Ent := Get_Formal_Entity (F_Node);
7300
7301                   if Present (F_Ent) then
7302
7303                      --  This is a formal of the original package. Record
7304                      --  association and recurse.
7305
7306                      Find_Matching_Actual (F_Node, A_Ent);
7307                      Match_Formal_Entity (F_Node, F_Ent, A_Ent);
7308                      Next_Entity (A_Ent);
7309                   end if;
7310
7311                   Next_Non_Pragma (F_Node);
7312                end loop;
7313             end;
7314          end if;
7315       end Match_Formal_Entity;
7316
7317       -----------------------
7318       -- Get_Formal_Entity --
7319       -----------------------
7320
7321       function Get_Formal_Entity (N : Node_Id) return Entity_Id is
7322          Kind : constant Node_Kind := Nkind (Original_Node (N));
7323       begin
7324          case Kind is
7325             when N_Formal_Object_Declaration     =>
7326                return Defining_Identifier (N);
7327
7328             when N_Formal_Type_Declaration       =>
7329                return Defining_Identifier (N);
7330
7331             when N_Formal_Subprogram_Declaration =>
7332                return Defining_Unit_Name (Specification (N));
7333
7334             when N_Formal_Package_Declaration    =>
7335                return Defining_Identifier (Original_Node (N));
7336
7337             when N_Generic_Package_Declaration   =>
7338                return Defining_Identifier (Original_Node (N));
7339
7340             --  All other declarations are introduced by semantic analysis and
7341             --  have no match in the actual.
7342
7343             when others =>
7344                return Empty;
7345          end case;
7346       end Get_Formal_Entity;
7347
7348       --------------------
7349       -- Is_Instance_Of --
7350       --------------------
7351
7352       function Is_Instance_Of
7353         (Act_Spec : Entity_Id;
7354          Gen_Anc  : Entity_Id) return Boolean
7355       is
7356          Gen_Par : constant Entity_Id := Generic_Parent (Act_Spec);
7357
7358       begin
7359          if No (Gen_Par) then
7360             return False;
7361
7362          --  Simplest case: the generic parent of the actual is the formal
7363
7364          elsif Gen_Par = Gen_Anc then
7365             return True;
7366
7367          elsif Chars (Gen_Par) /= Chars (Gen_Anc) then
7368             return False;
7369
7370          --  The actual may be obtained through several instantiations. Its
7371          --  scope must itself be an instance of a generic declared in the
7372          --  same scope as the formal. Any other case is detected above.
7373
7374          elsif not Is_Generic_Instance (Scope (Gen_Par)) then
7375             return False;
7376
7377          else
7378             return Generic_Parent (Parent (Scope (Gen_Par))) = Scope (Gen_Anc);
7379          end if;
7380       end Is_Instance_Of;
7381
7382       ------------------
7383       -- Map_Entities --
7384       ------------------
7385
7386       procedure Map_Entities (Form : Entity_Id; Act : Entity_Id) is
7387          E1 : Entity_Id;
7388          E2 : Entity_Id;
7389
7390       begin
7391          Set_Instance_Of (Form, Act);
7392
7393          --  Traverse formal and actual package to map the corresponding
7394          --  entities. We skip over internal entities that may be generated
7395          --  during semantic analysis, and find the matching entities by
7396          --  name, given that they must appear in the same order.
7397
7398          E1 := First_Entity (Form);
7399          E2 := First_Entity (Act);
7400          while Present (E1)
7401            and then E1 /= First_Private_Entity (Form)
7402          loop
7403             --  Could this test be a single condition???
7404             --  Seems like it could, and isn't FPE (Form) a constant anyway???
7405
7406             if not Is_Internal (E1)
7407               and then Present (Parent (E1))
7408               and then not Is_Class_Wide_Type (E1)
7409               and then not Is_Internal_Name (Chars (E1))
7410             then
7411                while Present (E2)
7412                  and then Chars (E2) /= Chars (E1)
7413                loop
7414                   Next_Entity (E2);
7415                end loop;
7416
7417                if No (E2) then
7418                   exit;
7419                else
7420                   Set_Instance_Of (E1, E2);
7421
7422                   if Is_Type (E1)
7423                     and then Is_Tagged_Type (E2)
7424                   then
7425                      Set_Instance_Of
7426                        (Class_Wide_Type (E1), Class_Wide_Type (E2));
7427                   end if;
7428
7429                   if Ekind (E1) = E_Package
7430                     and then No (Renamed_Object (E1))
7431                   then
7432                      Map_Entities (E1, E2);
7433                   end if;
7434                end if;
7435             end if;
7436
7437             Next_Entity (E1);
7438          end loop;
7439       end Map_Entities;
7440
7441       ---------------------------
7442       -- Process_Nested_Formal --
7443       ---------------------------
7444
7445       procedure Process_Nested_Formal (Formal : Entity_Id) is
7446          Ent : Entity_Id;
7447
7448       begin
7449          if Present (Associated_Formal_Package (Formal))
7450            and then Box_Present (Parent (Associated_Formal_Package (Formal)))
7451          then
7452             Ent := First_Entity (Formal);
7453             while Present (Ent) loop
7454                Set_Is_Hidden (Ent, False);
7455                Set_Is_Visible_Formal (Ent);
7456                Set_Is_Potentially_Use_Visible
7457                  (Ent, Is_Potentially_Use_Visible (Formal));
7458
7459                if Ekind (Ent) = E_Package then
7460                   exit when Renamed_Entity (Ent) = Renamed_Entity (Formal);
7461                   Process_Nested_Formal (Ent);
7462                end if;
7463
7464                Next_Entity (Ent);
7465             end loop;
7466          end if;
7467       end Process_Nested_Formal;
7468
7469    --  Start of processing for Instantiate_Formal_Package
7470
7471    begin
7472       Analyze (Actual);
7473
7474       if not Is_Entity_Name (Actual)
7475         or else  Ekind (Entity (Actual)) /= E_Package
7476       then
7477          Error_Msg_N
7478            ("expect package instance to instantiate formal", Actual);
7479          Abandon_Instantiation (Actual);
7480          raise Program_Error;
7481
7482       else
7483          Actual_Pack := Entity (Actual);
7484          Set_Is_Instantiated (Actual_Pack);
7485
7486          --  The actual may be a renamed package, or an outer generic formal
7487          --  package whose instantiation is converted into a renaming.
7488
7489          if Present (Renamed_Object (Actual_Pack)) then
7490             Actual_Pack := Renamed_Object (Actual_Pack);
7491          end if;
7492
7493          if Nkind (Analyzed_Formal) = N_Formal_Package_Declaration then
7494             Gen_Parent  := Get_Instance_Of (Entity (Name (Analyzed_Formal)));
7495             Formal_Pack := Defining_Identifier (Analyzed_Formal);
7496          else
7497             Gen_Parent :=
7498               Generic_Parent (Specification (Analyzed_Formal));
7499             Formal_Pack :=
7500               Defining_Unit_Name (Specification (Analyzed_Formal));
7501          end if;
7502
7503          if Nkind (Parent (Actual_Pack)) = N_Defining_Program_Unit_Name then
7504             Parent_Spec := Specification (Unit_Declaration_Node (Actual_Pack));
7505          else
7506             Parent_Spec := Parent (Actual_Pack);
7507          end if;
7508
7509          if Gen_Parent = Any_Id then
7510             Error_Msg_N
7511               ("previous error in declaration of formal package", Actual);
7512             Abandon_Instantiation (Actual);
7513
7514          elsif
7515            Is_Instance_Of (Parent_Spec, Get_Instance_Of (Gen_Parent))
7516          then
7517             null;
7518
7519          else
7520             Error_Msg_NE
7521               ("actual parameter must be instance of&", Actual, Gen_Parent);
7522             Abandon_Instantiation (Actual);
7523          end if;
7524
7525          Set_Instance_Of (Defining_Identifier (Formal), Actual_Pack);
7526          Map_Entities (Formal_Pack, Actual_Pack);
7527
7528          Nod :=
7529            Make_Package_Renaming_Declaration (Loc,
7530              Defining_Unit_Name => New_Copy (Defining_Identifier (Formal)),
7531              Name               => New_Reference_To (Actual_Pack, Loc));
7532
7533          Set_Associated_Formal_Package (Defining_Unit_Name (Nod),
7534            Defining_Identifier (Formal));
7535          Decls := New_List (Nod);
7536
7537          --  If the formal F has a box, then the generic declarations are
7538          --  visible in the generic G. In an instance of G, the corresponding
7539          --  entities in the actual for F (which are the actuals for the
7540          --  instantiation of the generic that F denotes) must also be made
7541          --  visible for analysis of the current instance. On exit from the
7542          --  current instance, those entities are made private again. If the
7543          --  actual is currently in use, these entities are also use-visible.
7544
7545          --  The loop through the actual entities also steps through the formal
7546          --  entities and enters associations from formals to actuals into the
7547          --  renaming map. This is necessary to properly handle checking of
7548          --  actual parameter associations for later formals that depend on
7549          --  actuals declared in the formal package.
7550
7551          --  In Ada 2005, partial parametrization requires that we make visible
7552          --  the actuals corresponding to formals that were defaulted in the
7553          --  formal package. There formals are identified because they remain
7554          --  formal generics within the formal package, rather than being
7555          --  renamings of the actuals supplied.
7556
7557          declare
7558             Gen_Decl : constant Node_Id :=
7559                          Unit_Declaration_Node (Gen_Parent);
7560             Formals  : constant List_Id :=
7561                          Generic_Formal_Declarations (Gen_Decl);
7562
7563             Actual_Ent       : Entity_Id;
7564             Actual_Of_Formal : Node_Id;
7565             Formal_Node      : Node_Id;
7566             Formal_Ent       : Entity_Id;
7567
7568          begin
7569             if Present (Formals) then
7570                Formal_Node := First_Non_Pragma (Formals);
7571             else
7572                Formal_Node := Empty;
7573             end if;
7574
7575             Actual_Ent := First_Entity (Actual_Pack);
7576             Actual_Of_Formal :=
7577                First (Visible_Declarations (Specification (Analyzed_Formal)));
7578             while Present (Actual_Ent)
7579               and then Actual_Ent /= First_Private_Entity (Actual_Pack)
7580             loop
7581                if Present (Formal_Node) then
7582                   Formal_Ent := Get_Formal_Entity (Formal_Node);
7583
7584                   if Present (Formal_Ent) then
7585                      Find_Matching_Actual (Formal_Node, Actual_Ent);
7586                      Match_Formal_Entity
7587                        (Formal_Node, Formal_Ent, Actual_Ent);
7588
7589                      --  We iterate at the same time over the actuals of the
7590                      --  local package created for the formal, to determine
7591                      --  which one of the formals of the original generic were
7592                      --  defaulted in the formal. The corresponding actual
7593                      --  entities are visible in the enclosing instance.
7594
7595                      if Box_Present (Formal)
7596                        or else
7597                          (Present (Actual_Of_Formal)
7598                            and then
7599                              Is_Generic_Formal
7600                                (Get_Formal_Entity (Actual_Of_Formal)))
7601                      then
7602                         Set_Is_Hidden (Actual_Ent, False);
7603                         Set_Is_Visible_Formal (Actual_Ent);
7604                         Set_Is_Potentially_Use_Visible
7605                           (Actual_Ent, In_Use (Actual_Pack));
7606
7607                         if Ekind (Actual_Ent) = E_Package then
7608                            Process_Nested_Formal (Actual_Ent);
7609                         end if;
7610
7611                      else
7612                         Set_Is_Hidden (Actual_Ent);
7613                         Set_Is_Potentially_Use_Visible (Actual_Ent, False);
7614                      end if;
7615                   end if;
7616
7617                   Next_Non_Pragma (Formal_Node);
7618                   Next (Actual_Of_Formal);
7619
7620                else
7621                   --  No further formals to match, but the generic part may
7622                   --  contain inherited operation that are not hidden in the
7623                   --  enclosing instance.
7624
7625                   Next_Entity (Actual_Ent);
7626                end if;
7627             end loop;
7628
7629             --  Inherited subprograms generated by formal derived types are
7630             --  also visible if the types are.
7631
7632             Actual_Ent := First_Entity (Actual_Pack);
7633             while Present (Actual_Ent)
7634               and then Actual_Ent /= First_Private_Entity (Actual_Pack)
7635             loop
7636                if Is_Overloadable (Actual_Ent)
7637                  and then
7638                    Nkind (Parent (Actual_Ent)) = N_Subtype_Declaration
7639                  and then
7640                    not Is_Hidden (Defining_Identifier (Parent (Actual_Ent)))
7641                then
7642                   Set_Is_Hidden (Actual_Ent, False);
7643                   Set_Is_Potentially_Use_Visible
7644                     (Actual_Ent, In_Use (Actual_Pack));
7645                end if;
7646
7647                Next_Entity (Actual_Ent);
7648             end loop;
7649          end;
7650
7651          --  If the formal is not declared with a box, reanalyze it as an
7652          --  abbreviated instantiation, to verify the matching rules of 12.7.
7653          --  The actual checks are performed after the generic associations
7654          --  have been analyzed, to guarantee the same visibility for this
7655          --  instantiation and for the actuals.
7656
7657          --  In Ada 2005, the generic associations for the formal can include
7658          --  defaulted parameters. These are ignored during check. This
7659          --  internal instantiation is removed from the tree after conformance
7660          --  checking, because it contains formal declarations for those
7661          --  defaulted parameters, and those should not reach the back-end.
7662
7663          if not Box_Present (Formal) then
7664             declare
7665                I_Pack : constant Entity_Id :=
7666                           Make_Defining_Identifier (Sloc (Actual),
7667                             Chars => New_Internal_Name  ('P'));
7668
7669             begin
7670                Set_Is_Internal (I_Pack);
7671
7672                Append_To (Decls,
7673                  Make_Package_Instantiation (Sloc (Actual),
7674                    Defining_Unit_Name => I_Pack,
7675                    Name =>
7676                      New_Occurrence_Of
7677                        (Get_Instance_Of (Gen_Parent), Sloc (Actual)),
7678                    Generic_Associations =>
7679                      Generic_Associations (Formal)));
7680             end;
7681          end if;
7682
7683          return Decls;
7684       end if;
7685    end Instantiate_Formal_Package;
7686
7687    -----------------------------------
7688    -- Instantiate_Formal_Subprogram --
7689    -----------------------------------
7690
7691    function Instantiate_Formal_Subprogram
7692      (Formal          : Node_Id;
7693       Actual          : Node_Id;
7694       Analyzed_Formal : Node_Id) return Node_Id
7695    is
7696       Loc        : Source_Ptr;
7697       Formal_Sub : constant Entity_Id :=
7698                      Defining_Unit_Name (Specification (Formal));
7699       Analyzed_S : constant Entity_Id :=
7700                      Defining_Unit_Name (Specification (Analyzed_Formal));
7701       Decl_Node  : Node_Id;
7702       Nam        : Node_Id;
7703       New_Spec   : Node_Id;
7704
7705       function From_Parent_Scope (Subp : Entity_Id) return Boolean;
7706       --  If the generic is a child unit, the parent has been installed on the
7707       --  scope stack, but a default subprogram cannot resolve to something on
7708       --  the parent because that parent is not really part of the visible
7709       --  context (it is there to resolve explicit local entities). If the
7710       --  default has resolved in this way, we remove the entity from
7711       --  immediate visibility and analyze the node again to emit an error
7712       --  message or find another visible candidate.
7713
7714       procedure Valid_Actual_Subprogram (Act : Node_Id);
7715       --  Perform legality check and raise exception on failure
7716
7717       -----------------------
7718       -- From_Parent_Scope --
7719       -----------------------
7720
7721       function From_Parent_Scope (Subp : Entity_Id) return Boolean is
7722          Gen_Scope : Node_Id;
7723
7724       begin
7725          Gen_Scope := Scope (Analyzed_S);
7726          while Present (Gen_Scope)
7727            and then  Is_Child_Unit (Gen_Scope)
7728          loop
7729             if Scope (Subp) = Scope (Gen_Scope) then
7730                return True;
7731             end if;
7732
7733             Gen_Scope := Scope (Gen_Scope);
7734          end loop;
7735
7736          return False;
7737       end From_Parent_Scope;
7738
7739       -----------------------------
7740       -- Valid_Actual_Subprogram --
7741       -----------------------------
7742
7743       procedure Valid_Actual_Subprogram (Act : Node_Id) is
7744          Act_E : Entity_Id;
7745
7746       begin
7747          if Is_Entity_Name (Act) then
7748             Act_E := Entity (Act);
7749
7750          elsif Nkind (Act) = N_Selected_Component
7751            and then Is_Entity_Name (Selector_Name (Act))
7752          then
7753             Act_E := Entity (Selector_Name (Act));
7754
7755          else
7756             Act_E := Empty;
7757          end if;
7758
7759          if (Present (Act_E) and then Is_Overloadable (Act_E))
7760            or else Nkind (Act) = N_Attribute_Reference
7761            or else Nkind (Act) = N_Indexed_Component
7762            or else Nkind (Act) = N_Character_Literal
7763            or else Nkind (Act) = N_Explicit_Dereference
7764          then
7765             return;
7766          end if;
7767
7768          Error_Msg_NE
7769            ("expect subprogram or entry name in instantiation of&",
7770             Instantiation_Node, Formal_Sub);
7771          Abandon_Instantiation (Instantiation_Node);
7772
7773       end Valid_Actual_Subprogram;
7774
7775    --  Start of processing for Instantiate_Formal_Subprogram
7776
7777    begin
7778       New_Spec := New_Copy_Tree (Specification (Formal));
7779
7780       --  The tree copy has created the proper instantiation sloc for the
7781       --  new specification. Use this location for all other constructed
7782       --  declarations.
7783
7784       Loc := Sloc (Defining_Unit_Name (New_Spec));
7785
7786       --  Create new entity for the actual (New_Copy_Tree does not)
7787
7788       Set_Defining_Unit_Name
7789         (New_Spec, Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
7790
7791       --  Create new entities for the each of the formals in the
7792       --  specification of the renaming declaration built for the actual.
7793
7794       if Present (Parameter_Specifications (New_Spec)) then
7795          declare
7796             F : Node_Id;
7797          begin
7798             F := First (Parameter_Specifications (New_Spec));
7799             while Present (F) loop
7800                Set_Defining_Identifier (F,
7801                   Make_Defining_Identifier (Loc,
7802                     Chars => Chars (Defining_Identifier (F))));
7803                Next (F);
7804             end loop;
7805          end;
7806       end if;
7807
7808       --  Find entity of actual. If the actual is an attribute reference, it
7809       --  cannot be resolved here (its formal is missing) but is handled
7810       --  instead in Attribute_Renaming. If the actual is overloaded, it is
7811       --  fully resolved subsequently, when the renaming declaration for the
7812       --  formal is analyzed. If it is an explicit dereference, resolve the
7813       --  prefix but not the actual itself, to prevent interpretation as call.
7814
7815       if Present (Actual) then
7816          Loc := Sloc (Actual);
7817          Set_Sloc (New_Spec, Loc);
7818
7819          if Nkind (Actual) = N_Operator_Symbol then
7820             Find_Direct_Name (Actual);
7821
7822          elsif Nkind (Actual) = N_Explicit_Dereference then
7823             Analyze (Prefix (Actual));
7824
7825          elsif Nkind (Actual) /= N_Attribute_Reference then
7826             Analyze (Actual);
7827          end if;
7828
7829          Valid_Actual_Subprogram (Actual);
7830          Nam := Actual;
7831
7832       elsif Present (Default_Name (Formal)) then
7833          if Nkind (Default_Name (Formal)) /= N_Attribute_Reference
7834            and then Nkind (Default_Name (Formal)) /= N_Selected_Component
7835            and then Nkind (Default_Name (Formal)) /= N_Indexed_Component
7836            and then Nkind (Default_Name (Formal)) /= N_Character_Literal
7837            and then Present (Entity (Default_Name (Formal)))
7838          then
7839             Nam := New_Occurrence_Of (Entity (Default_Name (Formal)), Loc);
7840          else
7841             Nam := New_Copy (Default_Name (Formal));
7842             Set_Sloc (Nam, Loc);
7843          end if;
7844
7845       elsif Box_Present (Formal) then
7846
7847          --  Actual is resolved at the point of instantiation. Create an
7848          --  identifier or operator with the same name as the formal.
7849
7850          if Nkind (Formal_Sub) = N_Defining_Operator_Symbol then
7851             Nam := Make_Operator_Symbol (Loc,
7852               Chars =>  Chars (Formal_Sub),
7853               Strval => No_String);
7854          else
7855             Nam := Make_Identifier (Loc, Chars (Formal_Sub));
7856          end if;
7857
7858       elsif Nkind (Specification (Formal)) = N_Procedure_Specification
7859         and then Null_Present (Specification (Formal))
7860       then
7861          --  Generate null body for procedure, for use in the instance
7862
7863          Decl_Node :=
7864            Make_Subprogram_Body (Loc,
7865              Specification              => New_Spec,
7866              Declarations               => New_List,
7867              Handled_Statement_Sequence =>
7868                Make_Handled_Sequence_Of_Statements (Loc,
7869                  Statements => New_List (Make_Null_Statement (Loc))));
7870
7871          Set_Is_Intrinsic_Subprogram (Defining_Unit_Name (New_Spec));
7872          return Decl_Node;
7873
7874       else
7875          Error_Msg_Sloc := Sloc (Scope (Analyzed_S));
7876          Error_Msg_NE
7877            ("missing actual&", Instantiation_Node, Formal_Sub);
7878          Error_Msg_NE
7879            ("\in instantiation of & declared#",
7880               Instantiation_Node, Scope (Analyzed_S));
7881          Abandon_Instantiation (Instantiation_Node);
7882       end if;
7883
7884       Decl_Node :=
7885         Make_Subprogram_Renaming_Declaration (Loc,
7886           Specification => New_Spec,
7887           Name          => Nam);
7888
7889       --  If we do not have an actual and the formal specified <> then set to
7890       --  get proper default.
7891
7892       if No (Actual) and then Box_Present (Formal) then
7893          Set_From_Default (Decl_Node);
7894       end if;
7895
7896       --  Gather possible interpretations for the actual before analyzing the
7897       --  instance. If overloaded, it will be resolved when analyzing the
7898       --  renaming declaration.
7899
7900       if Box_Present (Formal)
7901         and then No (Actual)
7902       then
7903          Analyze (Nam);
7904
7905          if Is_Child_Unit (Scope (Analyzed_S))
7906            and then Present (Entity (Nam))
7907          then
7908             if not Is_Overloaded (Nam) then
7909
7910                if From_Parent_Scope (Entity (Nam)) then
7911                   Set_Is_Immediately_Visible (Entity (Nam), False);
7912                   Set_Entity (Nam, Empty);
7913                   Set_Etype (Nam, Empty);
7914
7915                   Analyze (Nam);
7916
7917                   Set_Is_Immediately_Visible (Entity (Nam));
7918                end if;
7919
7920             else
7921                declare
7922                   I  : Interp_Index;
7923                   It : Interp;
7924
7925                begin
7926                   Get_First_Interp (Nam, I, It);
7927
7928                   while Present (It.Nam) loop
7929                      if From_Parent_Scope (It.Nam) then
7930                         Remove_Interp (I);
7931                      end if;
7932
7933                      Get_Next_Interp (I, It);
7934                   end loop;
7935                end;
7936             end if;
7937          end if;
7938       end if;
7939
7940       --  The generic instantiation freezes the actual. This can only be done
7941       --  once the actual is resolved, in the analysis of the renaming
7942       --  declaration. To make the formal subprogram entity available, we set
7943       --  Corresponding_Formal_Spec to point to the formal subprogram entity.
7944       --  This is also needed in Analyze_Subprogram_Renaming for the processing
7945       --  of formal abstract subprograms.
7946
7947       Set_Corresponding_Formal_Spec (Decl_Node, Analyzed_S);
7948
7949       --  We cannot analyze the renaming declaration, and thus find the actual,
7950       --  until all the actuals are assembled in the instance. For subsequent
7951       --  checks of other actuals, indicate the node that will hold the
7952       --  instance of this formal.
7953
7954       Set_Instance_Of (Analyzed_S, Nam);
7955
7956       if Nkind (Actual) = N_Selected_Component
7957         and then Is_Task_Type (Etype (Prefix (Actual)))
7958         and then not Is_Frozen (Etype (Prefix (Actual)))
7959       then
7960          --  The renaming declaration will create a body, which must appear
7961          --  outside of the instantiation, We move the renaming declaration
7962          --  out of the instance, and create an additional renaming inside,
7963          --  to prevent freezing anomalies.
7964
7965          declare
7966             Anon_Id : constant Entity_Id :=
7967                         Make_Defining_Identifier
7968                           (Loc, New_Internal_Name ('E'));
7969          begin
7970             Set_Defining_Unit_Name (New_Spec, Anon_Id);
7971             Insert_Before (Instantiation_Node, Decl_Node);
7972             Analyze (Decl_Node);
7973
7974             --  Now create renaming within the instance
7975
7976             Decl_Node :=
7977               Make_Subprogram_Renaming_Declaration (Loc,
7978                 Specification => New_Copy_Tree (New_Spec),
7979                 Name => New_Occurrence_Of (Anon_Id, Loc));
7980
7981             Set_Defining_Unit_Name (Specification (Decl_Node),
7982               Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
7983          end;
7984       end if;
7985
7986       return Decl_Node;
7987    end Instantiate_Formal_Subprogram;
7988
7989    ------------------------
7990    -- Instantiate_Object --
7991    ------------------------
7992
7993    function Instantiate_Object
7994      (Formal          : Node_Id;
7995       Actual          : Node_Id;
7996       Analyzed_Formal : Node_Id) return List_Id
7997    is
7998       Acc_Def     : Node_Id             := Empty;
7999       Act_Assoc   : constant Node_Id    := Parent (Actual);
8000       Actual_Decl : Node_Id             := Empty;
8001       Formal_Id   : constant Entity_Id  := Defining_Identifier (Formal);
8002       Decl_Node   : Node_Id;
8003       Def         : Node_Id;
8004       Ftyp        : Entity_Id;
8005       List        : constant List_Id    := New_List;
8006       Loc         : constant Source_Ptr := Sloc (Actual);
8007       Orig_Ftyp   : constant Entity_Id  :=
8008                       Etype (Defining_Identifier (Analyzed_Formal));
8009       Subt_Decl   : Node_Id             := Empty;
8010       Subt_Mark   : Node_Id             := Empty;
8011
8012    begin
8013       if Present (Subtype_Mark (Formal)) then
8014          Subt_Mark := Subtype_Mark (Formal);
8015       else
8016          Check_Access_Definition (Formal);
8017          Acc_Def := Access_Definition (Formal);
8018       end if;
8019
8020       --  Sloc for error message on missing actual
8021
8022       Error_Msg_Sloc := Sloc (Scope (Defining_Identifier (Analyzed_Formal)));
8023
8024       if Get_Instance_Of (Formal_Id) /= Formal_Id then
8025          Error_Msg_N ("duplicate instantiation of generic parameter", Actual);
8026       end if;
8027
8028       Set_Parent (List, Parent (Actual));
8029
8030       --  OUT present
8031
8032       if Out_Present (Formal) then
8033
8034          --  An IN OUT generic actual must be a name. The instantiation is a
8035          --  renaming declaration. The actual is the name being renamed. We
8036          --  use the actual directly, rather than a copy, because it is not
8037          --  used further in the list of actuals, and because a copy or a use
8038          --  of relocate_node is incorrect if the instance is nested within a
8039          --  generic. In order to simplify ASIS searches, the Generic_Parent
8040          --  field links the declaration to the generic association.
8041
8042          if No (Actual) then
8043             Error_Msg_NE
8044               ("missing actual&",
8045                Instantiation_Node, Formal_Id);
8046             Error_Msg_NE
8047               ("\in instantiation of & declared#",
8048                  Instantiation_Node,
8049                    Scope (Defining_Identifier (Analyzed_Formal)));
8050             Abandon_Instantiation (Instantiation_Node);
8051          end if;
8052
8053          if Present (Subt_Mark) then
8054             Decl_Node :=
8055               Make_Object_Renaming_Declaration (Loc,
8056                 Defining_Identifier => New_Copy (Formal_Id),
8057                 Subtype_Mark        => New_Copy_Tree (Subt_Mark),
8058                 Name                => Actual);
8059
8060          else pragma Assert (Present (Acc_Def));
8061             Decl_Node :=
8062               Make_Object_Renaming_Declaration (Loc,
8063                 Defining_Identifier => New_Copy (Formal_Id),
8064                 Access_Definition   => New_Copy_Tree (Acc_Def),
8065                 Name                => Actual);
8066          end if;
8067
8068          Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
8069
8070          --  The analysis of the actual may produce insert_action nodes, so
8071          --  the declaration must have a context in which to attach them.
8072
8073          Append (Decl_Node, List);
8074          Analyze (Actual);
8075
8076          --  Return if the analysis of the actual reported some error
8077
8078          if Etype (Actual) = Any_Type then
8079             return List;
8080          end if;
8081
8082          --  This check is performed here because Analyze_Object_Renaming will
8083          --  not check it when Comes_From_Source is False. Note though that the
8084          --  check for the actual being the name of an object will be performed
8085          --  in Analyze_Object_Renaming.
8086
8087          if Is_Object_Reference (Actual)
8088            and then Is_Dependent_Component_Of_Mutable_Object (Actual)
8089          then
8090             Error_Msg_N
8091               ("illegal discriminant-dependent component for in out parameter",
8092                Actual);
8093          end if;
8094
8095          --  The actual has to be resolved in order to check that it is a
8096          --  variable (due to cases such as F(1), where F returns
8097          --  access to an array, and for overloaded prefixes).
8098
8099          Ftyp :=
8100            Get_Instance_Of (Etype (Defining_Identifier (Analyzed_Formal)));
8101
8102          if Is_Private_Type (Ftyp)
8103            and then not Is_Private_Type (Etype (Actual))
8104            and then (Base_Type (Full_View (Ftyp)) = Base_Type (Etype (Actual))
8105                       or else Base_Type (Etype (Actual)) = Ftyp)
8106          then
8107             --  If the actual has the type of the full view of the formal, or
8108             --  else a non-private subtype of the formal, then the visibility
8109             --  of the formal type has changed. Add to the actuals a subtype
8110             --  declaration that will force the exchange of views in the body
8111             --  of the instance as well.
8112
8113             Subt_Decl :=
8114               Make_Subtype_Declaration (Loc,
8115                  Defining_Identifier =>
8116                    Make_Defining_Identifier (Loc, New_Internal_Name ('P')),
8117                  Subtype_Indication  => New_Occurrence_Of (Ftyp, Loc));
8118
8119             Prepend (Subt_Decl, List);
8120
8121             Prepend_Elmt (Full_View (Ftyp), Exchanged_Views);
8122             Exchange_Declarations (Ftyp);
8123          end if;
8124
8125          Resolve (Actual, Ftyp);
8126
8127          if not Is_Variable (Actual) or else Paren_Count (Actual) > 0 then
8128             Error_Msg_NE
8129               ("actual for& must be a variable", Actual, Formal_Id);
8130
8131          elsif Base_Type (Ftyp) /= Base_Type (Etype (Actual)) then
8132
8133             --  Ada 2005 (AI-423): For a generic formal object of mode in out,
8134             --  the type of the actual shall resolve to a specific anonymous
8135             --  access type.
8136
8137             if Ada_Version < Ada_05
8138               or else
8139                 Ekind (Base_Type (Ftyp)) /=
8140                   E_Anonymous_Access_Type
8141               or else
8142                 Ekind (Base_Type (Etype (Actual))) /=
8143                   E_Anonymous_Access_Type
8144             then
8145                Error_Msg_NE ("type of actual does not match type of&",
8146                              Actual, Formal_Id);
8147             end if;
8148          end if;
8149
8150          Note_Possible_Modification (Actual);
8151
8152          --  Check for instantiation of atomic/volatile actual for
8153          --  non-atomic/volatile formal (RM C.6 (12)).
8154
8155          if Is_Atomic_Object (Actual)
8156            and then not Is_Atomic (Orig_Ftyp)
8157          then
8158             Error_Msg_N
8159               ("cannot instantiate non-atomic formal object " &
8160                "with atomic actual", Actual);
8161
8162          elsif Is_Volatile_Object (Actual)
8163            and then not Is_Volatile (Orig_Ftyp)
8164          then
8165             Error_Msg_N
8166               ("cannot instantiate non-volatile formal object " &
8167                "with volatile actual", Actual);
8168          end if;
8169
8170       --  OUT not present
8171
8172       else
8173          --  The instantiation of a generic formal in-parameter is constant
8174          --  declaration. The actual is the expression for that declaration.
8175
8176          if Present (Actual) then
8177             if Present (Subt_Mark) then
8178                Def := Subt_Mark;
8179             else pragma Assert (Present (Acc_Def));
8180                Def := Acc_Def;
8181             end if;
8182
8183             Decl_Node :=
8184               Make_Object_Declaration (Loc,
8185                 Defining_Identifier => New_Copy (Formal_Id),
8186                 Constant_Present    => True,
8187                 Object_Definition   => New_Copy_Tree (Def),
8188                 Expression          => Actual);
8189
8190             Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
8191
8192             --  A generic formal object of a tagged type is defined to be
8193             --  aliased so the new constant must also be treated as aliased.
8194
8195             if Is_Tagged_Type
8196                  (Etype (Defining_Identifier (Analyzed_Formal)))
8197             then
8198                Set_Aliased_Present (Decl_Node);
8199             end if;
8200
8201             Append (Decl_Node, List);
8202
8203             --  No need to repeat (pre-)analysis of some expression nodes
8204             --  already handled in Pre_Analyze_Actuals.
8205
8206             if Nkind (Actual) /= N_Allocator then
8207                Analyze (Actual);
8208
8209                --  Return if the analysis of the actual reported some error
8210
8211                if Etype (Actual) = Any_Type then
8212                   return List;
8213                end if;
8214             end if;
8215
8216             declare
8217                Typ : constant Entity_Id :=
8218                        Get_Instance_Of
8219                          (Etype (Defining_Identifier (Analyzed_Formal)));
8220
8221             begin
8222                Freeze_Before (Instantiation_Node, Typ);
8223
8224                --  If the actual is an aggregate, perform name resolution on
8225                --  its components (the analysis of an aggregate does not do it)
8226                --  to capture local names that may be hidden if the generic is
8227                --  a child unit.
8228
8229                if Nkind (Actual) = N_Aggregate then
8230                      Pre_Analyze_And_Resolve (Actual, Typ);
8231                end if;
8232
8233                if Is_Limited_Type (Typ)
8234                  and then not OK_For_Limited_Init (Actual)
8235                then
8236                   Error_Msg_N
8237                     ("initialization not allowed for limited types", Actual);
8238                   Explain_Limited_Type (Typ, Actual);
8239                end if;
8240             end;
8241
8242          elsif Present (Default_Expression (Formal)) then
8243
8244             --  Use default to construct declaration
8245
8246             if Present (Subt_Mark) then
8247                Def := Subt_Mark;
8248             else pragma Assert (Present (Acc_Def));
8249                Def := Acc_Def;
8250             end if;
8251
8252             Decl_Node :=
8253               Make_Object_Declaration (Sloc (Formal),
8254                 Defining_Identifier => New_Copy (Formal_Id),
8255                 Constant_Present    => True,
8256                 Object_Definition   => New_Copy (Def),
8257                 Expression          => New_Copy_Tree (Default_Expression
8258                                         (Formal)));
8259
8260             Append (Decl_Node, List);
8261             Set_Analyzed (Expression (Decl_Node), False);
8262
8263          else
8264             Error_Msg_NE
8265               ("missing actual&",
8266                 Instantiation_Node, Formal_Id);
8267             Error_Msg_NE ("\in instantiation of & declared#",
8268               Instantiation_Node,
8269                 Scope (Defining_Identifier (Analyzed_Formal)));
8270
8271             if Is_Scalar_Type
8272                  (Etype (Defining_Identifier (Analyzed_Formal)))
8273             then
8274                --  Create dummy constant declaration so that instance can be
8275                --  analyzed, to minimize cascaded visibility errors.
8276
8277                if Present (Subt_Mark) then
8278                   Def := Subt_Mark;
8279                else pragma Assert (Present (Acc_Def));
8280                   Def := Acc_Def;
8281                end if;
8282
8283                Decl_Node :=
8284                  Make_Object_Declaration (Loc,
8285                    Defining_Identifier => New_Copy (Formal_Id),
8286                    Constant_Present    => True,
8287                    Object_Definition   => New_Copy (Def),
8288                    Expression          =>
8289                       Make_Attribute_Reference (Sloc (Formal_Id),
8290                         Attribute_Name => Name_First,
8291                         Prefix         => New_Copy (Def)));
8292
8293                Append (Decl_Node, List);
8294
8295             else
8296                Abandon_Instantiation (Instantiation_Node);
8297             end if;
8298          end if;
8299       end if;
8300
8301       if Nkind (Actual) in N_Has_Entity then
8302          Actual_Decl := Parent (Entity (Actual));
8303       end if;
8304
8305       --  Ada 2005 (AI-423): For a formal object declaration with a null
8306       --  exclusion or an access definition that has a null exclusion: If the
8307       --  actual matching the formal object declaration denotes a generic
8308       --  formal object of another generic unit G, and the instantiation
8309       --  containing the actual occurs within the body of G or within the body
8310       --  of a generic unit declared within the declarative region of G, then
8311       --  the declaration of the formal object of G must have a null exclusion.
8312       --  Otherwise, the subtype of the actual matching the formal object
8313       --  declaration shall exclude null.
8314
8315       if Ada_Version >= Ada_05
8316         and then Present (Actual_Decl)
8317         and then
8318           (Nkind (Actual_Decl) = N_Formal_Object_Declaration
8319              or else Nkind (Actual_Decl) = N_Object_Declaration)
8320         and then Nkind (Analyzed_Formal) = N_Formal_Object_Declaration
8321         and then Has_Null_Exclusion (Actual_Decl)
8322         and then not Has_Null_Exclusion (Analyzed_Formal)
8323       then
8324          Error_Msg_Sloc := Sloc (Actual_Decl);
8325          Error_Msg_N
8326            ("`NOT NULL` required in formal, to match actual #",
8327             Analyzed_Formal);
8328       end if;
8329
8330       return List;
8331    end Instantiate_Object;
8332
8333    ------------------------------
8334    -- Instantiate_Package_Body --
8335    ------------------------------
8336
8337    procedure Instantiate_Package_Body
8338      (Body_Info    : Pending_Body_Info;
8339       Inlined_Body : Boolean := False)
8340    is
8341       Act_Decl    : constant Node_Id    := Body_Info.Act_Decl;
8342       Inst_Node   : constant Node_Id    := Body_Info.Inst_Node;
8343       Loc         : constant Source_Ptr := Sloc (Inst_Node);
8344
8345       Gen_Id      : constant Node_Id    := Name (Inst_Node);
8346       Gen_Unit    : constant Entity_Id  := Get_Generic_Entity (Inst_Node);
8347       Gen_Decl    : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
8348       Act_Spec    : constant Node_Id    := Specification (Act_Decl);
8349       Act_Decl_Id : constant Entity_Id  := Defining_Entity (Act_Spec);
8350
8351       Act_Body_Name : Node_Id;
8352       Gen_Body      : Node_Id;
8353       Gen_Body_Id   : Node_Id;
8354       Act_Body      : Node_Id;
8355       Act_Body_Id   : Entity_Id;
8356
8357       Parent_Installed : Boolean := False;
8358       Save_Style_Check : constant Boolean := Style_Check;
8359
8360    begin
8361       Gen_Body_Id := Corresponding_Body (Gen_Decl);
8362
8363       --  The instance body may already have been processed, as the parent of
8364       --  another instance that is inlined (Load_Parent_Of_Generic).
8365
8366       if Present (Corresponding_Body (Instance_Spec (Inst_Node))) then
8367          return;
8368       end if;
8369
8370       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
8371
8372       if No (Gen_Body_Id) then
8373          Load_Parent_Of_Generic (Inst_Node, Specification (Gen_Decl));
8374          Gen_Body_Id := Corresponding_Body (Gen_Decl);
8375       end if;
8376
8377       --  Establish global variable for sloc adjustment and for error recovery
8378
8379       Instantiation_Node := Inst_Node;
8380
8381       if Present (Gen_Body_Id) then
8382          Save_Env (Gen_Unit, Act_Decl_Id);
8383          Style_Check := False;
8384          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
8385
8386          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
8387
8388          Create_Instantiation_Source
8389           (Inst_Node, Gen_Body_Id, False, S_Adjustment);
8390
8391          Act_Body :=
8392            Copy_Generic_Node
8393              (Original_Node (Gen_Body), Empty, Instantiating => True);
8394
8395          --  Build new name (possibly qualified) for body declaration
8396
8397          Act_Body_Id := New_Copy (Act_Decl_Id);
8398
8399          --  Some attributes of spec entity are not inherited by body entity
8400
8401          Set_Handler_Records (Act_Body_Id, No_List);
8402
8403          if Nkind (Defining_Unit_Name (Act_Spec)) =
8404                                            N_Defining_Program_Unit_Name
8405          then
8406             Act_Body_Name :=
8407               Make_Defining_Program_Unit_Name (Loc,
8408                 Name => New_Copy_Tree (Name (Defining_Unit_Name (Act_Spec))),
8409                 Defining_Identifier => Act_Body_Id);
8410          else
8411             Act_Body_Name :=  Act_Body_Id;
8412          end if;
8413
8414          Set_Defining_Unit_Name (Act_Body, Act_Body_Name);
8415
8416          Set_Corresponding_Spec (Act_Body, Act_Decl_Id);
8417          Check_Generic_Actuals (Act_Decl_Id, False);
8418
8419          --  If it is a child unit, make the parent instance (which is an
8420          --  instance of the parent of the generic) visible. The parent
8421          --  instance is the prefix of the name of the generic unit.
8422
8423          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
8424            and then Nkind (Gen_Id) = N_Expanded_Name
8425          then
8426             Install_Parent (Entity (Prefix (Gen_Id)), In_Body => True);
8427             Parent_Installed := True;
8428
8429          elsif Is_Child_Unit (Gen_Unit) then
8430             Install_Parent (Scope (Gen_Unit), In_Body => True);
8431             Parent_Installed := True;
8432          end if;
8433
8434          --  If the instantiation is a library unit, and this is the main unit,
8435          --  then build the resulting compilation unit nodes for the instance.
8436          --  If this is a compilation unit but it is not the main unit, then it
8437          --  is the body of a unit in the context, that is being compiled
8438          --  because it is encloses some inlined unit or another generic unit
8439          --  being instantiated. In that case, this body is not part of the
8440          --  current compilation, and is not attached to the tree, but its
8441          --  parent must be set for analysis.
8442
8443          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8444
8445             --  Replace instance node with body of instance, and create new
8446             --  node for corresponding instance declaration.
8447
8448             Build_Instance_Compilation_Unit_Nodes
8449               (Inst_Node, Act_Body, Act_Decl);
8450             Analyze (Inst_Node);
8451
8452             if Parent (Inst_Node) = Cunit (Main_Unit) then
8453
8454                --  If the instance is a child unit itself, then set the scope
8455                --  of the expanded body to be the parent of the instantiation
8456                --  (ensuring that the fully qualified name will be generated
8457                --  for the elaboration subprogram).
8458
8459                if Nkind (Defining_Unit_Name (Act_Spec)) =
8460                                               N_Defining_Program_Unit_Name
8461                then
8462                   Set_Scope
8463                     (Defining_Entity (Inst_Node), Scope (Act_Decl_Id));
8464                end if;
8465             end if;
8466
8467          --  Case where instantiation is not a library unit
8468
8469          else
8470             --  If this is an early instantiation, i.e. appears textually
8471             --  before the corresponding body and must be elaborated first,
8472             --  indicate that the body instance is to be delayed.
8473
8474             Install_Body (Act_Body, Inst_Node, Gen_Body, Gen_Decl);
8475
8476             --  Now analyze the body. We turn off all checks if this is an
8477             --  internal unit, since there is no reason to have checks on for
8478             --  any predefined run-time library code. All such code is designed
8479             --  to be compiled with checks off.
8480
8481             --  Note that we do NOT apply this criterion to children of GNAT
8482             --  (or on VMS, children of DEC). The latter units must suppress
8483             --  checks explicitly if this is needed.
8484
8485             if Is_Predefined_File_Name
8486                  (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
8487             then
8488                Analyze (Act_Body, Suppress => All_Checks);
8489             else
8490                Analyze (Act_Body);
8491             end if;
8492          end if;
8493
8494          if not Generic_Separately_Compiled (Gen_Unit) then
8495             Inherit_Context (Gen_Body, Inst_Node);
8496          end if;
8497
8498          --  Remove the parent instances if they have been placed on the scope
8499          --  stack to compile the body.
8500
8501          if Parent_Installed then
8502             Remove_Parent (In_Body => True);
8503          end if;
8504
8505          Restore_Private_Views (Act_Decl_Id);
8506
8507          --  Remove the current unit from visibility if this is an instance
8508          --  that is not elaborated on the fly for inlining purposes.
8509
8510          if not Inlined_Body then
8511             Set_Is_Immediately_Visible (Act_Decl_Id, False);
8512          end if;
8513
8514          Restore_Env;
8515          Style_Check := Save_Style_Check;
8516
8517       --  If we have no body, and the unit requires a body, then complain. This
8518       --  complaint is suppressed if we have detected other errors (since a
8519       --  common reason for missing the body is that it had errors).
8520
8521       elsif Unit_Requires_Body (Gen_Unit) then
8522          if Serious_Errors_Detected = 0 then
8523             Error_Msg_NE
8524               ("cannot find body of generic package &", Inst_Node, Gen_Unit);
8525
8526          --  Don't attempt to perform any cleanup actions if some other error
8527          --  was aready detected, since this can cause blowups.
8528
8529          else
8530             return;
8531          end if;
8532
8533       --  Case of package that does not need a body
8534
8535       else
8536          --  If the instantiation of the declaration is a library unit, rewrite
8537          --  the original package instantiation as a package declaration in the
8538          --  compilation unit node.
8539
8540          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8541             Set_Parent_Spec (Act_Decl, Parent_Spec (Inst_Node));
8542             Rewrite (Inst_Node, Act_Decl);
8543
8544             --  Generate elaboration entity, in case spec has elaboration code.
8545             --  This cannot be done when the instance is analyzed, because it
8546             --  is not known yet whether the body exists.
8547
8548             Set_Elaboration_Entity_Required (Act_Decl_Id, False);
8549             Build_Elaboration_Entity (Parent (Inst_Node), Act_Decl_Id);
8550
8551          --  If the instantiation is not a library unit, then append the
8552          --  declaration to the list of implicitly generated entities. unless
8553          --  it is already a list member which means that it was already
8554          --  processed
8555
8556          elsif not Is_List_Member (Act_Decl) then
8557             Mark_Rewrite_Insertion (Act_Decl);
8558             Insert_Before (Inst_Node, Act_Decl);
8559          end if;
8560       end if;
8561
8562       Expander_Mode_Restore;
8563    end Instantiate_Package_Body;
8564
8565    ---------------------------------
8566    -- Instantiate_Subprogram_Body --
8567    ---------------------------------
8568
8569    procedure Instantiate_Subprogram_Body
8570      (Body_Info : Pending_Body_Info)
8571    is
8572       Act_Decl      : constant Node_Id    := Body_Info.Act_Decl;
8573       Inst_Node     : constant Node_Id    := Body_Info.Inst_Node;
8574       Loc           : constant Source_Ptr := Sloc (Inst_Node);
8575       Gen_Id        : constant Node_Id   := Name (Inst_Node);
8576       Gen_Unit      : constant Entity_Id := Get_Generic_Entity (Inst_Node);
8577       Gen_Decl      : constant Node_Id   := Unit_Declaration_Node (Gen_Unit);
8578       Anon_Id       : constant Entity_Id :=
8579                         Defining_Unit_Name (Specification (Act_Decl));
8580       Pack_Id       : constant Entity_Id :=
8581                         Defining_Unit_Name (Parent (Act_Decl));
8582       Decls         : List_Id;
8583       Gen_Body      : Node_Id;
8584       Gen_Body_Id   : Node_Id;
8585       Act_Body      : Node_Id;
8586       Pack_Body     : Node_Id;
8587       Prev_Formal   : Entity_Id;
8588       Ret_Expr      : Node_Id;
8589       Unit_Renaming : Node_Id;
8590
8591       Parent_Installed : Boolean := False;
8592       Save_Style_Check : constant Boolean := Style_Check;
8593
8594    begin
8595       Gen_Body_Id := Corresponding_Body (Gen_Decl);
8596
8597       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
8598
8599       if No (Gen_Body_Id) then
8600          Load_Parent_Of_Generic (Inst_Node, Specification (Gen_Decl));
8601          Gen_Body_Id := Corresponding_Body (Gen_Decl);
8602       end if;
8603
8604       Instantiation_Node := Inst_Node;
8605
8606       if Present (Gen_Body_Id) then
8607          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
8608
8609          if Nkind (Gen_Body) = N_Subprogram_Body_Stub then
8610
8611             --  Either body is not present, or context is non-expanding, as
8612             --  when compiling a subunit. Mark the instance as completed, and
8613             --  diagnose a missing body when needed.
8614
8615             if Expander_Active
8616               and then Operating_Mode = Generate_Code
8617             then
8618                Error_Msg_N
8619                  ("missing proper body for instantiation", Gen_Body);
8620             end if;
8621
8622             Set_Has_Completion (Anon_Id);
8623             return;
8624          end if;
8625
8626          Save_Env (Gen_Unit, Anon_Id);
8627          Style_Check := False;
8628          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
8629          Create_Instantiation_Source
8630            (Inst_Node,
8631             Gen_Body_Id,
8632             False,
8633             S_Adjustment);
8634
8635          Act_Body :=
8636            Copy_Generic_Node
8637              (Original_Node (Gen_Body), Empty, Instantiating => True);
8638
8639          --  Create proper defining name for the body, to correspond to
8640          --  the one in the spec.
8641
8642          Set_Defining_Unit_Name (Specification (Act_Body),
8643            Make_Defining_Identifier
8644              (Sloc (Defining_Entity (Inst_Node)), Chars (Anon_Id)));
8645          Set_Corresponding_Spec (Act_Body, Anon_Id);
8646          Set_Has_Completion (Anon_Id);
8647          Check_Generic_Actuals (Pack_Id, False);
8648
8649          --  Generate a reference to link the visible subprogram instance to
8650          --  the the generic body, which for navigation purposes is the only
8651          --  available source for the instance.
8652
8653          Generate_Reference
8654            (Related_Instance (Pack_Id),
8655              Gen_Body_Id, 'b', Set_Ref => False, Force => True);
8656
8657          --  If it is a child unit, make the parent instance (which is an
8658          --  instance of the parent of the generic) visible. The parent
8659          --  instance is the prefix of the name of the generic unit.
8660
8661          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
8662            and then Nkind (Gen_Id) = N_Expanded_Name
8663          then
8664             Install_Parent (Entity (Prefix (Gen_Id)), In_Body => True);
8665             Parent_Installed := True;
8666
8667          elsif Is_Child_Unit (Gen_Unit) then
8668             Install_Parent (Scope (Gen_Unit), In_Body => True);
8669             Parent_Installed := True;
8670          end if;
8671
8672          --  Inside its body, a reference to the generic unit is a reference
8673          --  to the instance. The corresponding renaming is the first
8674          --  declaration in the body.
8675
8676          Unit_Renaming :=
8677            Make_Subprogram_Renaming_Declaration (Loc,
8678              Specification =>
8679                Copy_Generic_Node (
8680                  Specification (Original_Node (Gen_Body)),
8681                  Empty,
8682                  Instantiating => True),
8683              Name => New_Occurrence_Of (Anon_Id, Loc));
8684
8685          --  If there is a formal subprogram with the same name as the unit
8686          --  itself, do not add this renaming declaration. This is a temporary
8687          --  fix for one ACVC test. ???
8688
8689          Prev_Formal := First_Entity (Pack_Id);
8690          while Present (Prev_Formal) loop
8691             if Chars (Prev_Formal) = Chars (Gen_Unit)
8692               and then Is_Overloadable (Prev_Formal)
8693             then
8694                exit;
8695             end if;
8696
8697             Next_Entity (Prev_Formal);
8698          end loop;
8699
8700          if Present (Prev_Formal) then
8701             Decls :=  New_List (Act_Body);
8702          else
8703             Decls :=  New_List (Unit_Renaming, Act_Body);
8704          end if;
8705
8706          --  The subprogram body is placed in the body of a dummy package body,
8707          --  whose spec contains the subprogram declaration as well as the
8708          --  renaming declarations for the generic parameters.
8709
8710          Pack_Body := Make_Package_Body (Loc,
8711            Defining_Unit_Name => New_Copy (Pack_Id),
8712            Declarations       => Decls);
8713
8714          Set_Corresponding_Spec (Pack_Body, Pack_Id);
8715
8716          --  If the instantiation is a library unit, then build resulting
8717          --  compilation unit nodes for the instance. The declaration of
8718          --  the enclosing package is the grandparent of the subprogram
8719          --  declaration. First replace the instantiation node as the unit
8720          --  of the corresponding compilation.
8721
8722          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
8723             if Parent (Inst_Node) = Cunit (Main_Unit) then
8724                Set_Unit (Parent (Inst_Node), Inst_Node);
8725                Build_Instance_Compilation_Unit_Nodes
8726                  (Inst_Node, Pack_Body, Parent (Parent (Act_Decl)));
8727                Analyze (Inst_Node);
8728             else
8729                Set_Parent (Pack_Body, Parent (Inst_Node));
8730                Analyze (Pack_Body);
8731             end if;
8732
8733          else
8734             Insert_Before (Inst_Node, Pack_Body);
8735             Mark_Rewrite_Insertion (Pack_Body);
8736             Analyze (Pack_Body);
8737
8738             if Expander_Active then
8739                Freeze_Subprogram_Body (Inst_Node, Gen_Body, Pack_Id);
8740             end if;
8741          end if;
8742
8743          if not Generic_Separately_Compiled (Gen_Unit) then
8744             Inherit_Context (Gen_Body, Inst_Node);
8745          end if;
8746
8747          Restore_Private_Views (Pack_Id, False);
8748
8749          if Parent_Installed then
8750             Remove_Parent (In_Body => True);
8751          end if;
8752
8753          Restore_Env;
8754          Style_Check := Save_Style_Check;
8755
8756       --  Body not found. Error was emitted already. If there were no previous
8757       --  errors, this may be an instance whose scope is a premature instance.
8758       --  In that case we must insure that the (legal) program does raise
8759       --  program error if executed. We generate a subprogram body for this
8760       --  purpose. See DEC ac30vso.
8761
8762       --  Should not reference proprietary DEC tests in comments ???
8763
8764       elsif Serious_Errors_Detected = 0
8765         and then Nkind (Parent (Inst_Node)) /= N_Compilation_Unit
8766       then
8767          if Ekind (Anon_Id) = E_Procedure then
8768             Act_Body :=
8769               Make_Subprogram_Body (Loc,
8770                  Specification              =>
8771                    Make_Procedure_Specification (Loc,
8772                      Defining_Unit_Name         =>
8773                        Make_Defining_Identifier (Loc, Chars (Anon_Id)),
8774                        Parameter_Specifications =>
8775                        New_Copy_List
8776                          (Parameter_Specifications (Parent (Anon_Id)))),
8777
8778                  Declarations               => Empty_List,
8779                  Handled_Statement_Sequence =>
8780                    Make_Handled_Sequence_Of_Statements (Loc,
8781                      Statements =>
8782                        New_List (
8783                          Make_Raise_Program_Error (Loc,
8784                            Reason =>
8785                              PE_Access_Before_Elaboration))));
8786
8787          else
8788             Ret_Expr :=
8789               Make_Raise_Program_Error (Loc,
8790                 Reason => PE_Access_Before_Elaboration);
8791
8792             Set_Etype (Ret_Expr, (Etype (Anon_Id)));
8793             Set_Analyzed (Ret_Expr);
8794
8795             Act_Body :=
8796               Make_Subprogram_Body (Loc,
8797                 Specification =>
8798                   Make_Function_Specification (Loc,
8799                      Defining_Unit_Name         =>
8800                        Make_Defining_Identifier (Loc, Chars (Anon_Id)),
8801                        Parameter_Specifications =>
8802                        New_Copy_List
8803                          (Parameter_Specifications (Parent (Anon_Id))),
8804                      Result_Definition =>
8805                        New_Occurrence_Of (Etype (Anon_Id), Loc)),
8806
8807                   Declarations               => Empty_List,
8808                   Handled_Statement_Sequence =>
8809                     Make_Handled_Sequence_Of_Statements (Loc,
8810                       Statements =>
8811                         New_List (Make_Return_Statement (Loc, Ret_Expr))));
8812          end if;
8813
8814          Pack_Body := Make_Package_Body (Loc,
8815            Defining_Unit_Name => New_Copy (Pack_Id),
8816            Declarations       => New_List (Act_Body));
8817
8818          Insert_After (Inst_Node, Pack_Body);
8819          Set_Corresponding_Spec (Pack_Body, Pack_Id);
8820          Analyze (Pack_Body);
8821       end if;
8822
8823       Expander_Mode_Restore;
8824    end Instantiate_Subprogram_Body;
8825
8826    ----------------------
8827    -- Instantiate_Type --
8828    ----------------------
8829
8830    function Instantiate_Type
8831      (Formal          : Node_Id;
8832       Actual          : Node_Id;
8833       Analyzed_Formal : Node_Id;
8834       Actual_Decls    : List_Id) return List_Id
8835    is
8836       Gen_T      : constant Entity_Id  := Defining_Identifier (Formal);
8837       A_Gen_T    : constant Entity_Id  :=
8838                      Defining_Identifier (Analyzed_Formal);
8839       Ancestor   : Entity_Id := Empty;
8840       Def        : constant Node_Id    := Formal_Type_Definition (Formal);
8841       Act_T      : Entity_Id;
8842       Decl_Node  : Node_Id;
8843       Decl_Nodes : List_Id;
8844       Loc        : Source_Ptr;
8845       Subt       : Entity_Id;
8846
8847       procedure Validate_Array_Type_Instance;
8848       procedure Validate_Access_Subprogram_Instance;
8849       procedure Validate_Access_Type_Instance;
8850       procedure Validate_Derived_Type_Instance;
8851       procedure Validate_Derived_Interface_Type_Instance;
8852       procedure Validate_Interface_Type_Instance;
8853       procedure Validate_Private_Type_Instance;
8854       --  These procedures perform validation tests for the named case
8855
8856       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean;
8857       --  Check that base types are the same and that the subtypes match
8858       --  statically. Used in several of the above.
8859
8860       --------------------
8861       -- Subtypes_Match --
8862       --------------------
8863
8864       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean is
8865          T : constant Entity_Id := Get_Instance_Of (Gen_T);
8866
8867       begin
8868          return (Base_Type (T) = Base_Type (Act_T)
8869                   and then Subtypes_Statically_Match (T, Act_T))
8870
8871            or else (Is_Class_Wide_Type (Gen_T)
8872                      and then Is_Class_Wide_Type (Act_T)
8873                      and then
8874                        Subtypes_Match
8875                         (Get_Instance_Of (Root_Type (Gen_T)),
8876                          Root_Type (Act_T)))
8877
8878            or else
8879              ((Ekind (Gen_T) = E_Anonymous_Access_Subprogram_Type
8880                  or else Ekind (Gen_T) = E_Anonymous_Access_Type)
8881                and then Ekind (Act_T) = Ekind (Gen_T)
8882                and then
8883                  Subtypes_Statically_Match
8884                    (Designated_Type (Gen_T), Designated_Type (Act_T)));
8885       end Subtypes_Match;
8886
8887       -----------------------------------------
8888       -- Validate_Access_Subprogram_Instance --
8889       -----------------------------------------
8890
8891       procedure Validate_Access_Subprogram_Instance is
8892       begin
8893          if not Is_Access_Type (Act_T)
8894            or else Ekind (Designated_Type (Act_T)) /= E_Subprogram_Type
8895          then
8896             Error_Msg_NE
8897               ("expect access type in instantiation of &", Actual, Gen_T);
8898             Abandon_Instantiation (Actual);
8899          end if;
8900
8901          Check_Mode_Conformant
8902            (Designated_Type (Act_T),
8903             Designated_Type (A_Gen_T),
8904             Actual,
8905             Get_Inst => True);
8906
8907          if Ekind (Base_Type (Act_T)) = E_Access_Protected_Subprogram_Type then
8908             if Ekind (A_Gen_T) = E_Access_Subprogram_Type then
8909                Error_Msg_NE
8910                  ("protected access type not allowed for formal &",
8911                   Actual, Gen_T);
8912             end if;
8913
8914          elsif Ekind (A_Gen_T) = E_Access_Protected_Subprogram_Type then
8915             Error_Msg_NE
8916               ("expect protected access type for formal &",
8917                Actual, Gen_T);
8918          end if;
8919       end Validate_Access_Subprogram_Instance;
8920
8921       -----------------------------------
8922       -- Validate_Access_Type_Instance --
8923       -----------------------------------
8924
8925       procedure Validate_Access_Type_Instance is
8926          Desig_Type : constant Entity_Id :=
8927                         Find_Actual_Type
8928                           (Designated_Type (A_Gen_T), Scope (A_Gen_T));
8929
8930       begin
8931          if not Is_Access_Type (Act_T) then
8932             Error_Msg_NE
8933               ("expect access type in instantiation of &", Actual, Gen_T);
8934             Abandon_Instantiation (Actual);
8935          end if;
8936
8937          if Is_Access_Constant (A_Gen_T) then
8938             if not Is_Access_Constant (Act_T) then
8939                Error_Msg_N
8940                  ("actual type must be access-to-constant type", Actual);
8941                Abandon_Instantiation (Actual);
8942             end if;
8943          else
8944             if Is_Access_Constant (Act_T) then
8945                Error_Msg_N
8946                  ("actual type must be access-to-variable type", Actual);
8947                Abandon_Instantiation (Actual);
8948
8949             elsif Ekind (A_Gen_T) = E_General_Access_Type
8950               and then Ekind (Base_Type (Act_T)) /= E_General_Access_Type
8951             then
8952                Error_Msg_N ("actual must be general access type!", Actual);
8953                Error_Msg_NE ("add ALL to }!", Actual, Act_T);
8954                Abandon_Instantiation (Actual);
8955             end if;
8956          end if;
8957
8958          --  The designated subtypes, that is to say the subtypes introduced
8959          --  by an access type declaration (and not by a subtype declaration)
8960          --  must match.
8961
8962          if not Subtypes_Match
8963            (Desig_Type, Designated_Type (Base_Type (Act_T)))
8964          then
8965             Error_Msg_NE
8966               ("designated type of actual does not match that of formal &",
8967                  Actual, Gen_T);
8968             Abandon_Instantiation (Actual);
8969
8970          elsif Is_Access_Type (Designated_Type (Act_T))
8971            and then Is_Constrained (Designated_Type (Designated_Type (Act_T)))
8972                       /=
8973                   Is_Constrained (Designated_Type (Desig_Type))
8974          then
8975             Error_Msg_NE
8976               ("designated type of actual does not match that of formal &",
8977                  Actual, Gen_T);
8978             Abandon_Instantiation (Actual);
8979          end if;
8980
8981          --  Ada 2005: null-exclusion indicators of the two types must agree
8982
8983          if Can_Never_Be_Null (A_Gen_T) /=  Can_Never_Be_Null (Act_T) then
8984             Error_Msg_NE
8985               ("non null exclusion of actual and formal & do not match",
8986                  Actual, Gen_T);
8987          end if;
8988       end Validate_Access_Type_Instance;
8989
8990       ----------------------------------
8991       -- Validate_Array_Type_Instance --
8992       ----------------------------------
8993
8994       procedure Validate_Array_Type_Instance is
8995          I1 : Node_Id;
8996          I2 : Node_Id;
8997          T2 : Entity_Id;
8998
8999          function Formal_Dimensions return Int;
9000          --  Count number of dimensions in array type formal
9001
9002          -----------------------
9003          -- Formal_Dimensions --
9004          -----------------------
9005
9006          function Formal_Dimensions return Int is
9007             Num   : Int := 0;
9008             Index : Node_Id;
9009
9010          begin
9011             if Nkind (Def) = N_Constrained_Array_Definition then
9012                Index := First (Discrete_Subtype_Definitions (Def));
9013             else
9014                Index := First (Subtype_Marks (Def));
9015             end if;
9016
9017             while Present (Index) loop
9018                Num := Num + 1;
9019                Next_Index (Index);
9020             end loop;
9021
9022             return Num;
9023          end Formal_Dimensions;
9024
9025       --  Start of processing for Validate_Array_Type_Instance
9026
9027       begin
9028          if not Is_Array_Type (Act_T) then
9029             Error_Msg_NE
9030               ("expect array type in instantiation of &", Actual, Gen_T);
9031             Abandon_Instantiation (Actual);
9032
9033          elsif Nkind (Def) = N_Constrained_Array_Definition then
9034             if not (Is_Constrained (Act_T)) then
9035                Error_Msg_NE
9036                  ("expect constrained array in instantiation of &",
9037                   Actual, Gen_T);
9038                Abandon_Instantiation (Actual);
9039             end if;
9040
9041          else
9042             if Is_Constrained (Act_T) then
9043                Error_Msg_NE
9044                  ("expect unconstrained array in instantiation of &",
9045                   Actual, Gen_T);
9046                Abandon_Instantiation (Actual);
9047             end if;
9048          end if;
9049
9050          if Formal_Dimensions /= Number_Dimensions (Act_T) then
9051             Error_Msg_NE
9052               ("dimensions of actual do not match formal &", Actual, Gen_T);
9053             Abandon_Instantiation (Actual);
9054          end if;
9055
9056          I1 := First_Index (A_Gen_T);
9057          I2 := First_Index (Act_T);
9058          for J in 1 .. Formal_Dimensions loop
9059
9060             --  If the indices of the actual were given by a subtype_mark,
9061             --  the index was transformed into a range attribute. Retrieve
9062             --  the original type mark for checking.
9063
9064             if Is_Entity_Name (Original_Node (I2)) then
9065                T2 := Entity (Original_Node (I2));
9066             else
9067                T2 := Etype (I2);
9068             end if;
9069
9070             if not Subtypes_Match
9071               (Find_Actual_Type (Etype (I1), Scope (A_Gen_T)), T2)
9072             then
9073                Error_Msg_NE
9074                  ("index types of actual do not match those of formal &",
9075                   Actual, Gen_T);
9076                Abandon_Instantiation (Actual);
9077             end if;
9078
9079             Next_Index (I1);
9080             Next_Index (I2);
9081          end loop;
9082
9083          if not Subtypes_Match (
9084             Find_Actual_Type (Component_Type (A_Gen_T), Scope (A_Gen_T)),
9085             Component_Type (Act_T))
9086          then
9087             Error_Msg_NE
9088               ("component subtype of actual does not match that of formal &",
9089                Actual, Gen_T);
9090             Abandon_Instantiation (Actual);
9091          end if;
9092
9093          if Has_Aliased_Components (A_Gen_T)
9094            and then not Has_Aliased_Components (Act_T)
9095          then
9096             Error_Msg_NE
9097               ("actual must have aliased components to match formal type &",
9098                Actual, Gen_T);
9099          end if;
9100
9101       end Validate_Array_Type_Instance;
9102
9103       -----------------------------------------------
9104       --  Validate_Derived_Interface_Type_Instance --
9105       -----------------------------------------------
9106
9107       procedure Validate_Derived_Interface_Type_Instance is
9108          Par  : constant Entity_Id := Entity (Subtype_Indication (Def));
9109          Elmt : Elmt_Id;
9110
9111       begin
9112          --  First apply interface instance checks
9113
9114          Validate_Interface_Type_Instance;
9115
9116          --  Verify that immediate parent interface is an ancestor of
9117          --  the actual.
9118
9119          if Present (Par)
9120            and then not Interface_Present_In_Ancestor (Act_T, Par)
9121          then
9122             Error_Msg_NE
9123               ("interface actual must include progenitor&", Actual, Par);
9124          end if;
9125
9126          --  Now verify that the actual includes all other ancestors of
9127          --  the formal.
9128
9129          Elmt := First_Elmt (Abstract_Interfaces (A_Gen_T));
9130          while Present (Elmt) loop
9131             if not Interface_Present_In_Ancestor
9132                      (Act_T, Get_Instance_Of (Node (Elmt)))
9133             then
9134                Error_Msg_NE
9135                  ("interface actual must include progenitor&",
9136                     Actual, Node (Elmt));
9137             end if;
9138
9139             Next_Elmt (Elmt);
9140          end loop;
9141       end Validate_Derived_Interface_Type_Instance;
9142
9143       ------------------------------------
9144       -- Validate_Derived_Type_Instance --
9145       ------------------------------------
9146
9147       procedure Validate_Derived_Type_Instance is
9148          Actual_Discr   : Entity_Id;
9149          Ancestor_Discr : Entity_Id;
9150
9151       begin
9152          --  If the parent type in the generic declaration is itself a previous
9153          --  formal type, then it is local to the generic and absent from the
9154          --  analyzed generic definition. In that case the ancestor is the
9155          --  instance of the formal (which must have been instantiated
9156          --  previously), unless the ancestor is itself a formal derived type.
9157          --  In this latter case (which is the subject of Corrigendum 8652/0038
9158          --  (AI-202) the ancestor of the formals is the ancestor of its
9159          --  parent. Otherwise, the analyzed generic carries the parent type.
9160          --  If the parent type is defined in a previous formal package, then
9161          --  the scope of that formal package is that of the generic type
9162          --  itself, and it has already been mapped into the corresponding type
9163          --  in the actual package.
9164
9165          --  Common case: parent type defined outside of the generic
9166
9167          if Is_Entity_Name (Subtype_Mark (Def))
9168            and then Present (Entity (Subtype_Mark (Def)))
9169          then
9170             Ancestor := Get_Instance_Of (Entity (Subtype_Mark (Def)));
9171
9172          --  Check whether parent is defined in a previous formal package
9173
9174          elsif
9175            Scope (Scope (Base_Type (Etype (A_Gen_T)))) = Scope (A_Gen_T)
9176          then
9177             Ancestor :=
9178               Get_Instance_Of (Base_Type (Etype (A_Gen_T)));
9179
9180          --  The type may be a local derivation, or a type extension of a
9181          --  previous formal, or of a formal of a parent package.
9182
9183          elsif Is_Derived_Type (Get_Instance_Of (A_Gen_T))
9184           or else
9185             Ekind (Get_Instance_Of (A_Gen_T)) = E_Record_Type_With_Private
9186          then
9187             --  Check whether the parent is another derived formal type in the
9188             --  same generic unit.
9189
9190             if Etype (A_Gen_T) /= A_Gen_T
9191               and then Is_Generic_Type (Etype (A_Gen_T))
9192               and then Scope (Etype (A_Gen_T)) = Scope (A_Gen_T)
9193               and then Etype (Etype (A_Gen_T)) /= Etype (A_Gen_T)
9194             then
9195                --  Locate ancestor of parent from the subtype declaration
9196                --  created for the actual.
9197
9198                declare
9199                   Decl : Node_Id;
9200
9201                begin
9202                   Decl := First (Actual_Decls);
9203                   while Present (Decl) loop
9204                      if Nkind (Decl) = N_Subtype_Declaration
9205                        and then Chars (Defining_Identifier (Decl)) =
9206                                                     Chars (Etype (A_Gen_T))
9207                      then
9208                         Ancestor := Generic_Parent_Type (Decl);
9209                         exit;
9210                      else
9211                         Next (Decl);
9212                      end if;
9213                   end loop;
9214                end;
9215
9216                pragma Assert (Present (Ancestor));
9217
9218             else
9219                Ancestor :=
9220                  Get_Instance_Of (Base_Type (Get_Instance_Of (A_Gen_T)));
9221             end if;
9222
9223          else
9224             Ancestor := Get_Instance_Of (Etype (Base_Type (A_Gen_T)));
9225          end if;
9226
9227          --  Ada 2005 (AI-251)
9228
9229          if Ada_Version >= Ada_05
9230            and then Is_Interface (Ancestor)
9231          then
9232             if not Interface_Present_In_Ancestor (Act_T, Ancestor) then
9233                Error_Msg_NE
9234                  ("(Ada 2005) expected type implementing & in instantiation",
9235                   Actual, Ancestor);
9236             end if;
9237
9238          elsif not Is_Ancestor (Base_Type (Ancestor), Act_T) then
9239             Error_Msg_NE
9240               ("expect type derived from & in instantiation",
9241                Actual, First_Subtype (Ancestor));
9242             Abandon_Instantiation (Actual);
9243          end if;
9244
9245          --  Ada 2005 (AI-443): Synchronized formal derived type ckecks. Note
9246          --  that the formal type declaration has been rewritten as a private
9247          --  extension.
9248
9249          if Ada_Version >= Ada_05
9250            and then Nkind (Parent (A_Gen_T)) = N_Private_Extension_Declaration
9251            and then Synchronized_Present (Parent (A_Gen_T))
9252          then
9253             --  The actual must be a synchronized tagged type
9254
9255             if not Is_Tagged_Type (Act_T) then
9256                Error_Msg_N
9257                  ("actual of synchronized type must be tagged", Actual);
9258                Abandon_Instantiation (Actual);
9259
9260             elsif Nkind (Parent (Act_T)) = N_Full_Type_Declaration
9261               and then Nkind (Type_Definition (Parent (Act_T))) =
9262                          N_Derived_Type_Definition
9263               and then not Synchronized_Present (Type_Definition
9264                              (Parent (Act_T)))
9265             then
9266                Error_Msg_N
9267                  ("actual of synchronized type must be synchronized", Actual);
9268                Abandon_Instantiation (Actual);
9269             end if;
9270          end if;
9271
9272          --  Perform atomic/volatile checks (RM C.6(12))
9273
9274          if Is_Atomic (Act_T) and then not Is_Atomic (Ancestor) then
9275             Error_Msg_N
9276               ("cannot have atomic actual type for non-atomic formal type",
9277                Actual);
9278
9279          elsif Is_Volatile (Act_T)
9280            and then not Is_Volatile (Ancestor)
9281            and then Is_By_Reference_Type (Ancestor)
9282          then
9283             Error_Msg_N
9284               ("cannot have volatile actual type for non-volatile formal type",
9285                Actual);
9286          end if;
9287
9288          --  It should not be necessary to check for unknown discriminants on
9289          --  Formal, but for some reason Has_Unknown_Discriminants is false for
9290          --  A_Gen_T, so Is_Indefinite_Subtype incorrectly returns False. This
9291          --  needs fixing. ???
9292
9293          if not Is_Indefinite_Subtype (A_Gen_T)
9294            and then not Unknown_Discriminants_Present (Formal)
9295            and then Is_Indefinite_Subtype (Act_T)
9296          then
9297             Error_Msg_N
9298               ("actual subtype must be constrained", Actual);
9299             Abandon_Instantiation (Actual);
9300          end if;
9301
9302          if not Unknown_Discriminants_Present (Formal) then
9303             if Is_Constrained (Ancestor) then
9304                if not Is_Constrained (Act_T) then
9305                   Error_Msg_N
9306                     ("actual subtype must be constrained", Actual);
9307                   Abandon_Instantiation (Actual);
9308                end if;
9309
9310             --  Ancestor is unconstrained, Check if generic formal and actual
9311             --  agree on constrainedness. The check only applies to array types
9312             --  and discriminated types.
9313
9314             elsif Is_Constrained (Act_T) then
9315                if Ekind (Ancestor) = E_Access_Type
9316                  or else
9317                    (not Is_Constrained (A_Gen_T)
9318                      and then Is_Composite_Type (A_Gen_T))
9319                then
9320                   Error_Msg_N
9321                     ("actual subtype must be unconstrained", Actual);
9322                   Abandon_Instantiation (Actual);
9323                end if;
9324
9325             --  A class-wide type is only allowed if the formal has unknown
9326             --  discriminants.
9327
9328             elsif Is_Class_Wide_Type (Act_T)
9329               and then not Has_Unknown_Discriminants (Ancestor)
9330             then
9331                Error_Msg_NE
9332                  ("actual for & cannot be a class-wide type", Actual, Gen_T);
9333                Abandon_Instantiation (Actual);
9334
9335             --  Otherwise, the formal and actual shall have the same number
9336             --  of discriminants and each discriminant of the actual must
9337             --  correspond to a discriminant of the formal.
9338
9339             elsif Has_Discriminants (Act_T)
9340               and then not Has_Unknown_Discriminants (Act_T)
9341               and then Has_Discriminants (Ancestor)
9342             then
9343                Actual_Discr   := First_Discriminant (Act_T);
9344                Ancestor_Discr := First_Discriminant (Ancestor);
9345                while Present (Actual_Discr)
9346                  and then Present (Ancestor_Discr)
9347                loop
9348                   if Base_Type (Act_T) /= Base_Type (Ancestor) and then
9349                     No (Corresponding_Discriminant (Actual_Discr))
9350                   then
9351                      Error_Msg_NE
9352                        ("discriminant & does not correspond " &
9353                         "to ancestor discriminant", Actual, Actual_Discr);
9354                      Abandon_Instantiation (Actual);
9355                   end if;
9356
9357                   Next_Discriminant (Actual_Discr);
9358                   Next_Discriminant (Ancestor_Discr);
9359                end loop;
9360
9361                if Present (Actual_Discr) or else Present (Ancestor_Discr) then
9362                   Error_Msg_NE
9363                     ("actual for & must have same number of discriminants",
9364                      Actual, Gen_T);
9365                   Abandon_Instantiation (Actual);
9366                end if;
9367
9368             --  This case should be caught by the earlier check for for
9369             --  constrainedness, but the check here is added for completeness.
9370
9371             elsif Has_Discriminants (Act_T)
9372               and then not Has_Unknown_Discriminants (Act_T)
9373             then
9374                Error_Msg_NE
9375                  ("actual for & must not have discriminants", Actual, Gen_T);
9376                Abandon_Instantiation (Actual);
9377
9378             elsif Has_Discriminants (Ancestor) then
9379                Error_Msg_NE
9380                  ("actual for & must have known discriminants", Actual, Gen_T);
9381                Abandon_Instantiation (Actual);
9382             end if;
9383
9384             if not Subtypes_Statically_Compatible (Act_T, Ancestor) then
9385                Error_Msg_N
9386                  ("constraint on actual is incompatible with formal", Actual);
9387                Abandon_Instantiation (Actual);
9388             end if;
9389          end if;
9390       end Validate_Derived_Type_Instance;
9391
9392       --------------------------------------
9393       -- Validate_Interface_Type_Instance --
9394       --------------------------------------
9395
9396       procedure Validate_Interface_Type_Instance is
9397       begin
9398          if not Is_Interface (Act_T) then
9399             Error_Msg_NE
9400               ("actual for formal interface type must be an interface",
9401                 Actual, Gen_T);
9402
9403          elsif Is_Limited_Type (Act_T) /= Is_Limited_Type (A_Gen_T)
9404            or else
9405              Is_Task_Interface (A_Gen_T) /= Is_Task_Interface (Act_T)
9406            or else
9407              Is_Protected_Interface (A_Gen_T) /=
9408                Is_Protected_Interface (Act_T)
9409            or else
9410              Is_Synchronized_Interface (A_Gen_T) /=
9411                Is_Synchronized_Interface (Act_T)
9412          then
9413             Error_Msg_NE
9414               ("actual for interface& does not match ('R'M 12.5.5(4))",
9415                  Actual, Gen_T);
9416          end if;
9417       end Validate_Interface_Type_Instance;
9418
9419       ------------------------------------
9420       -- Validate_Private_Type_Instance --
9421       ------------------------------------
9422
9423       procedure Validate_Private_Type_Instance is
9424          Formal_Discr : Entity_Id;
9425          Actual_Discr : Entity_Id;
9426          Formal_Subt  : Entity_Id;
9427
9428       begin
9429          if Is_Limited_Type (Act_T)
9430            and then not Is_Limited_Type (A_Gen_T)
9431          then
9432             Error_Msg_NE
9433               ("actual for non-limited & cannot be a limited type", Actual,
9434                Gen_T);
9435             Explain_Limited_Type (Act_T, Actual);
9436             Abandon_Instantiation (Actual);
9437
9438          elsif Known_To_Have_Preelab_Init (A_Gen_T)
9439            and then not Has_Preelaborable_Initialization (Act_T)
9440          then
9441             Error_Msg_NE
9442               ("actual for & must have preelaborable initialization", Actual,
9443                Gen_T);
9444
9445          elsif Is_Indefinite_Subtype (Act_T)
9446             and then not Is_Indefinite_Subtype (A_Gen_T)
9447             and then Ada_Version >= Ada_95
9448          then
9449             Error_Msg_NE
9450               ("actual for & must be a definite subtype", Actual, Gen_T);
9451
9452          elsif not Is_Tagged_Type (Act_T)
9453            and then Is_Tagged_Type (A_Gen_T)
9454          then
9455             Error_Msg_NE
9456               ("actual for & must be a tagged type", Actual, Gen_T);
9457
9458          elsif Has_Discriminants (A_Gen_T) then
9459             if not Has_Discriminants (Act_T) then
9460                Error_Msg_NE
9461                  ("actual for & must have discriminants", Actual, Gen_T);
9462                Abandon_Instantiation (Actual);
9463
9464             elsif Is_Constrained (Act_T) then
9465                Error_Msg_NE
9466                  ("actual for & must be unconstrained", Actual, Gen_T);
9467                Abandon_Instantiation (Actual);
9468
9469             else
9470                Formal_Discr := First_Discriminant (A_Gen_T);
9471                Actual_Discr := First_Discriminant (Act_T);
9472                while Formal_Discr /= Empty loop
9473                   if Actual_Discr = Empty then
9474                      Error_Msg_NE
9475                        ("discriminants on actual do not match formal",
9476                         Actual, Gen_T);
9477                      Abandon_Instantiation (Actual);
9478                   end if;
9479
9480                   Formal_Subt := Get_Instance_Of (Etype (Formal_Discr));
9481
9482                   --  Access discriminants match if designated types do
9483
9484                   if Ekind (Base_Type (Formal_Subt)) = E_Anonymous_Access_Type
9485                     and then (Ekind (Base_Type (Etype (Actual_Discr)))) =
9486                                 E_Anonymous_Access_Type
9487                     and then
9488                       Get_Instance_Of
9489                         (Designated_Type (Base_Type (Formal_Subt))) =
9490                            Designated_Type (Base_Type (Etype (Actual_Discr)))
9491                   then
9492                      null;
9493
9494                   elsif Base_Type (Formal_Subt) /=
9495                           Base_Type (Etype (Actual_Discr))
9496                   then
9497                      Error_Msg_NE
9498                        ("types of actual discriminants must match formal",
9499                         Actual, Gen_T);
9500                      Abandon_Instantiation (Actual);
9501
9502                   elsif not Subtypes_Statically_Match
9503                               (Formal_Subt, Etype (Actual_Discr))
9504                     and then Ada_Version >= Ada_95
9505                   then
9506                      Error_Msg_NE
9507                        ("subtypes of actual discriminants must match formal",
9508                         Actual, Gen_T);
9509                      Abandon_Instantiation (Actual);
9510                   end if;
9511
9512                   Next_Discriminant (Formal_Discr);
9513                   Next_Discriminant (Actual_Discr);
9514                end loop;
9515
9516                if Actual_Discr /= Empty then
9517                   Error_Msg_NE
9518                     ("discriminants on actual do not match formal",
9519                      Actual, Gen_T);
9520                   Abandon_Instantiation (Actual);
9521                end if;
9522             end if;
9523
9524          end if;
9525
9526          Ancestor := Gen_T;
9527       end Validate_Private_Type_Instance;
9528
9529    --  Start of processing for Instantiate_Type
9530
9531    begin
9532       if Get_Instance_Of (A_Gen_T) /= A_Gen_T then
9533          Error_Msg_N ("duplicate instantiation of generic type", Actual);
9534          return New_List (Error);
9535
9536       elsif not Is_Entity_Name (Actual)
9537         or else not Is_Type (Entity (Actual))
9538       then
9539          Error_Msg_NE
9540            ("expect valid subtype mark to instantiate &", Actual, Gen_T);
9541          Abandon_Instantiation (Actual);
9542
9543       else
9544          Act_T := Entity (Actual);
9545
9546          --  Ada 2005 (AI-216): An Unchecked_Union subtype shall only be passed
9547          --  as a generic actual parameter if the corresponding formal type
9548          --  does not have a known_discriminant_part, or is a formal derived
9549          --  type that is an Unchecked_Union type.
9550
9551          if Is_Unchecked_Union (Base_Type (Act_T)) then
9552             if not Has_Discriminants (A_Gen_T)
9553                      or else
9554                    (Is_Derived_Type (A_Gen_T)
9555                      and then
9556                     Is_Unchecked_Union (A_Gen_T))
9557             then
9558                null;
9559             else
9560                Error_Msg_N ("Unchecked_Union cannot be the actual for a" &
9561                  " discriminated formal type", Act_T);
9562
9563             end if;
9564          end if;
9565
9566          --  Deal with fixed/floating restrictions
9567
9568          if Is_Floating_Point_Type (Act_T) then
9569             Check_Restriction (No_Floating_Point, Actual);
9570          elsif Is_Fixed_Point_Type (Act_T) then
9571             Check_Restriction (No_Fixed_Point, Actual);
9572          end if;
9573
9574          --  Deal with error of using incomplete type as generic actual
9575
9576          if Ekind (Act_T) = E_Incomplete_Type
9577            or else (Is_Class_Wide_Type (Act_T)
9578                       and then
9579                          Ekind (Root_Type (Act_T)) = E_Incomplete_Type)
9580          then
9581             if Is_Class_Wide_Type (Act_T)
9582               or else No (Underlying_Type (Act_T))
9583             then
9584                Error_Msg_N ("premature use of incomplete type", Actual);
9585                Abandon_Instantiation (Actual);
9586             else
9587                Act_T := Full_View (Act_T);
9588                Set_Entity (Actual, Act_T);
9589
9590                if Has_Private_Component (Act_T) then
9591                   Error_Msg_N
9592                     ("premature use of type with private component", Actual);
9593                end if;
9594             end if;
9595
9596          --  Deal with error of premature use of private type as generic actual
9597
9598          elsif Is_Private_Type (Act_T)
9599            and then Is_Private_Type (Base_Type (Act_T))
9600            and then not Is_Generic_Type (Act_T)
9601            and then not Is_Derived_Type (Act_T)
9602            and then No (Full_View (Root_Type (Act_T)))
9603          then
9604             Error_Msg_N ("premature use of private type", Actual);
9605
9606          elsif Has_Private_Component (Act_T) then
9607             Error_Msg_N
9608               ("premature use of type with private component", Actual);
9609          end if;
9610
9611          Set_Instance_Of (A_Gen_T, Act_T);
9612
9613          --  If the type is generic, the class-wide type may also be used
9614
9615          if Is_Tagged_Type (A_Gen_T)
9616            and then Is_Tagged_Type (Act_T)
9617            and then not Is_Class_Wide_Type (A_Gen_T)
9618          then
9619             Set_Instance_Of (Class_Wide_Type (A_Gen_T),
9620               Class_Wide_Type (Act_T));
9621          end if;
9622
9623          if not Is_Abstract_Type (A_Gen_T)
9624            and then Is_Abstract_Type (Act_T)
9625          then
9626             Error_Msg_N
9627               ("actual of non-abstract formal cannot be abstract", Actual);
9628          end if;
9629
9630          --  A generic scalar type is a first subtype for which we generate
9631          --  an anonymous base type. Indicate that the instance of this base
9632          --  is the base type of the actual.
9633
9634          if Is_Scalar_Type (A_Gen_T) then
9635             Set_Instance_Of (Etype (A_Gen_T), Etype (Act_T));
9636          end if;
9637       end if;
9638
9639       case Nkind (Def) is
9640          when N_Formal_Private_Type_Definition =>
9641             Validate_Private_Type_Instance;
9642
9643          when N_Formal_Derived_Type_Definition =>
9644             Validate_Derived_Type_Instance;
9645
9646          when N_Formal_Discrete_Type_Definition =>
9647             if not Is_Discrete_Type (Act_T) then
9648                Error_Msg_NE
9649                  ("expect discrete type in instantiation of&", Actual, Gen_T);
9650                Abandon_Instantiation (Actual);
9651             end if;
9652
9653          when N_Formal_Signed_Integer_Type_Definition =>
9654             if not Is_Signed_Integer_Type (Act_T) then
9655                Error_Msg_NE
9656                  ("expect signed integer type in instantiation of&",
9657                   Actual, Gen_T);
9658                Abandon_Instantiation (Actual);
9659             end if;
9660
9661          when N_Formal_Modular_Type_Definition =>
9662             if not Is_Modular_Integer_Type (Act_T) then
9663                Error_Msg_NE
9664                  ("expect modular type in instantiation of &", Actual, Gen_T);
9665                Abandon_Instantiation (Actual);
9666             end if;
9667
9668          when N_Formal_Floating_Point_Definition =>
9669             if not Is_Floating_Point_Type (Act_T) then
9670                Error_Msg_NE
9671                  ("expect float type in instantiation of &", Actual, Gen_T);
9672                Abandon_Instantiation (Actual);
9673             end if;
9674
9675          when N_Formal_Ordinary_Fixed_Point_Definition =>
9676             if not Is_Ordinary_Fixed_Point_Type (Act_T) then
9677                Error_Msg_NE
9678                  ("expect ordinary fixed point type in instantiation of &",
9679                   Actual, Gen_T);
9680                Abandon_Instantiation (Actual);
9681             end if;
9682
9683          when N_Formal_Decimal_Fixed_Point_Definition =>
9684             if not Is_Decimal_Fixed_Point_Type (Act_T) then
9685                Error_Msg_NE
9686                  ("expect decimal type in instantiation of &",
9687                   Actual, Gen_T);
9688                Abandon_Instantiation (Actual);
9689             end if;
9690
9691          when N_Array_Type_Definition =>
9692             Validate_Array_Type_Instance;
9693
9694          when N_Access_To_Object_Definition =>
9695             Validate_Access_Type_Instance;
9696
9697          when N_Access_Function_Definition |
9698               N_Access_Procedure_Definition =>
9699             Validate_Access_Subprogram_Instance;
9700
9701          when N_Record_Definition           =>
9702             Validate_Interface_Type_Instance;
9703
9704          when N_Derived_Type_Definition     =>
9705             Validate_Derived_Interface_Type_Instance;
9706
9707          when others =>
9708             raise Program_Error;
9709
9710       end case;
9711
9712       Subt := New_Copy (Gen_T);
9713
9714       --  Use adjusted sloc of subtype name as the location for other nodes in
9715       --  the subtype declaration.
9716
9717       Loc  := Sloc (Subt);
9718
9719       Decl_Node :=
9720         Make_Subtype_Declaration (Loc,
9721           Defining_Identifier => Subt,
9722           Subtype_Indication  => New_Reference_To (Act_T, Loc));
9723
9724       if Is_Private_Type (Act_T) then
9725          Set_Has_Private_View (Subtype_Indication (Decl_Node));
9726
9727       elsif Is_Access_Type (Act_T)
9728         and then Is_Private_Type (Designated_Type (Act_T))
9729       then
9730          Set_Has_Private_View (Subtype_Indication (Decl_Node));
9731       end if;
9732
9733       Decl_Nodes := New_List (Decl_Node);
9734
9735       --  Flag actual derived types so their elaboration produces the
9736       --  appropriate renamings for the primitive operations of the ancestor.
9737       --  Flag actual for formal private types as well, to determine whether
9738       --  operations in the private part may override inherited operations.
9739
9740       if Nkind (Def) = N_Formal_Derived_Type_Definition
9741         or else Nkind (Def) = N_Formal_Private_Type_Definition
9742       then
9743          Set_Generic_Parent_Type (Decl_Node, Ancestor);
9744       end if;
9745
9746       --  If the actual is a synchronized type that implements an interface,
9747       --  the primitive operations are attached to the corresponding record,
9748       --  and we have to treat it as an additional generic actual, so that its
9749       --  primitive operations become visible in the instance. The task or
9750       --  protected type itself does not carry primitive operations.
9751
9752       if Is_Concurrent_Type (Act_T)
9753         and then Is_Tagged_Type (Act_T)
9754         and then Present (Corresponding_Record_Type (Act_T))
9755         and then Present (Ancestor)
9756         and then Is_Interface (Ancestor)
9757       then
9758          declare
9759             Corr_Rec  : constant Entity_Id :=
9760                           Corresponding_Record_Type (Act_T);
9761             New_Corr  : Entity_Id;
9762             Corr_Decl : Node_Id;
9763
9764          begin
9765             New_Corr := Make_Defining_Identifier (Loc,
9766                             Chars => New_Internal_Name  ('S'));
9767             Corr_Decl :=
9768               Make_Subtype_Declaration (Loc,
9769                 Defining_Identifier => New_Corr,
9770                 Subtype_Indication  =>
9771                   New_Reference_To (Corr_Rec, Loc));
9772             Append_To (Decl_Nodes, Corr_Decl);
9773
9774             if Ekind (Act_T) = E_Task_Type then
9775                Set_Ekind (Subt, E_Task_Subtype);
9776             else
9777                Set_Ekind (Subt, E_Protected_Subtype);
9778             end if;
9779
9780             Set_Corresponding_Record_Type (Subt, Corr_Rec);
9781             Set_Generic_Parent_Type (Corr_Decl, Ancestor);
9782             Set_Generic_Parent_Type (Decl_Node, Empty);
9783          end;
9784       end if;
9785
9786       return Decl_Nodes;
9787    end Instantiate_Type;
9788
9789    -----------------------
9790    -- Is_Generic_Formal --
9791    -----------------------
9792
9793    function Is_Generic_Formal (E : Entity_Id) return Boolean is
9794       Kind : Node_Kind;
9795
9796    begin
9797       if No (E) then
9798          return False;
9799       else
9800          Kind := Nkind (Parent (E));
9801          return
9802            Kind = N_Formal_Object_Declaration
9803              or else Kind = N_Formal_Package_Declaration
9804              or else Kind = N_Formal_Type_Declaration
9805              or else
9806                (Is_Formal_Subprogram (E)
9807                  and then
9808                    Nkind (Parent (Parent (E))) in
9809                      N_Formal_Subprogram_Declaration);
9810       end if;
9811    end Is_Generic_Formal;
9812
9813    ---------------------
9814    -- Is_In_Main_Unit --
9815    ---------------------
9816
9817    function Is_In_Main_Unit (N : Node_Id) return Boolean is
9818       Unum         : constant Unit_Number_Type := Get_Source_Unit (N);
9819       Current_Unit : Node_Id;
9820
9821    begin
9822       if Unum = Main_Unit then
9823          return True;
9824
9825       --  If the current unit is a subunit then it is either the main unit or
9826       --  is being compiled as part of the main unit.
9827
9828       elsif Nkind (N) = N_Compilation_Unit then
9829          return Nkind (Unit (N)) = N_Subunit;
9830       end if;
9831
9832       Current_Unit := Parent (N);
9833       while Present (Current_Unit)
9834         and then Nkind (Current_Unit) /= N_Compilation_Unit
9835       loop
9836          Current_Unit := Parent (Current_Unit);
9837       end loop;
9838
9839       --  The instantiation node is in the main unit, or else the current node
9840       --  (perhaps as the result of nested instantiations) is in the main unit,
9841       --  or in the declaration of the main unit, which in this last case must
9842       --  be a body.
9843
9844       return Unum = Main_Unit
9845         or else Current_Unit = Cunit (Main_Unit)
9846         or else Current_Unit = Library_Unit (Cunit (Main_Unit))
9847         or else (Present (Library_Unit (Current_Unit))
9848                   and then Is_In_Main_Unit (Library_Unit (Current_Unit)));
9849    end Is_In_Main_Unit;
9850
9851    ----------------------------
9852    -- Load_Parent_Of_Generic --
9853    ----------------------------
9854
9855    procedure Load_Parent_Of_Generic (N : Node_Id; Spec : Node_Id) is
9856       Comp_Unit        : constant Node_Id := Cunit (Get_Source_Unit (Spec));
9857       Save_Style_Check : constant Boolean := Style_Check;
9858       True_Parent      : Node_Id;
9859       Inst_Node        : Node_Id;
9860       OK               : Boolean;
9861
9862    begin
9863       if not In_Same_Source_Unit (N, Spec)
9864         or else Nkind (Unit (Comp_Unit)) = N_Package_Declaration
9865         or else (Nkind (Unit (Comp_Unit)) = N_Package_Body
9866                    and then not Is_In_Main_Unit (Spec))
9867       then
9868          --  Find body of parent of spec, and analyze it. A special case arises
9869          --  when the parent is an instantiation, that is to say when we are
9870          --  currently instantiating a nested generic. In that case, there is
9871          --  no separate file for the body of the enclosing instance. Instead,
9872          --  the enclosing body must be instantiated as if it were a pending
9873          --  instantiation, in order to produce the body for the nested generic
9874          --  we require now. Note that in that case the generic may be defined
9875          --  in a package body, the instance defined in the same package body,
9876          --  and the original enclosing body may not be in the main unit.
9877
9878          True_Parent := Parent (Spec);
9879          Inst_Node   := Empty;
9880
9881          while Present (True_Parent)
9882            and then Nkind (True_Parent) /= N_Compilation_Unit
9883          loop
9884             if Nkind (True_Parent) = N_Package_Declaration
9885               and then
9886                 Nkind (Original_Node (True_Parent)) = N_Package_Instantiation
9887             then
9888                --  Parent is a compilation unit that is an instantiation.
9889                --  Instantiation node has been replaced with package decl.
9890
9891                Inst_Node := Original_Node (True_Parent);
9892                exit;
9893
9894             elsif Nkind (True_Parent) = N_Package_Declaration
9895               and then Present (Generic_Parent (Specification (True_Parent)))
9896               and then Nkind (Parent (True_Parent)) /= N_Compilation_Unit
9897             then
9898                --  Parent is an instantiation within another specification.
9899                --  Declaration for instance has been inserted before original
9900                --  instantiation node. A direct link would be preferable?
9901
9902                Inst_Node := Next (True_Parent);
9903
9904                while Present (Inst_Node)
9905                  and then Nkind (Inst_Node) /= N_Package_Instantiation
9906                loop
9907                   Next (Inst_Node);
9908                end loop;
9909
9910                --  If the instance appears within a generic, and the generic
9911                --  unit is defined within a formal package of the enclosing
9912                --  generic, there is no generic body available, and none
9913                --  needed. A more precise test should be used ???
9914
9915                if No (Inst_Node) then
9916                   return;
9917                end if;
9918
9919                exit;
9920             else
9921                True_Parent := Parent (True_Parent);
9922             end if;
9923          end loop;
9924
9925          --  Case where we are currently instantiating a nested generic
9926
9927          if Present (Inst_Node) then
9928             if Nkind (Parent (True_Parent)) = N_Compilation_Unit then
9929
9930                --  Instantiation node and declaration of instantiated package
9931                --  were exchanged when only the declaration was needed.
9932                --  Restore instantiation node before proceeding with body.
9933
9934                Set_Unit (Parent (True_Parent), Inst_Node);
9935             end if;
9936
9937             --  Now complete instantiation of enclosing body, if it appears
9938             --  in some other unit. If it appears in the current unit, the
9939             --  body will have been instantiated already.
9940
9941             if No (Corresponding_Body (Instance_Spec (Inst_Node))) then
9942
9943                --  We need to determine the expander mode to instantiate the
9944                --  enclosing body. Because the generic body we need may use
9945                --  global entities declared in the enclosing package (including
9946                --  aggregates) it is in general necessary to compile this body
9947                --  with expansion enabled. The exception is if we are within a
9948                --  generic package, in which case the usual generic rule
9949                --  applies.
9950
9951                declare
9952                   Exp_Status : Boolean := True;
9953                   Scop       : Entity_Id;
9954
9955                begin
9956                   --  Loop through scopes looking for generic package
9957
9958                   Scop := Scope (Defining_Entity (Instance_Spec (Inst_Node)));
9959                   while Present (Scop)
9960                     and then Scop /= Standard_Standard
9961                   loop
9962                      if Ekind (Scop) = E_Generic_Package then
9963                         Exp_Status := False;
9964                         exit;
9965                      end if;
9966
9967                      Scop := Scope (Scop);
9968                   end loop;
9969
9970                   Instantiate_Package_Body
9971                     (Pending_Body_Info'(
9972                        Inst_Node, True_Parent, Exp_Status,
9973                          Get_Code_Unit (Sloc (Inst_Node))));
9974                end;
9975             end if;
9976
9977          --  Case where we are not instantiating a nested generic
9978
9979          else
9980             Opt.Style_Check := False;
9981             Expander_Mode_Save_And_Set (True);
9982             Load_Needed_Body (Comp_Unit, OK);
9983             Opt.Style_Check := Save_Style_Check;
9984             Expander_Mode_Restore;
9985
9986             if not OK
9987               and then Unit_Requires_Body (Defining_Entity (Spec))
9988             then
9989                declare
9990                   Bname : constant Unit_Name_Type :=
9991                             Get_Body_Name (Get_Unit_Name (Unit (Comp_Unit)));
9992
9993                begin
9994                   Error_Msg_Unit_1 := Bname;
9995                   Error_Msg_N ("this instantiation requires$!", N);
9996                   Error_Msg_File_1 := Get_File_Name (Bname, Subunit => False);
9997                   Error_Msg_N ("\but file{ was not found!", N);
9998                   raise Unrecoverable_Error;
9999                end;
10000             end if;
10001          end if;
10002       end if;
10003
10004       --  If loading parent of the generic caused an instantiation circularity,
10005       --  we abandon compilation at this point, because otherwise in some cases
10006       --  we get into trouble with infinite recursions after this point.
10007
10008       if Circularity_Detected then
10009          raise Unrecoverable_Error;
10010       end if;
10011    end Load_Parent_Of_Generic;
10012
10013    -----------------------
10014    -- Move_Freeze_Nodes --
10015    -----------------------
10016
10017    procedure Move_Freeze_Nodes
10018      (Out_Of : Entity_Id;
10019       After  : Node_Id;
10020       L      : List_Id)
10021    is
10022       Decl      : Node_Id;
10023       Next_Decl : Node_Id;
10024       Next_Node : Node_Id := After;
10025       Spec      : Node_Id;
10026
10027       function Is_Outer_Type (T : Entity_Id) return Boolean;
10028       --  Check whether entity is declared in a scope external to that
10029       --  of the generic unit.
10030
10031       -------------------
10032       -- Is_Outer_Type --
10033       -------------------
10034
10035       function Is_Outer_Type (T : Entity_Id) return Boolean is
10036          Scop : Entity_Id := Scope (T);
10037
10038       begin
10039          if Scope_Depth (Scop) < Scope_Depth (Out_Of) then
10040             return True;
10041
10042          else
10043             while Scop /= Standard_Standard loop
10044                if Scop = Out_Of then
10045                   return False;
10046                else
10047                   Scop := Scope (Scop);
10048                end if;
10049             end loop;
10050
10051             return True;
10052          end if;
10053       end Is_Outer_Type;
10054
10055    --  Start of processing for Move_Freeze_Nodes
10056
10057    begin
10058       if No (L) then
10059          return;
10060       end if;
10061
10062       --  First remove the freeze nodes that may appear before all other
10063       --  declarations.
10064
10065       Decl := First (L);
10066       while Present (Decl)
10067         and then Nkind (Decl) = N_Freeze_Entity
10068         and then Is_Outer_Type (Entity (Decl))
10069       loop
10070          Decl := Remove_Head (L);
10071          Insert_After (Next_Node, Decl);
10072          Set_Analyzed (Decl, False);
10073          Next_Node := Decl;
10074          Decl := First (L);
10075       end loop;
10076
10077       --  Next scan the list of declarations and remove each freeze node that
10078       --  appears ahead of the current node.
10079
10080       while Present (Decl) loop
10081          while Present (Next (Decl))
10082            and then Nkind (Next (Decl)) = N_Freeze_Entity
10083            and then Is_Outer_Type (Entity (Next (Decl)))
10084          loop
10085             Next_Decl := Remove_Next (Decl);
10086             Insert_After (Next_Node, Next_Decl);
10087             Set_Analyzed (Next_Decl, False);
10088             Next_Node := Next_Decl;
10089          end loop;
10090
10091          --  If the declaration is a nested package or concurrent type, then
10092          --  recurse. Nested generic packages will have been processed from the
10093          --  inside out.
10094
10095          if Nkind (Decl) = N_Package_Declaration then
10096             Spec := Specification (Decl);
10097
10098          elsif Nkind (Decl) = N_Task_Type_Declaration then
10099             Spec := Task_Definition (Decl);
10100
10101          elsif Nkind (Decl) = N_Protected_Type_Declaration then
10102             Spec := Protected_Definition (Decl);
10103
10104          else
10105             Spec := Empty;
10106          end if;
10107
10108          if Present (Spec) then
10109             Move_Freeze_Nodes (Out_Of, Next_Node,
10110               Visible_Declarations (Spec));
10111             Move_Freeze_Nodes (Out_Of, Next_Node,
10112               Private_Declarations (Spec));
10113          end if;
10114
10115          Next (Decl);
10116       end loop;
10117    end Move_Freeze_Nodes;
10118
10119    ----------------
10120    -- Next_Assoc --
10121    ----------------
10122
10123    function Next_Assoc (E : Assoc_Ptr) return Assoc_Ptr is
10124    begin
10125       return Generic_Renamings.Table (E).Next_In_HTable;
10126    end Next_Assoc;
10127
10128    ------------------------
10129    -- Preanalyze_Actuals --
10130    ------------------------
10131
10132    procedure Pre_Analyze_Actuals (N : Node_Id) is
10133       Assoc : Node_Id;
10134       Act   : Node_Id;
10135       Errs  : constant Int := Serious_Errors_Detected;
10136
10137    begin
10138       Assoc := First (Generic_Associations (N));
10139       while Present (Assoc) loop
10140          if Nkind (Assoc) /= N_Others_Choice then
10141             Act := Explicit_Generic_Actual_Parameter (Assoc);
10142
10143             --  Within a nested instantiation, a defaulted actual is an empty
10144             --  association, so nothing to analyze. If the subprogram actual
10145             --  isan attribute, analyze prefix only, because actual is not a
10146             --  complete attribute reference.
10147
10148             --  If actual is an allocator, analyze expression only. The full
10149             --  analysis can generate code, and if instance is a compilation
10150             --  unit we have to wait until the package instance is installed
10151             --  to have a proper place to insert this code.
10152
10153             --  String literals may be operators, but at this point we do not
10154             --  know whether the actual is a formal subprogram or a string.
10155
10156             if No (Act) then
10157                null;
10158
10159             elsif Nkind (Act) = N_Attribute_Reference then
10160                Analyze (Prefix (Act));
10161
10162             elsif Nkind (Act) = N_Explicit_Dereference then
10163                Analyze (Prefix (Act));
10164
10165             elsif Nkind (Act) = N_Allocator then
10166                declare
10167                   Expr : constant Node_Id := Expression (Act);
10168
10169                begin
10170                   if Nkind (Expr) = N_Subtype_Indication then
10171                      Analyze (Subtype_Mark (Expr));
10172
10173                      --  Analyze separately each discriminant constraint,
10174                      --  when given with a named association.
10175
10176                      declare
10177                         Constr : Node_Id;
10178
10179                      begin
10180                         Constr := First (Constraints (Constraint (Expr)));
10181                         while Present (Constr) loop
10182                            if Nkind (Constr) = N_Discriminant_Association then
10183                               Analyze (Expression (Constr));
10184                            else
10185                               Analyze (Constr);
10186                            end if;
10187
10188                            Next (Constr);
10189                         end loop;
10190                      end;
10191
10192                   else
10193                      Analyze (Expr);
10194                   end if;
10195                end;
10196
10197             elsif Nkind (Act) /= N_Operator_Symbol then
10198                Analyze (Act);
10199             end if;
10200
10201             if Errs /= Serious_Errors_Detected then
10202                Abandon_Instantiation (Act);
10203             end if;
10204          end if;
10205
10206          Next (Assoc);
10207       end loop;
10208    end Pre_Analyze_Actuals;
10209
10210    -------------------
10211    -- Remove_Parent --
10212    -------------------
10213
10214    procedure Remove_Parent (In_Body : Boolean := False) is
10215       S      : Entity_Id := Current_Scope;
10216       E      : Entity_Id;
10217       P      : Entity_Id;
10218       Hidden : Elmt_Id;
10219
10220    begin
10221       --  After child instantiation is complete, remove from scope stack the
10222       --  extra copy of the current scope, and then remove parent instances.
10223
10224       if not In_Body then
10225          Pop_Scope;
10226
10227          while Current_Scope /= S loop
10228             P := Current_Scope;
10229             End_Package_Scope (Current_Scope);
10230
10231             if In_Open_Scopes (P) then
10232                E := First_Entity (P);
10233
10234                while Present (E) loop
10235                   Set_Is_Immediately_Visible (E, True);
10236                   Next_Entity (E);
10237                end loop;
10238
10239                if Is_Generic_Instance (Current_Scope)
10240                  and then P /= Current_Scope
10241                then
10242                   --  We are within an instance of some sibling. Retain
10243                   --  visibility of parent, for proper subsequent cleanup,
10244                   --  and reinstall private declarations as well.
10245
10246                   Set_In_Private_Part (P);
10247                   Install_Private_Declarations (P);
10248                end if;
10249
10250             --  If the ultimate parent is a top-level unit recorded in
10251             --  Instance_Parent_Unit, then reset its visibility to what
10252             --  it was before instantiation. (It's not clear what the
10253             --  purpose is of testing whether Scope (P) is In_Open_Scopes,
10254             --  but that test was present before the ultimate parent test
10255             --  was added.???)
10256
10257             elsif not In_Open_Scopes (Scope (P))
10258               or else (P = Instance_Parent_Unit
10259                         and then not Parent_Unit_Visible)
10260             then
10261                Set_Is_Immediately_Visible (P, False);
10262             end if;
10263          end loop;
10264
10265          --  Reset visibility of entities in the enclosing scope
10266
10267          Set_Is_Hidden_Open_Scope (Current_Scope, False);
10268          Hidden := First_Elmt (Hidden_Entities);
10269
10270          while Present (Hidden) loop
10271             Set_Is_Immediately_Visible (Node (Hidden), True);
10272             Next_Elmt (Hidden);
10273          end loop;
10274
10275       else
10276          --  Each body is analyzed separately, and there is no context
10277          --  that needs preserving from one body instance to the next,
10278          --  so remove all parent scopes that have been installed.
10279
10280          while Present (S) loop
10281             End_Package_Scope (S);
10282             Set_Is_Immediately_Visible (S, False);
10283             S := Current_Scope;
10284             exit when S = Standard_Standard;
10285          end loop;
10286       end if;
10287    end Remove_Parent;
10288
10289    -----------------
10290    -- Restore_Env --
10291    -----------------
10292
10293    procedure Restore_Env is
10294       Saved : Instance_Env renames Instance_Envs.Table (Instance_Envs.Last);
10295
10296    begin
10297       if No (Current_Instantiated_Parent.Act_Id) then
10298
10299          --  Restore environment after subprogram inlining
10300
10301          Restore_Private_Views (Empty);
10302       end if;
10303
10304       Current_Instantiated_Parent  := Saved.Instantiated_Parent;
10305       Exchanged_Views              := Saved.Exchanged_Views;
10306       Hidden_Entities              := Saved.Hidden_Entities;
10307       Current_Sem_Unit             := Saved.Current_Sem_Unit;
10308       Parent_Unit_Visible          := Saved.Parent_Unit_Visible;
10309       Instance_Parent_Unit         := Saved.Instance_Parent_Unit;
10310
10311       Restore_Opt_Config_Switches (Saved.Switches);
10312
10313       Instance_Envs.Decrement_Last;
10314    end Restore_Env;
10315
10316    ---------------------------
10317    -- Restore_Private_Views --
10318    ---------------------------
10319
10320    procedure Restore_Private_Views
10321      (Pack_Id    : Entity_Id;
10322       Is_Package : Boolean := True)
10323    is
10324       M        : Elmt_Id;
10325       E        : Entity_Id;
10326       Typ      : Entity_Id;
10327       Dep_Elmt : Elmt_Id;
10328       Dep_Typ  : Node_Id;
10329
10330       procedure Restore_Nested_Formal (Formal : Entity_Id);
10331       --  Hide the generic formals of formal packages declared with box
10332       --  which were reachable in the current instantiation.
10333
10334       ---------------------------
10335       -- Restore_Nested_Formal --
10336       ---------------------------
10337
10338       procedure Restore_Nested_Formal (Formal : Entity_Id) is
10339          Ent : Entity_Id;
10340
10341       begin
10342          if Present (Renamed_Object (Formal))
10343            and then Denotes_Formal_Package (Renamed_Object (Formal), True)
10344          then
10345             return;
10346
10347          elsif Present (Associated_Formal_Package (Formal)) then
10348
10349             Ent := First_Entity (Formal);
10350             while Present (Ent) loop
10351                exit when Ekind (Ent) = E_Package
10352                  and then Renamed_Entity (Ent) = Renamed_Entity (Formal);
10353
10354                Set_Is_Hidden (Ent);
10355                Set_Is_Potentially_Use_Visible (Ent, False);
10356
10357                --  If package, then recurse
10358
10359                if Ekind (Ent) = E_Package then
10360                   Restore_Nested_Formal (Ent);
10361                end if;
10362
10363                Next_Entity (Ent);
10364             end loop;
10365          end if;
10366       end Restore_Nested_Formal;
10367
10368    --  Start of processing for Restore_Private_Views
10369
10370    begin
10371       M := First_Elmt (Exchanged_Views);
10372       while Present (M) loop
10373          Typ := Node (M);
10374
10375          --  Subtypes of types whose views have been exchanged, and that
10376          --  are defined within the instance, were not on the list of
10377          --  Private_Dependents on entry to the instance, so they have to
10378          --  be exchanged explicitly now, in order to remain consistent with
10379          --  the view of the parent type.
10380
10381          if Ekind (Typ) = E_Private_Type
10382            or else Ekind (Typ) = E_Limited_Private_Type
10383            or else Ekind (Typ) = E_Record_Type_With_Private
10384          then
10385             Dep_Elmt := First_Elmt (Private_Dependents (Typ));
10386             while Present (Dep_Elmt) loop
10387                Dep_Typ := Node (Dep_Elmt);
10388
10389                if Scope (Dep_Typ) = Pack_Id
10390                  and then Present (Full_View (Dep_Typ))
10391                then
10392                   Replace_Elmt (Dep_Elmt, Full_View (Dep_Typ));
10393                   Exchange_Declarations (Dep_Typ);
10394                end if;
10395
10396                Next_Elmt (Dep_Elmt);
10397             end loop;
10398          end if;
10399
10400          Exchange_Declarations (Node (M));
10401          Next_Elmt (M);
10402       end loop;
10403
10404       if No (Pack_Id) then
10405          return;
10406       end if;
10407
10408       --  Make the generic formal parameters private, and make the formal
10409       --  types into subtypes of the actuals again.
10410
10411       E := First_Entity (Pack_Id);
10412       while Present (E) loop
10413          Set_Is_Hidden (E, True);
10414
10415          if Is_Type (E)
10416            and then Nkind (Parent (E)) = N_Subtype_Declaration
10417          then
10418             Set_Is_Generic_Actual_Type (E, False);
10419
10420             --  An unusual case of aliasing: the actual may also be directly
10421             --  visible in the generic, and be private there, while it is fully
10422             --  visible in the context of the instance. The internal subtype is
10423             --  private in the instance, but has full visibility like its
10424             --  parent in the enclosing scope. This enforces the invariant that
10425             --  the privacy status of all private dependents of a type coincide
10426             --  with that of the parent type. This can only happen when a
10427             --  generic child unit is instantiated within sibling.
10428
10429             if Is_Private_Type (E)
10430               and then not Is_Private_Type (Etype (E))
10431             then
10432                Exchange_Declarations (E);
10433             end if;
10434
10435          elsif Ekind (E) = E_Package then
10436
10437             --  The end of the renaming list is the renaming of the generic
10438             --  package itself. If the instance is a subprogram, all entities
10439             --  in the corresponding package are renamings. If this entity is
10440             --  a formal package, make its own formals private as well. The
10441             --  actual in this case is itself the renaming of an instantation.
10442             --  If the entity is not a package renaming, it is the entity
10443             --  created to validate formal package actuals: ignore.
10444
10445             --  If the actual is itself a formal package for the enclosing
10446             --  generic, or the actual for such a formal package, it remains
10447             --  visible on exit from the instance, and therefore nothing
10448             --  needs to be done either, except to keep it accessible.
10449
10450             if Is_Package
10451               and then Renamed_Object (E) = Pack_Id
10452             then
10453                exit;
10454
10455             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
10456                null;
10457
10458             elsif Denotes_Formal_Package (Renamed_Object (E), True) then
10459                Set_Is_Hidden (E, False);
10460
10461             else
10462                declare
10463                   Act_P : constant Entity_Id := Renamed_Object (E);
10464                   Id    : Entity_Id;
10465
10466                begin
10467                   Id := First_Entity (Act_P);
10468                   while Present (Id)
10469                     and then Id /= First_Private_Entity (Act_P)
10470                   loop
10471                      exit when Ekind (Id) = E_Package
10472                                  and then Renamed_Object (Id) = Act_P;
10473
10474                      Set_Is_Hidden (Id, True);
10475                      Set_Is_Potentially_Use_Visible (Id, In_Use (Act_P));
10476
10477                      if Ekind (Id) = E_Package then
10478                         Restore_Nested_Formal (Id);
10479                      end if;
10480
10481                      Next_Entity (Id);
10482                   end loop;
10483                end;
10484             end if;
10485          end if;
10486
10487          Next_Entity (E);
10488       end loop;
10489    end Restore_Private_Views;
10490
10491    --------------
10492    -- Save_Env --
10493    --------------
10494
10495    procedure Save_Env
10496      (Gen_Unit : Entity_Id;
10497       Act_Unit : Entity_Id)
10498    is
10499    begin
10500       Init_Env;
10501       Set_Instance_Env (Gen_Unit, Act_Unit);
10502    end Save_Env;
10503
10504    ----------------------------
10505    -- Save_Global_References --
10506    ----------------------------
10507
10508    procedure Save_Global_References (N : Node_Id) is
10509       Gen_Scope : Entity_Id;
10510       E         : Entity_Id;
10511       N2        : Node_Id;
10512
10513       function Is_Global (E : Entity_Id) return Boolean;
10514       --  Check whether entity is defined outside of generic unit. Examine the
10515       --  scope of an entity, and the scope of the scope, etc, until we find
10516       --  either Standard, in which case the entity is global, or the generic
10517       --  unit itself, which indicates that the entity is local. If the entity
10518       --  is the generic unit itself, as in the case of a recursive call, or
10519       --  the enclosing generic unit, if different from the current scope, then
10520       --  it is local as well, because it will be replaced at the point of
10521       --  instantiation. On the other hand, if it is a reference to a child
10522       --  unit of a common ancestor, which appears in an instantiation, it is
10523       --  global because it is used to denote a specific compilation unit at
10524       --  the time the instantiations will be analyzed.
10525
10526       procedure Reset_Entity (N : Node_Id);
10527       --  Save semantic information on global entity, so that it is not
10528       --  resolved again at instantiation time.
10529
10530       procedure Save_Entity_Descendants (N : Node_Id);
10531       --  Apply Save_Global_References to the two syntactic descendants of
10532       --  non-terminal nodes that carry an Associated_Node and are processed
10533       --  through Reset_Entity. Once the global entity (if any) has been
10534       --  captured together with its type, only two syntactic descendants need
10535       --  to be traversed to complete the processing of the tree rooted at N.
10536       --  This applies to Selected_Components, Expanded_Names, and to Operator
10537       --  nodes. N can also be a character literal, identifier, or operator
10538       --  symbol node, but the call has no effect in these cases.
10539
10540       procedure Save_Global_Defaults (N1, N2 : Node_Id);
10541       --  Default actuals in nested instances must be handled specially
10542       --  because there is no link to them from the original tree. When an
10543       --  actual subprogram is given by a default, we add an explicit generic
10544       --  association for it in the instantiation node. When we save the
10545       --  global references on the name of the instance, we recover the list
10546       --  of generic associations, and add an explicit one to the original
10547       --  generic tree, through which a global actual can be preserved.
10548       --  Similarly, if a child unit is instantiated within a sibling, in the
10549       --  context of the parent, we must preserve the identifier of the parent
10550       --  so that it can be properly resolved in a subsequent instantiation.
10551
10552       procedure Save_Global_Descendant (D : Union_Id);
10553       --  Apply Save_Global_References recursively to the descendents of the
10554       --  current node.
10555
10556       procedure Save_References (N : Node_Id);
10557       --  This is the recursive procedure that does the work, once the
10558       --  enclosing generic scope has been established.
10559
10560       ---------------
10561       -- Is_Global --
10562       ---------------
10563
10564       function Is_Global (E : Entity_Id) return Boolean is
10565          Se  : Entity_Id := Scope (E);
10566
10567          function Is_Instance_Node (Decl : Node_Id) return Boolean;
10568          --  Determine whether the parent node of a reference to a child unit
10569          --  denotes an instantiation or a formal package, in which case the
10570          --  reference to the child unit is global, even if it appears within
10571          --  the current scope (e.g. when the instance appears within the body
10572          --  of an ancestor).
10573
10574          ----------------------
10575          -- Is_Instance_Node --
10576          ----------------------
10577
10578          function Is_Instance_Node (Decl : Node_Id) return Boolean is
10579          begin
10580             return (Nkind (Decl) in N_Generic_Instantiation
10581               or else
10582                 Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration);
10583          end Is_Instance_Node;
10584
10585       --  Start of processing for Is_Global
10586
10587       begin
10588          if E = Gen_Scope then
10589             return False;
10590
10591          elsif E = Standard_Standard then
10592             return True;
10593
10594          elsif Is_Child_Unit (E)
10595            and then (Is_Instance_Node (Parent (N2))
10596              or else (Nkind (Parent (N2)) = N_Expanded_Name
10597                        and then N2 = Selector_Name (Parent (N2))
10598                        and then Is_Instance_Node (Parent (Parent (N2)))))
10599          then
10600             return True;
10601
10602          else
10603             while Se /= Gen_Scope loop
10604                if Se = Standard_Standard then
10605                   return True;
10606                else
10607                   Se := Scope (Se);
10608                end if;
10609             end loop;
10610
10611             return False;
10612          end if;
10613       end Is_Global;
10614
10615       ------------------
10616       -- Reset_Entity --
10617       ------------------
10618
10619       procedure Reset_Entity (N : Node_Id) is
10620
10621          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id);
10622          --  The type of N2 is global to the generic unit. Save the
10623          --  type in the generic node.
10624
10625          function Top_Ancestor (E : Entity_Id) return Entity_Id;
10626          --  Find the ultimate ancestor of the current unit. If it is
10627          --  not a generic unit, then the name of the current unit
10628          --  in the prefix of an expanded name must be replaced with
10629          --  its generic homonym to ensure that it will be properly
10630          --  resolved in an instance.
10631
10632          ---------------------
10633          -- Set_Global_Type --
10634          ---------------------
10635
10636          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id) is
10637             Typ : constant Entity_Id := Etype (N2);
10638
10639          begin
10640             Set_Etype (N, Typ);
10641
10642             if Entity (N) /= N2
10643               and then Has_Private_View (Entity (N))
10644             then
10645                --  If the entity of N is not the associated node, this is
10646                --  a nested generic and it has an associated node as well,
10647                --  whose type is already the full view (see below). Indicate
10648                --  that the original node has a private view.
10649
10650                Set_Has_Private_View (N);
10651             end if;
10652
10653             --  If not a private type, nothing else to do
10654
10655             if not Is_Private_Type (Typ) then
10656                if Is_Array_Type (Typ)
10657                  and then Is_Private_Type (Component_Type (Typ))
10658                then
10659                   Set_Has_Private_View (N);
10660                end if;
10661
10662             --  If it is a derivation of a private type in a context where
10663             --  no full view is needed, nothing to do either.
10664
10665             elsif No (Full_View (Typ)) and then Typ /= Etype (Typ) then
10666                null;
10667
10668             --  Otherwise mark the type for flipping and use the full_view
10669             --  when available.
10670
10671             else
10672                Set_Has_Private_View (N);
10673
10674                if Present (Full_View (Typ)) then
10675                   Set_Etype (N2, Full_View (Typ));
10676                end if;
10677             end if;
10678          end Set_Global_Type;
10679
10680          ------------------
10681          -- Top_Ancestor --
10682          ------------------
10683
10684          function Top_Ancestor (E : Entity_Id) return Entity_Id is
10685             Par : Entity_Id := E;
10686
10687          begin
10688             while Is_Child_Unit (Par) loop
10689                Par := Scope (Par);
10690             end loop;
10691
10692             return Par;
10693          end Top_Ancestor;
10694
10695       --  Start of processing for Reset_Entity
10696
10697       begin
10698          N2 := Get_Associated_Node (N);
10699          E := Entity (N2);
10700
10701          if Present (E) then
10702             if Is_Global (E) then
10703                Set_Global_Type (N, N2);
10704
10705             elsif Nkind (N) = N_Op_Concat
10706               and then Is_Generic_Type (Etype (N2))
10707               and then
10708                (Base_Type (Etype (Right_Opnd (N2))) = Etype (N2)
10709                   or else Base_Type (Etype (Left_Opnd (N2))) = Etype (N2))
10710               and then Is_Intrinsic_Subprogram (E)
10711             then
10712                null;
10713
10714             else
10715                --  Entity is local. Mark generic node as unresolved.
10716                --  Note that now it does not have an entity.
10717
10718                Set_Associated_Node (N, Empty);
10719                Set_Etype  (N, Empty);
10720             end if;
10721
10722             if Nkind (Parent (N)) in N_Generic_Instantiation
10723               and then N = Name (Parent (N))
10724             then
10725                Save_Global_Defaults (Parent (N), Parent (N2));
10726             end if;
10727
10728          elsif Nkind (Parent (N)) = N_Selected_Component
10729            and then Nkind (Parent (N2)) = N_Expanded_Name
10730          then
10731             if Is_Global (Entity (Parent (N2))) then
10732                Change_Selected_Component_To_Expanded_Name (Parent (N));
10733                Set_Associated_Node (Parent (N), Parent (N2));
10734                Set_Global_Type (Parent (N), Parent (N2));
10735                Save_Entity_Descendants (N);
10736
10737             --  If this is a reference to the current generic entity, replace
10738             --  by the name of the generic homonym of the current package. This
10739             --  is because in an instantiation Par.P.Q will not resolve to the
10740             --  name of the instance, whose enclosing scope is not necessarily
10741             --  Par. We use the generic homonym rather that the name of the
10742             --  generic itself, because it may be hidden by a local
10743             --  declaration.
10744
10745             elsif In_Open_Scopes (Entity (Parent (N2)))
10746               and then not
10747                 Is_Generic_Unit (Top_Ancestor (Entity (Prefix (Parent (N2)))))
10748             then
10749                if Ekind (Entity (Parent (N2))) = E_Generic_Package then
10750                   Rewrite (Parent (N),
10751                     Make_Identifier (Sloc (N),
10752                       Chars =>
10753                         Chars (Generic_Homonym (Entity (Parent (N2))))));
10754                else
10755                   Rewrite (Parent (N),
10756                     Make_Identifier (Sloc (N),
10757                       Chars => Chars (Selector_Name (Parent (N2)))));
10758                end if;
10759             end if;
10760
10761             if Nkind (Parent (Parent (N))) in N_Generic_Instantiation
10762               and then Parent (N) = Name (Parent (Parent (N)))
10763             then
10764                Save_Global_Defaults
10765                  (Parent (Parent (N)), Parent (Parent ((N2))));
10766             end if;
10767
10768          --  A selected component may denote a static constant that has been
10769          --  folded. Make the same replacement in original tree.
10770
10771          elsif Nkind (Parent (N)) = N_Selected_Component
10772            and then (Nkind (Parent (N2)) = N_Integer_Literal
10773                       or else Nkind (Parent (N2)) = N_Real_Literal)
10774          then
10775             Rewrite (Parent (N),
10776               New_Copy (Parent (N2)));
10777             Set_Analyzed (Parent (N), False);
10778
10779          --  A selected component may be transformed into a parameterless
10780          --  function call. If the called entity is global, rewrite the node
10781          --  appropriately, i.e. as an extended name for the global entity.
10782
10783          elsif Nkind (Parent (N)) = N_Selected_Component
10784            and then Nkind (Parent (N2)) = N_Function_Call
10785            and then N = Selector_Name (Parent (N))
10786          then
10787             if No (Parameter_Associations (Parent (N2))) then
10788                if Is_Global (Entity (Name (Parent (N2)))) then
10789                   Change_Selected_Component_To_Expanded_Name (Parent (N));
10790                   Set_Associated_Node (Parent (N), Name (Parent (N2)));
10791                   Set_Global_Type (Parent (N), Name (Parent (N2)));
10792                   Save_Entity_Descendants (N);
10793
10794                else
10795                   Set_Associated_Node (N, Empty);
10796                   Set_Etype (N, Empty);
10797                end if;
10798
10799             --  In Ada 2005, X.F may be a call to a primitive operation,
10800             --  rewritten as F (X). This rewriting will be done again in an
10801             --  instance, so keep the original node. Global entities will be
10802             --  captured as for other constructs.
10803
10804             else
10805                null;
10806             end if;
10807
10808          --  Entity is local. Reset in generic unit, so that node is resolved
10809          --  anew at the point of instantiation.
10810
10811          else
10812             Set_Associated_Node (N, Empty);
10813             Set_Etype (N, Empty);
10814          end if;
10815       end Reset_Entity;
10816
10817       -----------------------------
10818       -- Save_Entity_Descendants --
10819       -----------------------------
10820
10821       procedure Save_Entity_Descendants (N : Node_Id) is
10822       begin
10823          case Nkind (N) is
10824             when N_Binary_Op =>
10825                Save_Global_Descendant (Union_Id (Left_Opnd (N)));
10826                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
10827
10828             when N_Unary_Op =>
10829                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
10830
10831             when N_Expanded_Name | N_Selected_Component =>
10832                Save_Global_Descendant (Union_Id (Prefix (N)));
10833                Save_Global_Descendant (Union_Id (Selector_Name (N)));
10834
10835             when N_Identifier | N_Character_Literal | N_Operator_Symbol =>
10836                null;
10837
10838             when others =>
10839                raise Program_Error;
10840          end case;
10841       end Save_Entity_Descendants;
10842
10843       --------------------------
10844       -- Save_Global_Defaults --
10845       --------------------------
10846
10847       procedure Save_Global_Defaults (N1, N2 : Node_Id) is
10848          Loc    : constant Source_Ptr := Sloc (N1);
10849          Assoc2 : constant List_Id    := Generic_Associations (N2);
10850          Gen_Id : constant Entity_Id  := Get_Generic_Entity (N2);
10851          Assoc1 : List_Id;
10852          Act1   : Node_Id;
10853          Act2   : Node_Id;
10854          Def    : Node_Id;
10855          Ndec   : Node_Id;
10856          Subp   : Entity_Id;
10857          Actual : Entity_Id;
10858
10859       begin
10860          Assoc1 := Generic_Associations (N1);
10861
10862          if Present (Assoc1) then
10863             Act1 := First (Assoc1);
10864          else
10865             Act1 := Empty;
10866             Set_Generic_Associations (N1, New_List);
10867             Assoc1 := Generic_Associations (N1);
10868          end if;
10869
10870          if Present (Assoc2) then
10871             Act2 := First (Assoc2);
10872          else
10873             return;
10874          end if;
10875
10876          while Present (Act1) and then Present (Act2) loop
10877             Next (Act1);
10878             Next (Act2);
10879          end loop;
10880
10881          --  Find the associations added for default suprograms
10882
10883          if Present (Act2) then
10884             while Nkind (Act2) /= N_Generic_Association
10885               or else No (Entity (Selector_Name (Act2)))
10886               or else not Is_Overloadable (Entity (Selector_Name (Act2)))
10887             loop
10888                Next (Act2);
10889             end loop;
10890
10891             --  Add a similar association if the default is global. The
10892             --  renaming declaration for the actual has been analyzed, and
10893             --  its alias is the program it renames. Link the actual in the
10894             --  original generic tree with the node in the analyzed tree.
10895
10896             while Present (Act2) loop
10897                Subp := Entity (Selector_Name (Act2));
10898                Def  := Explicit_Generic_Actual_Parameter (Act2);
10899
10900                --  Following test is defence against rubbish errors
10901
10902                if No (Alias (Subp)) then
10903                   return;
10904                end if;
10905
10906                --  Retrieve the resolved actual from the renaming declaration
10907                --  created for the instantiated formal.
10908
10909                Actual := Entity (Name (Parent (Parent (Subp))));
10910                Set_Entity (Def, Actual);
10911                Set_Etype (Def, Etype (Actual));
10912
10913                if Is_Global (Actual) then
10914                   Ndec :=
10915                     Make_Generic_Association (Loc,
10916                       Selector_Name => New_Occurrence_Of (Subp, Loc),
10917                         Explicit_Generic_Actual_Parameter =>
10918                           New_Occurrence_Of (Actual, Loc));
10919
10920                   Set_Associated_Node
10921                     (Explicit_Generic_Actual_Parameter (Ndec), Def);
10922
10923                   Append (Ndec, Assoc1);
10924
10925                --  If there are other defaults, add a dummy association in case
10926                --  there are other defaulted formals with the same name.
10927
10928                elsif Present (Next (Act2)) then
10929                   Ndec :=
10930                     Make_Generic_Association (Loc,
10931                       Selector_Name => New_Occurrence_Of (Subp, Loc),
10932                         Explicit_Generic_Actual_Parameter => Empty);
10933
10934                   Append (Ndec, Assoc1);
10935                end if;
10936
10937                Next (Act2);
10938             end loop;
10939          end if;
10940
10941          if Nkind (Name (N1)) = N_Identifier
10942            and then Is_Child_Unit (Gen_Id)
10943            and then Is_Global (Gen_Id)
10944            and then Is_Generic_Unit (Scope (Gen_Id))
10945            and then In_Open_Scopes (Scope (Gen_Id))
10946          then
10947             --  This is an instantiation of a child unit within a sibling,
10948             --  so that the generic parent is in scope. An eventual instance
10949             --  must occur within the scope of an instance of the parent.
10950             --  Make name in instance into an expanded name, to preserve the
10951             --  identifier of the parent, so it can be resolved subsequently.
10952
10953             Rewrite (Name (N2),
10954               Make_Expanded_Name (Loc,
10955                 Chars         => Chars (Gen_Id),
10956                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
10957                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
10958             Set_Entity (Name (N2), Gen_Id);
10959
10960             Rewrite (Name (N1),
10961                Make_Expanded_Name (Loc,
10962                 Chars         => Chars (Gen_Id),
10963                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
10964                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
10965
10966             Set_Associated_Node (Name (N1), Name (N2));
10967             Set_Associated_Node (Prefix (Name (N1)), Empty);
10968             Set_Associated_Node
10969               (Selector_Name (Name (N1)), Selector_Name (Name (N2)));
10970             Set_Etype (Name (N1), Etype (Gen_Id));
10971          end if;
10972
10973       end Save_Global_Defaults;
10974
10975       ----------------------------
10976       -- Save_Global_Descendant --
10977       ----------------------------
10978
10979       procedure Save_Global_Descendant (D : Union_Id) is
10980          N1 : Node_Id;
10981
10982       begin
10983          if D in Node_Range then
10984             if D = Union_Id (Empty) then
10985                null;
10986
10987             elsif Nkind (Node_Id (D)) /= N_Compilation_Unit then
10988                Save_References (Node_Id (D));
10989             end if;
10990
10991          elsif D in List_Range then
10992             if D = Union_Id (No_List)
10993               or else Is_Empty_List (List_Id (D))
10994             then
10995                null;
10996
10997             else
10998                N1 := First (List_Id (D));
10999                while Present (N1) loop
11000                   Save_References (N1);
11001                   Next (N1);
11002                end loop;
11003             end if;
11004
11005          --  Element list or other non-node field, nothing to do
11006
11007          else
11008             null;
11009          end if;
11010       end Save_Global_Descendant;
11011
11012       ---------------------
11013       -- Save_References --
11014       ---------------------
11015
11016       --  This is the recursive procedure that does the work, once the
11017       --  enclosing generic scope has been established. We have to treat
11018       --  specially a number of node rewritings that are required by semantic
11019       --  processing and which change the kind of nodes in the generic copy:
11020       --  typically constant-folding, replacing an operator node by a string
11021       --  literal, or a selected component by an expanded name. In each of
11022       --  those cases, the transformation is propagated to the generic unit.
11023
11024       procedure Save_References (N : Node_Id) is
11025       begin
11026          if N = Empty then
11027             null;
11028
11029          elsif Nkind (N) = N_Character_Literal
11030            or else Nkind (N) = N_Operator_Symbol
11031          then
11032             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
11033                Reset_Entity (N);
11034
11035             elsif Nkind (N) = N_Operator_Symbol
11036               and then Nkind (Get_Associated_Node (N)) = N_String_Literal
11037             then
11038                Change_Operator_Symbol_To_String_Literal (N);
11039             end if;
11040
11041          elsif Nkind (N) in N_Op then
11042             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
11043                if Nkind (N) = N_Op_Concat then
11044                   Set_Is_Component_Left_Opnd (N,
11045                     Is_Component_Left_Opnd (Get_Associated_Node (N)));
11046
11047                   Set_Is_Component_Right_Opnd (N,
11048                     Is_Component_Right_Opnd (Get_Associated_Node (N)));
11049                end if;
11050
11051                Reset_Entity (N);
11052
11053             else
11054                --  Node may be transformed into call to a user-defined operator
11055
11056                N2 := Get_Associated_Node (N);
11057
11058                if Nkind (N2) = N_Function_Call then
11059                   E := Entity (Name (N2));
11060
11061                   if Present (E)
11062                     and then Is_Global (E)
11063                   then
11064                      Set_Etype (N, Etype (N2));
11065                   else
11066                      Set_Associated_Node (N, Empty);
11067                      Set_Etype (N, Empty);
11068                   end if;
11069
11070                elsif Nkind (N2) = N_Integer_Literal
11071                  or else Nkind (N2) = N_Real_Literal
11072                  or else Nkind (N2) = N_String_Literal
11073                then
11074                   if Present (Original_Node (N2))
11075                     and then Nkind (Original_Node (N2)) = Nkind (N)
11076                   then
11077
11078                      --  Operation was constant-folded. Whenever possible,
11079                      --  recover semantic information from unfolded node,
11080                      --  for ASIS use.
11081
11082                      Set_Associated_Node (N, Original_Node (N2));
11083
11084                      if Nkind (N) = N_Op_Concat then
11085                         Set_Is_Component_Left_Opnd (N,
11086                           Is_Component_Left_Opnd  (Get_Associated_Node (N)));
11087                         Set_Is_Component_Right_Opnd (N,
11088                           Is_Component_Right_Opnd (Get_Associated_Node (N)));
11089                      end if;
11090
11091                      Reset_Entity (N);
11092
11093                   else
11094                      --  If original node is already modified, propagate
11095                      --  constant-folding to template.
11096
11097                      Rewrite (N, New_Copy (N2));
11098                      Set_Analyzed (N, False);
11099                   end if;
11100
11101                elsif Nkind (N2) = N_Identifier
11102                  and then Ekind (Entity (N2)) = E_Enumeration_Literal
11103                then
11104                   --  Same if call was folded into a literal, but in this case
11105                   --  retain the entity to avoid spurious ambiguities if id is
11106                   --  overloaded at the point of instantiation or inlining.
11107
11108                   Rewrite (N, New_Copy (N2));
11109                   Set_Analyzed (N, False);
11110                end if;
11111             end if;
11112
11113             --  Complete the check on operands, if node has not been
11114             --  constant-folded.
11115
11116             if Nkind (N) in N_Op then
11117                Save_Entity_Descendants (N);
11118             end if;
11119
11120          elsif Nkind (N) = N_Identifier then
11121             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
11122
11123                --  If this is a discriminant reference, always save it. It is
11124                --  used in the instance to find the corresponding discriminant
11125                --  positionally rather than by name.
11126
11127                Set_Original_Discriminant
11128                  (N, Original_Discriminant (Get_Associated_Node (N)));
11129                Reset_Entity (N);
11130
11131             else
11132                N2 := Get_Associated_Node (N);
11133
11134                if Nkind (N2) = N_Function_Call then
11135                   E := Entity (Name (N2));
11136
11137                   --  Name resolves to a call to parameterless function. If
11138                   --  original entity is global, mark node as resolved.
11139
11140                   if Present (E)
11141                     and then Is_Global (E)
11142                   then
11143                      Set_Etype (N, Etype (N2));
11144                   else
11145                      Set_Associated_Node (N, Empty);
11146                      Set_Etype (N, Empty);
11147                   end if;
11148
11149                elsif
11150                  (Nkind (N2) = N_Integer_Literal
11151                     or else
11152                   Nkind (N2) = N_Real_Literal)
11153                  and then Is_Entity_Name (Original_Node (N2))
11154                then
11155                   --  Name resolves to named number that is constant-folded,
11156                   --  We must preserve the original name for ASIS use, and
11157                   --  undo the constant-folding, which will be repeated in
11158                   --  each instance.
11159
11160                   Set_Associated_Node (N, Original_Node (N2));
11161                   Reset_Entity (N);
11162
11163                elsif Nkind (N2) = N_String_Literal then
11164
11165                   --  Name resolves to string literal. Perform the same
11166                   --  replacement in generic.
11167
11168                   Rewrite (N, New_Copy (N2));
11169
11170                elsif Nkind (N2) = N_Explicit_Dereference then
11171
11172                   --  An identifier is rewritten as a dereference if it is
11173                   --  the prefix in a selected component, and it denotes an
11174                   --  access to a composite type, or a parameterless function
11175                   --  call that returns an access type.
11176
11177                   --  Check whether corresponding entity in prefix is global
11178
11179                   if Is_Entity_Name (Prefix (N2))
11180                     and then Present (Entity (Prefix (N2)))
11181                     and then Is_Global (Entity (Prefix (N2)))
11182                   then
11183                      Rewrite (N,
11184                        Make_Explicit_Dereference (Sloc (N),
11185                           Prefix => Make_Identifier (Sloc (N),
11186                             Chars => Chars (N))));
11187                      Set_Associated_Node (Prefix (N), Prefix (N2));
11188
11189                   elsif Nkind (Prefix (N2)) = N_Function_Call
11190                     and then Is_Global (Entity (Name (Prefix (N2))))
11191                   then
11192                      Rewrite (N,
11193                        Make_Explicit_Dereference (Sloc (N),
11194                           Prefix => Make_Function_Call (Sloc (N),
11195                             Name  =>
11196                               Make_Identifier (Sloc (N),
11197                               Chars => Chars (N)))));
11198
11199                      Set_Associated_Node
11200                       (Name (Prefix (N)), Name (Prefix (N2)));
11201
11202                   else
11203                      Set_Associated_Node (N, Empty);
11204                      Set_Etype (N, Empty);
11205                   end if;
11206
11207                --  The subtype mark of a nominally unconstrained object is
11208                --  rewritten as a subtype indication using the bounds of the
11209                --  expression. Recover the original subtype mark.
11210
11211                elsif Nkind (N2) = N_Subtype_Indication
11212                  and then Is_Entity_Name (Original_Node (N2))
11213                then
11214                   Set_Associated_Node (N, Original_Node (N2));
11215                   Reset_Entity (N);
11216
11217                else
11218                   null;
11219                end if;
11220             end if;
11221
11222          elsif Nkind (N) in N_Entity then
11223             null;
11224
11225          else
11226             declare
11227                Loc  : constant Source_Ptr := Sloc (N);
11228                Qual : Node_Id := Empty;
11229                Typ  : Entity_Id := Empty;
11230                Nam  : Node_Id;
11231
11232                use Atree.Unchecked_Access;
11233                --  This code section is part of implementing an untyped tree
11234                --  traversal, so it needs direct access to node fields.
11235
11236             begin
11237                if Nkind (N) = N_Aggregate
11238                     or else
11239                   Nkind (N) = N_Extension_Aggregate
11240                then
11241                   N2 := Get_Associated_Node (N);
11242
11243                   if No (N2) then
11244                      Typ := Empty;
11245                   else
11246                      Typ := Etype (N2);
11247
11248                      --  In an instance within a generic, use the name of
11249                      --  the actual and not the original generic parameter.
11250                      --  If the actual is global in the current generic it
11251                      --  must be preserved for its instantiation.
11252
11253                      if Nkind (Parent (Typ)) = N_Subtype_Declaration
11254                        and then
11255                          Present (Generic_Parent_Type (Parent (Typ)))
11256                      then
11257                         Typ := Base_Type (Typ);
11258                         Set_Etype (N2, Typ);
11259                      end if;
11260                   end if;
11261
11262                   if No (N2)
11263                     or else No (Typ)
11264                     or else not Is_Global (Typ)
11265                   then
11266                      Set_Associated_Node (N, Empty);
11267
11268                      --  If the aggregate is an actual in a call, it has been
11269                      --  resolved in the current context, to some local type.
11270                      --  The enclosing call may have been disambiguated by the
11271                      --  aggregate, and this disambiguation might fail at
11272                      --  instantiation time because the type to which the
11273                      --  aggregate did resolve is not preserved. In order to
11274                      --  preserve some of this information, we wrap the
11275                      --  aggregate in a qualified expression, using the id of
11276                      --  its type. For further disambiguation we qualify the
11277                      --  type name with its scope (if visible) because both
11278                      --  id's will have corresponding entities in an instance.
11279                      --  This resolves most of the problems with missing type
11280                      --  information on aggregates in instances.
11281
11282                      if Nkind (N2) = Nkind (N)
11283                        and then
11284                          (Nkind (Parent (N2)) = N_Procedure_Call_Statement
11285                            or else Nkind (Parent (N2)) = N_Function_Call)
11286                        and then Comes_From_Source (Typ)
11287                      then
11288                         if Is_Immediately_Visible (Scope (Typ)) then
11289                            Nam := Make_Selected_Component (Loc,
11290                              Prefix =>
11291                                Make_Identifier (Loc, Chars (Scope (Typ))),
11292                              Selector_Name =>
11293                                Make_Identifier (Loc, Chars (Typ)));
11294                         else
11295                            Nam := Make_Identifier (Loc, Chars (Typ));
11296                         end if;
11297
11298                         Qual :=
11299                           Make_Qualified_Expression (Loc,
11300                             Subtype_Mark => Nam,
11301                             Expression => Relocate_Node (N));
11302                      end if;
11303                   end if;
11304
11305                   Save_Global_Descendant (Field1 (N));
11306                   Save_Global_Descendant (Field2 (N));
11307                   Save_Global_Descendant (Field3 (N));
11308                   Save_Global_Descendant (Field5 (N));
11309
11310                   if Present (Qual) then
11311                      Rewrite (N, Qual);
11312                   end if;
11313
11314                --  All other cases than aggregates
11315
11316                else
11317                   Save_Global_Descendant (Field1 (N));
11318                   Save_Global_Descendant (Field2 (N));
11319                   Save_Global_Descendant (Field3 (N));
11320                   Save_Global_Descendant (Field4 (N));
11321                   Save_Global_Descendant (Field5 (N));
11322                end if;
11323             end;
11324          end if;
11325       end Save_References;
11326
11327    --  Start of processing for Save_Global_References
11328
11329    begin
11330       Gen_Scope := Current_Scope;
11331
11332       --  If the generic unit is a child unit, references to entities in the
11333       --  parent are treated as local, because they will be resolved anew in
11334       --  the context of the instance of the parent.
11335
11336       while Is_Child_Unit (Gen_Scope)
11337         and then Ekind (Scope (Gen_Scope)) = E_Generic_Package
11338       loop
11339          Gen_Scope := Scope (Gen_Scope);
11340       end loop;
11341
11342       Save_References (N);
11343    end Save_Global_References;
11344
11345    --------------------------------------
11346    -- Set_Copied_Sloc_For_Inlined_Body --
11347    --------------------------------------
11348
11349    procedure Set_Copied_Sloc_For_Inlined_Body (N : Node_Id; E : Entity_Id) is
11350    begin
11351       Create_Instantiation_Source (N, E, True, S_Adjustment);
11352    end Set_Copied_Sloc_For_Inlined_Body;
11353
11354    ---------------------
11355    -- Set_Instance_Of --
11356    ---------------------
11357
11358    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id) is
11359    begin
11360       Generic_Renamings.Table (Generic_Renamings.Last) := (A, B, Assoc_Null);
11361       Generic_Renamings_HTable.Set (Generic_Renamings.Last);
11362       Generic_Renamings.Increment_Last;
11363    end Set_Instance_Of;
11364
11365    --------------------
11366    -- Set_Next_Assoc --
11367    --------------------
11368
11369    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr) is
11370    begin
11371       Generic_Renamings.Table (E).Next_In_HTable := Next;
11372    end Set_Next_Assoc;
11373
11374    -------------------
11375    -- Start_Generic --
11376    -------------------
11377
11378    procedure Start_Generic is
11379    begin
11380       --  ??? I am sure more things could be factored out in this routine.
11381       --  Should probably be done at a later stage.
11382
11383       Generic_Flags.Increment_Last;
11384       Generic_Flags.Table (Generic_Flags.Last) := Inside_A_Generic;
11385       Inside_A_Generic := True;
11386
11387       Expander_Mode_Save_And_Set (False);
11388    end Start_Generic;
11389
11390    ----------------------
11391    -- Set_Instance_Env --
11392    ----------------------
11393
11394    procedure Set_Instance_Env
11395      (Gen_Unit : Entity_Id;
11396       Act_Unit : Entity_Id)
11397    is
11398    begin
11399       --  Regardless of the current mode, predefined units are analyzed in
11400       --  the most current Ada mode, and earlier version Ada checks do not
11401       --  apply to predefined units.
11402
11403       Set_Opt_Config_Switches (
11404         Is_Internal_File_Name
11405           (Fname => Unit_File_Name (Get_Source_Unit (Gen_Unit)),
11406            Renamings_Included => True),
11407         Current_Sem_Unit = Main_Unit);
11408
11409       Current_Instantiated_Parent := (Gen_Unit, Act_Unit, Assoc_Null);
11410    end Set_Instance_Env;
11411
11412    -----------------
11413    -- Switch_View --
11414    -----------------
11415
11416    procedure Switch_View (T : Entity_Id) is
11417       BT        : constant Entity_Id := Base_Type (T);
11418       Priv_Elmt : Elmt_Id := No_Elmt;
11419       Priv_Sub  : Entity_Id;
11420
11421    begin
11422       --  T may be private but its base type may have been exchanged through
11423       --  some other occurrence, in which case there is nothing to switch
11424       --  besides T itself. Note that a private dependent subtype of a private
11425       --  type might not have been switched even if the base type has been,
11426       --  because of the last branch of Check_Private_View (see comment there).
11427
11428       if not Is_Private_Type (BT) then
11429          Prepend_Elmt (Full_View (T), Exchanged_Views);
11430          Exchange_Declarations (T);
11431          return;
11432       end if;
11433
11434       Priv_Elmt := First_Elmt (Private_Dependents (BT));
11435
11436       if Present (Full_View (BT)) then
11437          Prepend_Elmt (Full_View (BT), Exchanged_Views);
11438          Exchange_Declarations (BT);
11439       end if;
11440
11441       while Present (Priv_Elmt) loop
11442          Priv_Sub := (Node (Priv_Elmt));
11443
11444          --  We avoid flipping the subtype if the Etype of its full view is
11445          --  private because this would result in a malformed subtype. This
11446          --  occurs when the Etype of the subtype full view is the full view of
11447          --  the base type (and since the base types were just switched, the
11448          --  subtype is pointing to the wrong view). This is currently the case
11449          --  for tagged record types, access types (maybe more?) and needs to
11450          --  be resolved. ???
11451
11452          if Present (Full_View (Priv_Sub))
11453            and then not Is_Private_Type (Etype (Full_View (Priv_Sub)))
11454          then
11455             Prepend_Elmt (Full_View (Priv_Sub), Exchanged_Views);
11456             Exchange_Declarations (Priv_Sub);
11457          end if;
11458
11459          Next_Elmt (Priv_Elmt);
11460       end loop;
11461    end Switch_View;
11462
11463    -----------------------------
11464    -- Valid_Default_Attribute --
11465    -----------------------------
11466
11467    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id) is
11468       Attr_Id : constant Attribute_Id :=
11469                   Get_Attribute_Id (Attribute_Name (Def));
11470       T       : constant Entity_Id := Entity (Prefix (Def));
11471       Is_Fun  : constant Boolean := (Ekind (Nam) = E_Function);
11472       F       : Entity_Id;
11473       Num_F   : Int;
11474       OK      : Boolean;
11475
11476    begin
11477       if No (T)
11478         or else T = Any_Id
11479       then
11480          return;
11481       end if;
11482
11483       Num_F := 0;
11484       F := First_Formal (Nam);
11485       while Present (F) loop
11486          Num_F := Num_F + 1;
11487          Next_Formal (F);
11488       end loop;
11489
11490       case Attr_Id is
11491          when Attribute_Adjacent |  Attribute_Ceiling   | Attribute_Copy_Sign |
11492               Attribute_Floor    |  Attribute_Fraction  | Attribute_Machine   |
11493               Attribute_Model    |  Attribute_Remainder | Attribute_Rounding  |
11494               Attribute_Unbiased_Rounding  =>
11495             OK := Is_Fun
11496                     and then Num_F = 1
11497                     and then Is_Floating_Point_Type (T);
11498
11499          when Attribute_Image    | Attribute_Pred       | Attribute_Succ |
11500               Attribute_Value    | Attribute_Wide_Image |
11501               Attribute_Wide_Value  =>
11502             OK := (Is_Fun and then Num_F = 1 and then Is_Scalar_Type (T));
11503
11504          when Attribute_Max      |  Attribute_Min  =>
11505             OK := (Is_Fun and then Num_F = 2 and then Is_Scalar_Type (T));
11506
11507          when Attribute_Input =>
11508             OK := (Is_Fun and then Num_F = 1);
11509
11510          when Attribute_Output | Attribute_Read | Attribute_Write =>
11511             OK := (not Is_Fun and then Num_F = 2);
11512
11513          when others =>
11514             OK := False;
11515       end case;
11516
11517       if not OK then
11518          Error_Msg_N ("attribute reference has wrong profile for subprogram",
11519            Def);
11520       end if;
11521    end Valid_Default_Attribute;
11522
11523 end Sem_Ch12;