OSDN Git Service

* expr.c (expand_expr): Use unsave lang hook.
[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 --                            $Revision$
10 --                                                                          --
11 --          Copyright (C) 1992-2001, Free Software Foundation, Inc.         --
12 --                                                                          --
13 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
14 -- terms of the  GNU General Public License as published  by the Free Soft- --
15 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
16 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
17 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
18 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
19 -- for  more details.  You should have  received  a copy of the GNU General --
20 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
21 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
22 -- MA 02111-1307, USA.                                                      --
23 --                                                                          --
24 -- GNAT was originally developed  by the GNAT team at  New York University. --
25 -- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
26 --                                                                          --
27 ------------------------------------------------------------------------------
28
29 with Atree;    use Atree;
30 with Einfo;    use Einfo;
31 with Elists;   use Elists;
32 with Errout;   use Errout;
33 with Expander; use Expander;
34 with Fname;    use Fname;
35 with Fname.UF; use Fname.UF;
36 with Freeze;   use Freeze;
37 with Hostparm;
38 with Inline;   use Inline;
39 with Lib;      use Lib;
40 with Lib.Load; use Lib.Load;
41 with Lib.Xref; use Lib.Xref;
42 with Nlists;   use Nlists;
43 with Nmake;    use Nmake;
44 with Opt;      use Opt;
45 with Restrict; use Restrict;
46 with Rtsfind;  use Rtsfind;
47 with Sem;      use Sem;
48 with Sem_Cat;  use Sem_Cat;
49 with Sem_Ch3;  use Sem_Ch3;
50 with Sem_Ch6;  use Sem_Ch6;
51 with Sem_Ch7;  use Sem_Ch7;
52 with Sem_Ch8;  use Sem_Ch8;
53 with Sem_Ch10; use Sem_Ch10;
54 with Sem_Ch13; use Sem_Ch13;
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 Stand;    use Stand;
62 with Sinfo;    use Sinfo;
63 with Sinfo.CN; use Sinfo.CN;
64 with Sinput;   use Sinput;
65 with Sinput.L; use Sinput.L;
66 with Snames;   use Snames;
67 with Stringt;  use Stringt;
68 with Uname;    use Uname;
69 with Table;
70 with Tbuild;   use Tbuild;
71 with Uintp;    use Uintp;
72 with Urealp;   use Urealp;
73
74 with GNAT.HTable;
75
76 package body Sem_Ch12 is
77
78    ----------------------------------------------------------
79    -- Implementation of Generic Analysis and Instantiation --
80    -----------------------------------------------------------
81
82    --  GNAT implements generics by macro expansion. No attempt is made to
83    --  share generic instantiations (for now). Analysis of a generic definition
84    --  does not perform any expansion action, but the expander must be called
85    --  on the tree for each instantiation, because the expansion may of course
86    --  depend on the generic actuals. All of this is best achieved as follows:
87    --
88    --  a) Semantic analysis of a generic unit is performed on a copy of the
89    --  tree for the generic unit. All tree modifications that follow analysis
90    --  do not affect the original tree. Links are kept between the original
91    --  tree and the copy, in order to recognize non-local references within
92    --  the generic, and propagate them to each instance (recall that name
93    --  resolution is done on the generic declaration: generics are not really
94    --  macros!). This is summarized in the following diagram:
95    --
96    --              .-----------.               .----------.
97    --              |  semantic |<--------------|  generic |
98    --              |    copy   |               |    unit  |
99    --              |           |==============>|          |
100    --              |___________|    global     |__________|
101    --                             references     |   |  |
102    --                                            |   |  |
103    --                                          .-----|--|.
104    --                                          |  .-----|---.
105    --                                          |  |  .----------.
106    --                                          |  |  |  generic |
107    --                                          |__|  |          |
108    --                                             |__| instance |
109    --                                                |__________|
110    --
111    --  b) Each instantiation copies the original tree, and inserts into it a
112    --  series of declarations that describe the mapping between generic formals
113    --  and actuals. For example, a generic In OUT parameter is an object
114    --  renaming of the corresponing actual, etc. Generic IN parameters are
115    --  constant declarations.
116    --
117    --  c) In order to give the right visibility for these renamings, we use
118    --  a different scheme for package and subprogram instantiations. For
119    --  packages, the list of renamings is inserted into the package
120    --  specification, before the visible declarations of the package. The
121    --  renamings are analyzed before any of the text of the instance, and are
122    --  thus visible at the right place. Furthermore, outside of the instance,
123    --  the generic parameters are visible and denote their corresponding
124    --  actuals.
125
126    --  For subprograms, we create a container package to hold the renamings
127    --  and the subprogram instance itself. Analysis of the package makes the
128    --  renaming declarations visible to the subprogram. After analyzing the
129    --  package, the defining entity for the subprogram is touched-up so that
130    --  it appears declared in the current scope, and not inside the container
131    --  package.
132
133    --  If the instantiation is a compilation unit, the container package is
134    --  given the same name as the subprogram instance. This ensures that
135    --  the elaboration procedure called by the binder, using the compilation
136    --  unit name, calls in fact the elaboration procedure for the package.
137
138    --  Not surprisingly, private types complicate this approach. By saving in
139    --  the original generic object the non-local references, we guarantee that
140    --  the proper entities are referenced at the point of instantiation.
141    --  However, for private types, this by itself does not insure that the
142    --  proper VIEW of the entity is used (the full type may be visible at the
143    --  point of generic definition, but not at instantiation, or vice-versa).
144    --  In  order to reference the proper view, we special-case any reference
145    --  to private types in the generic object, by saving both views, one in
146    --  the generic and one in the semantic copy. At time of instantiation, we
147    --  check whether the two views are consistent, and exchange declarations if
148    --  necessary, in order to restore the correct visibility. Similarly, if
149    --  the instance view is private when the generic view was not, we perform
150    --  the exchange. After completing the instantiation, we restore the
151    --  current visibility. The flag Has_Private_View marks identifiers in the
152    --  the generic unit that require checking.
153
154    --  Visibility within nested generic units requires special handling.
155    --  Consider the following scheme:
156    --
157    --  type Global is ...         --  outside of generic unit.
158    --  generic ...
159    --  package Outer is
160    --     ...
161    --     type Semi_Global is ... --  global to inner.
162    --
163    --     generic ...                                         -- 1
164    --     procedure inner (X1 : Global;  X2 : Semi_Global);
165    --
166    --     procedure in2 is new inner (...);                   -- 4
167    --  end Outer;
168
169    --  package New_Outer is new Outer (...);                  -- 2
170    --  procedure New_Inner is new New_Outer.Inner (...);      -- 3
171
172    --  The semantic analysis of Outer captures all occurrences of Global.
173    --  The semantic analysis of Inner (at 1) captures both occurrences of
174    --  Global and Semi_Global.
175
176    --  At point 2 (instantiation of Outer), we also produce a generic copy
177    --  of Inner, even though Inner is, at that point, not being instantiated.
178    --  (This is just part of the semantic analysis of New_Outer).
179
180    --  Critically, references to Global within Inner must be preserved, while
181    --  references to Semi_Global should not preserved, because they must now
182    --  resolve to an entity within New_Outer. To distinguish between these, we
183    --  use a global variable, Current_Instantiated_Parent, which is set when
184    --  performing a generic copy during instantiation (at 2). This variable is
185    --  used when performing a generic copy that is not an instantiation, but
186    --  that is nested within one, as the occurrence of 1 within 2. The analysis
187    --  of a nested generic only preserves references that are global to the
188    --  enclosing Current_Instantiated_Parent. We use the Scope_Depth value to
189    --  determine whether a reference is external to the given parent.
190
191    --  The instantiation at point 3 requires no special treatment. The method
192    --  works as well for further nestings of generic units, but of course the
193    --  variable Current_Instantiated_Parent must be stacked because nested
194    --  instantiations can occur, e.g. the occurrence of 4 within 2.
195
196    --  The instantiation of package and subprogram bodies is handled in a
197    --  similar manner, except that it is delayed until after semantic
198    --  analysis is complete. In this fashion complex cross-dependencies
199    --  between several package declarations and bodies containing generics
200    --  can be compiled which otherwise would diagnose spurious circularities.
201
202    --  For example, it is possible to compile two packages A and B that
203    --  have the following structure:
204
205    --    package A is                         package B is
206    --       generic ...                          generic ...
207    --       package G_A is                       package G_B is
208
209    --    with B;                              with A;
210    --    package body A is                    package body B is
211    --       package N_B is new G_B (..)          package N_A is new G_A (..)
212
213    --  The table Pending_Instantiations in package Inline is used to keep
214    --  track of body instantiations that are delayed in this manner. Inline
215    --  handles the actual calls to do the body instantiations. This activity
216    --  is part of Inline, since the processing occurs at the same point, and
217    --  for essentially the same reason, as the handling of inlined routines.
218
219    ----------------------------------------------
220    -- Detection of Instantiation Circularities --
221    ----------------------------------------------
222
223    --  If we have a chain of instantiations that is circular, this is a
224    --  static error which must be detected at compile time. The detection
225    --  of these circularities is carried out at the point that we insert
226    --  a generic instance spec or body. If there is a circularity, then
227    --  the analysis of the offending spec or body will eventually result
228    --  in trying to load the same unit again, and we detect this problem
229    --  as we analyze the package instantiation for the second time.
230
231    --  At least in some cases after we have detected the circularity, we
232    --  get into trouble if we try to keep going. The following flag is
233    --  set if a circularity is detected, and used to abandon compilation
234    --  after the messages have been posted.
235
236    Circularity_Detected : Boolean := False;
237    --  This should really be reset on encountering a new main unit, but in
238    --  practice we are not using multiple main units so it is not critical.
239
240    -----------------------
241    -- Local subprograms --
242    -----------------------
243
244    procedure Abandon_Instantiation (N : Node_Id);
245    pragma No_Return (Abandon_Instantiation);
246    --  Posts an error message "instantiation abandoned" at the indicated
247    --  node and then raises the exception Instantiation_Error to do it.
248
249    procedure Analyze_Formal_Array_Type
250      (T   : in out Entity_Id;
251       Def : Node_Id);
252    --  A formal array type is treated like an array type declaration, and
253    --  invokes Array_Type_Declaration (sem_ch3) whose first parameter is
254    --  in-out, because in the case of an anonymous type the entity is
255    --  actually created in the procedure.
256
257    --  The following procedures treat other kinds of formal parameters.
258
259    procedure Analyze_Formal_Derived_Type
260      (N   : Node_Id;
261       T   : Entity_Id;
262       Def : Node_Id);
263
264    --  All the following need comments???
265
266    procedure Analyze_Formal_Decimal_Fixed_Point_Type
267                                                 (T : Entity_Id; Def : Node_Id);
268    procedure Analyze_Formal_Discrete_Type       (T : Entity_Id; Def : Node_Id);
269    procedure Analyze_Formal_Floating_Type       (T : Entity_Id; Def : Node_Id);
270    procedure Analyze_Formal_Signed_Integer_Type (T : Entity_Id; Def : Node_Id);
271    procedure Analyze_Formal_Modular_Type        (T : Entity_Id; Def : Node_Id);
272    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
273                                                 (T : Entity_Id; Def : Node_Id);
274
275    procedure Analyze_Formal_Private_Type
276      (N   : Node_Id;
277       T   : Entity_Id;
278       Def : Node_Id);
279    --  This needs comments???
280
281    procedure Analyze_Generic_Formal_Part (N : Node_Id);
282
283    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id);
284    --  This needs comments ???
285
286    function Analyze_Associations
287      (I_Node  : Node_Id;
288       Formals : List_Id;
289       F_Copy  : List_Id)
290       return    List_Id;
291    --  At instantiation time, build the list of associations between formals
292    --  and actuals. Each association becomes a renaming declaration for the
293    --  formal entity. F_Copy is the analyzed list of formals in the generic
294    --  copy. It is used to apply legality checks to the actuals. I_Node is the
295    --  instantiation node itself.
296
297    procedure Analyze_Subprogram_Instantiation
298      (N : Node_Id;
299       K : Entity_Kind);
300
301    procedure Build_Instance_Compilation_Unit_Nodes
302      (N        : Node_Id;
303       Act_Body : Node_Id;
304       Act_Decl : Node_Id);
305    --  This procedure is used in the case where the generic instance of a
306    --  subprogram body or package body is a library unit. In this case, the
307    --  original library unit node for the generic instantiation must be
308    --  replaced by the resulting generic body, and a link made to a new
309    --  compilation unit node for the generic declaration. The argument N is
310    --  the original generic instantiation. Act_Body and Act_Decl are the body
311    --  and declaration of the instance (either package body and declaration
312    --  nodes or subprogram body and declaration nodes depending on the case).
313    --  On return, the node N has been rewritten with the actual body.
314
315    procedure Check_Formal_Packages (P_Id : Entity_Id);
316    --  Apply the following to all formal packages in generic associations.
317
318    procedure Check_Formal_Package_Instance
319      (Formal_Pack : Entity_Id;
320       Actual_Pack : Entity_Id);
321    --  Verify that the actuals of the actual instance match the actuals of
322    --  the template for a formal package that is not declared with a box.
323
324    procedure Check_Forward_Instantiation (N : Node_Id; Decl : Node_Id);
325    --  If the generic is a local entity and the corresponding body has not
326    --  been seen yet, flag enclosing packages to indicate that it will be
327    --  elaborated after the generic body. Subprograms declared in the same
328    --  package cannot be inlined by the front-end because front-end inlining
329    --  requires a strict linear order of elaboration.
330
331    procedure Check_Hidden_Child_Unit
332      (N           : Node_Id;
333       Gen_Unit    : Entity_Id;
334       Act_Decl_Id : Entity_Id);
335    --  If the generic unit is an implicit child instance within a parent
336    --  instance, we need to make an explicit test that it is not hidden by
337    --  a child instance of the same name and parent.
338
339    procedure Check_Private_View (N : Node_Id);
340    --  Check whether the type of a generic entity has a different view between
341    --  the point of generic analysis and the point of instantiation. If the
342    --  view has changed, then at the point of instantiation we restore the
343    --  correct view to perform semantic analysis of the instance, and reset
344    --  the current view after instantiation. The processing is driven by the
345    --  current private status of the type of the node, and Has_Private_View,
346    --  a flag that is set at the point of generic compilation. If view and
347    --  flag are inconsistent then the type is updated appropriately.
348
349    procedure Check_Generic_Actuals
350      (Instance      : Entity_Id;
351       Is_Formal_Box : Boolean);
352    --  Similar to previous one. Check the actuals in the instantiation,
353    --  whose views can change between the point of instantiation and the point
354    --  of instantiation of the body. In addition, mark the generic renamings
355    --  as generic actuals, so that they are not compatible with other actuals.
356    --  Recurse on an actual that is a formal package whose declaration has
357    --  a box.
358
359    function Contains_Instance_Of
360      (Inner : Entity_Id;
361       Outer : Entity_Id;
362       N     : Node_Id)
363       return  Boolean;
364    --  Inner is instantiated within the generic Outer. Check whether Inner
365    --  directly or indirectly contains an instance of Outer or of one of its
366    --  parents, in the case of a subunit. Each generic unit holds a list of
367    --  the entities instantiated within (at any depth). This procedure
368    --  determines whether the set of such lists contains a cycle, i.e. an
369    --  illegal circular instantiation.
370
371    function Denotes_Formal_Package (Pack : Entity_Id) return Boolean;
372    --  Returns True if E is a formal package of an enclosing generic, or
373    --  the actual for such a formal in an enclosing instantiation. Used in
374    --  Restore_Private_Views, to keep the formals of such a package visible
375    --  on exit from an inner instantiation.
376
377    function Find_Actual_Type
378      (Typ       : Entity_Id;
379       Gen_Scope : Entity_Id)
380       return      Entity_Id;
381    --  When validating the actual types of a child instance, check whether
382    --  the formal is a formal type of the parent unit, and retrieve the current
383    --  actual for it. Typ is the entity in the analyzed formal type declaration
384    --  (component or index type of an array type) and Gen_Scope is the scope of
385    --  the analyzed formal array type.
386
387    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id;
388    --  Given the entity of a unit that is an instantiation, retrieve the
389    --  original instance node. This is used when loading the instantiations
390    --  of the ancestors of a child generic that is being instantiated.
391
392    function In_Same_Declarative_Part
393      (F_Node : Node_Id;
394       Inst   : Node_Id)
395       return   Boolean;
396    --  True if the instantiation Inst and the given freeze_node F_Node appear
397    --  within the same declarative part, ignoring subunits, but with no inter-
398    --  vening suprograms or concurrent units. If true, the freeze node
399    --  of the instance can be placed after the freeze node of the parent,
400    --  which it itself an instance.
401
402    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id);
403    --  Associate analyzed generic parameter with corresponding
404    --  instance. Used for semantic checks at instantiation time.
405
406    function Has_Been_Exchanged (E : Entity_Id) return Boolean;
407    --  Traverse the Exchanged_Views list to see if a type was private
408    --  and has already been flipped during this phase of instantiation.
409
410    procedure Hide_Current_Scope;
411    --  When compiling a generic child unit, the parent context must be
412    --  present, but the instance and all entities that may be generated
413    --  must be inserted in the current scope. We leave the current scope
414    --  on the stack, but make its entities invisible to avoid visibility
415    --  problems. This is reversed at the end of instantiations. This is
416    --  not done for the instantiation of the bodies, which only require the
417    --  instances of the generic parents to be in scope.
418
419    procedure Install_Body
420      (Act_Body : Node_Id;
421       N        : Node_Id;
422       Gen_Body : Node_Id;
423       Gen_Decl : Node_Id);
424    --  If the instantiation happens textually before the body of the generic,
425    --  the instantiation of the body must be analyzed after the generic body,
426    --  and not at the point of instantiation. Such early instantiations can
427    --  happen if the generic and the instance appear in  a package declaration
428    --  because the generic body can only appear in the corresponding package
429    --  body. Early instantiations can also appear if generic, instance and
430    --  body are all in the declarative part of a subprogram or entry. Entities
431    --  of packages that are early instantiations are delayed, and their freeze
432    --  node appears after the generic body.
433
434    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id);
435    --  Insert freeze node at the end of the declarative part that includes the
436    --  instance node N. If N is in the visible part of an enclosing package
437    --  declaration, the freeze node has to be inserted at the end of the
438    --  private declarations, if any.
439
440    procedure Freeze_Subprogram_Body
441      (Inst_Node : Node_Id;
442       Gen_Body  : Node_Id;
443       Pack_Id   : Entity_Id);
444    --  The generic body may appear textually after the instance, including
445    --  in the proper body of a stub, or within a different package instance.
446    --  Given that the instance can only be elaborated after the generic, we
447    --  place freeze_nodes for the instance and/or for packages that may enclose
448    --  the instance and the generic, so that the back-end can establish the
449    --  proper order of elaboration.
450
451    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False);
452    --  When compiling an instance of a child unit the parent (which is
453    --  itself an instance) is an enclosing scope that must be made
454    --  immediately visible. This procedure is also used to install the non-
455    --  generic parent of a generic child unit when compiling its body, so that
456    --  full views of types in the parent are made visible.
457
458    procedure Remove_Parent (In_Body : Boolean := False);
459    --  Reverse effect after instantiation of child is complete.
460
461    procedure Inline_Instance_Body
462      (N        : Node_Id;
463       Gen_Unit : Entity_Id;
464       Act_Decl : Node_Id);
465    --  If front-end inlining is requested, instantiate the package body,
466    --  and preserve the visibility of its compilation unit, to insure
467    --  that successive instantiations succeed.
468
469    --  The functions Instantiate_XXX perform various legality checks and build
470    --  the declarations for instantiated generic parameters.
471    --  Need to describe what the parameters are ???
472
473    function Instantiate_Object
474      (Formal          : Node_Id;
475       Actual          : Node_Id;
476       Analyzed_Formal : Node_Id)
477       return            List_Id;
478
479    function Instantiate_Type
480      (Formal          : Node_Id;
481       Actual          : Node_Id;
482       Analyzed_Formal : Node_Id)
483       return            Node_Id;
484
485    function Instantiate_Formal_Subprogram
486      (Formal          : Node_Id;
487       Actual          : Node_Id;
488       Analyzed_Formal : Node_Id)
489       return            Node_Id;
490
491    function Instantiate_Formal_Package
492      (Formal          : Node_Id;
493       Actual          : Node_Id;
494       Analyzed_Formal : Node_Id)
495       return            List_Id;
496    --  If the formal package is declared with a box, special visibility rules
497    --  apply to its formals: they are in the visible part of the package. This
498    --  is true in the declarative region of the formal package, that is to say
499    --  in the enclosing generic or instantiation. For an instantiation, the
500    --  parameters of the formal package are made visible in an explicit step.
501    --  Furthermore, if the actual is a visible use_clause, these formals must
502    --  be made potentially use_visible as well. On exit from the enclosing
503    --  instantiation, the reverse must be done.
504
505    --  For a formal package declared without a box, there are conformance rules
506    --  that apply to the actuals in the generic declaration and the actuals of
507    --  the actual package in the enclosing instantiation. The simplest way to
508    --  apply these rules is to repeat the instantiation of the formal package
509    --  in the context of the enclosing instance, and compare the generic
510    --  associations of this instantiation with those of the actual package.
511
512    function Is_In_Main_Unit (N : Node_Id) return Boolean;
513    --  Test if given node is in the main unit
514
515    procedure Load_Parent_Of_Generic (N : Node_Id; Spec : Node_Id);
516    --  If the generic appears in a separate non-generic library unit,
517    --  load the corresponding body to retrieve the body of the generic.
518    --  N is the node for the generic instantiation, Spec is the generic
519    --  package declaration.
520
521    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id);
522    --  Add the context clause of the unit containing a generic unit to
523    --  an instantiation that is a compilation unit.
524
525    function Get_Associated_Node (N : Node_Id) return Node_Id;
526    --  In order to propagate semantic information back from the analyzed
527    --  copy to the original generic, we maintain links between selected nodes
528    --  in the generic and their corresponding copies. At the end of generic
529    --  analysis, the routine Save_Global_References traverses the generic
530    --  tree, examines the semantic information, and preserves the links to
531    --  those nodes that contain global information. At instantiation, the
532    --  information from the associated node is placed on the new copy, so
533    --  that name resolution is not repeated.
534
535    --  Three kinds of source nodes have associated nodes:
536
537    --    a) those that can reference (denote) entities, that is identifiers,
538    --       character literals, expanded_names, operator symbols, operators,
539    --       and attribute reference nodes. These nodes have an Entity field
540    --       and are the set of nodes that are in N_Has_Entity.
541
542    --    b) aggregates (N_Aggregate and N_Extension_Aggregate)
543
544    --    c) selected components (N_Selected_Component)
545
546    --  For the first class, the associated node preserves the entity if it is
547    --  global. If the generic contains nested instantiations, the associated_
548    --  node itself has been recopied, and a chain of them must be followed.
549
550    --  For aggregates, the associated node allows retrieval of the type, which
551    --  may otherwise not appear in the generic. The view of this type may be
552    --  different between generic and instantiation, and the full view can be
553    --  installed before the instantiation is analyzed. For aggregates of
554    --  type extensions, the same view exchange may have to be performed for
555    --  some of the ancestor types, if their view is private at the point of
556    --  instantiation.
557
558    --  Nodes that are selected components in the parse tree may be rewritten
559    --  as expanded names after resolution, and must be treated as potential
560    --  entity holders. which is why they also have an Associated_Node.
561
562    --  Nodes that do not come from source, such as freeze nodes, do not appear
563    --  in the generic tree, and need not have an associated node.
564
565    --  The associated node is stored in the Associated_Node field. Note that
566    --  this field overlaps Entity, which is fine, because the whole point is
567    --  that we don't need or want the normal Entity field in this situation.
568
569    procedure Move_Freeze_Nodes
570      (Out_Of : Entity_Id;
571       After  : Node_Id;
572       L      : List_Id);
573    --  Freeze nodes can be generated in the analysis of a generic unit, but
574    --  will not be seen by the back-end. It is necessary to move those nodes
575    --  to the enclosing scope if they freeze an outer entity. We place them
576    --  at the end of the enclosing generic package, which is semantically
577    --  neutral.
578
579    procedure Pre_Analyze_Actuals (N : Node_Id);
580    --  Analyze actuals to perform name resolution. Full resolution is done
581    --  later, when the expected types are known, but names have to be captured
582    --  before installing parents of generics, that are not visible for the
583    --  actuals themselves.
584
585    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id);
586    --  Verify that an attribute that appears as the default for a formal
587    --  subprogram is a function or procedure with the correct profile.
588
589    -------------------------------------------
590    -- Data Structures for Generic Renamings --
591    -------------------------------------------
592
593    --  The map Generic_Renamings associates generic entities with their
594    --  corresponding actuals. Currently used to validate type instances.
595    --  It will eventually be used for all generic parameters to eliminate
596    --  the need for overload resolution in the instance.
597
598    type Assoc_Ptr is new Int;
599
600    Assoc_Null : constant Assoc_Ptr := -1;
601
602    type Assoc is record
603       Gen_Id         : Entity_Id;
604       Act_Id         : Entity_Id;
605       Next_In_HTable : Assoc_Ptr;
606    end record;
607
608    package Generic_Renamings is new Table.Table
609      (Table_Component_Type => Assoc,
610       Table_Index_Type     => Assoc_Ptr,
611       Table_Low_Bound      => 0,
612       Table_Initial        => 10,
613       Table_Increment      => 100,
614       Table_Name           => "Generic_Renamings");
615
616    --  Variable to hold enclosing instantiation. When the environment is
617    --  saved for a subprogram inlining, the corresponding Act_Id is empty.
618
619    Current_Instantiated_Parent : Assoc := (Empty, Empty, Assoc_Null);
620
621    --  Hash table for associations
622
623    HTable_Size : constant := 37;
624    type HTable_Range is range 0 .. HTable_Size - 1;
625
626    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr);
627    function  Next_Assoc     (E : Assoc_Ptr) return Assoc_Ptr;
628    function Get_Gen_Id      (E : Assoc_Ptr) return Entity_Id;
629    function Hash            (F : Entity_Id)   return HTable_Range;
630
631    package Generic_Renamings_HTable is new GNAT.HTable.Static_HTable (
632       Header_Num => HTable_Range,
633       Element    => Assoc,
634       Elmt_Ptr   => Assoc_Ptr,
635       Null_Ptr   => Assoc_Null,
636       Set_Next   => Set_Next_Assoc,
637       Next       => Next_Assoc,
638       Key        => Entity_Id,
639       Get_Key    => Get_Gen_Id,
640       Hash       => Hash,
641       Equal      => "=");
642
643    Exchanged_Views : Elist_Id;
644    --  This list holds the private views that have been exchanged during
645    --  instantiation to restore the visibility of the generic declaration.
646    --  (see comments above). After instantiation, the current visibility is
647    --  reestablished by means of a traversal of this list.
648
649    Hidden_Entities : Elist_Id;
650    --  This list holds the entities of the current scope that are removed
651    --  from immediate visibility when instantiating a child unit. Their
652    --  visibility is restored in Remove_Parent.
653
654    --  Because instantiations can be recursive, the following must be saved
655    --  on entry and restored on exit from an instantiation (spec or body).
656    --  This is done by the two procedures Save_Env and Restore_Env.
657
658    type Instance_Env is record
659       Ada_83              : Boolean;
660       Instantiated_Parent : Assoc;
661       Exchanged_Views     : Elist_Id;
662       Hidden_Entities     : Elist_Id;
663       Current_Sem_Unit    : Unit_Number_Type;
664    end record;
665
666    package Instance_Envs is new Table.Table (
667      Table_Component_Type => Instance_Env,
668      Table_Index_Type     => Int,
669      Table_Low_Bound      => 0,
670      Table_Initial        => 32,
671      Table_Increment      => 100,
672      Table_Name           => "Instance_Envs");
673
674    procedure Restore_Private_Views
675      (Pack_Id    : Entity_Id;
676       Is_Package : Boolean := True);
677    --  Restore the private views of external types, and unmark the generic
678    --  renamings of actuals, so that they become comptible subtypes again.
679    --  For subprograms, Pack_Id is the package constructed to hold the
680    --  renamings.
681
682    procedure Switch_View (T : Entity_Id);
683    --  Switch the partial and full views of a type and its private
684    --  dependents (i.e. its subtypes and derived types).
685
686    ------------------------------------
687    -- Structures for Error Reporting --
688    ------------------------------------
689
690    Instantiation_Node : Node_Id;
691    --  Used by subprograms that validate instantiation of formal parameters
692    --  where there might be no actual on which to place the error message.
693    --  Also used to locate the instantiation node for generic subunits.
694
695    Instantiation_Error : exception;
696    --  When there is a semantic error in the generic parameter matching,
697    --  there is no point in continuing the instantiation, because the
698    --  number of cascaded errors is unpredictable. This exception aborts
699    --  the instantiation process altogether.
700
701    S_Adjustment : Sloc_Adjustment;
702    --  Offset created for each node in an instantiation, in order to keep
703    --  track of the source position of the instantiation in each of its nodes.
704    --  A subsequent semantic error or warning on a construct of the instance
705    --  points to both places: the original generic node, and the point of
706    --  instantiation. See Sinput and Sinput.L for additional details.
707
708    ------------------------------------------------------------
709    -- Data structure for keeping track when inside a Generic --
710    ------------------------------------------------------------
711
712    --  The following table is used to save values of the Inside_A_Generic
713    --  flag (see spec of Sem) when they are saved by Start_Generic.
714
715    package Generic_Flags is new Table.Table (
716      Table_Component_Type => Boolean,
717      Table_Index_Type     => Int,
718      Table_Low_Bound      => 0,
719      Table_Initial        => 32,
720      Table_Increment      => 200,
721      Table_Name           => "Generic_Flags");
722
723    ---------------------------
724    -- Abandon_Instantiation --
725    ---------------------------
726
727    procedure Abandon_Instantiation (N : Node_Id) is
728    begin
729       Error_Msg_N ("instantiation abandoned!", N);
730       raise Instantiation_Error;
731    end Abandon_Instantiation;
732
733    --------------------------
734    -- Analyze_Associations --
735    --------------------------
736
737    function Analyze_Associations
738      (I_Node  : Node_Id;
739       Formals : List_Id;
740       F_Copy  : List_Id)
741       return    List_Id
742    is
743       Actuals         : List_Id := Generic_Associations (I_Node);
744       Actual          : Node_Id;
745       Actual_Types    : Elist_Id := New_Elmt_List;
746       Assoc           : List_Id  := New_List;
747       Formal          : Node_Id;
748       Next_Formal     : Node_Id;
749       Temp_Formal     : Node_Id;
750       Analyzed_Formal : Node_Id;
751       Defaults        : Elist_Id := New_Elmt_List;
752       Match           : Node_Id;
753       Named           : Node_Id;
754       First_Named     : Node_Id := Empty;
755       Found_Assoc     : Node_Id;
756       Is_Named_Assoc  : Boolean;
757       Num_Matched     : Int := 0;
758       Num_Actuals     : Int := 0;
759
760       function Matching_Actual
761         (F    : Entity_Id;
762          A_F  : Entity_Id)
763          return Node_Id;
764       --  Find actual that corresponds to a given a formal parameter. If the
765       --  actuals are positional, return the next one, if any. If the actuals
766       --  are named, scan the parameter associations to find the right one.
767       --  A_F is the corresponding entity in the analyzed generic,which is
768       --  placed on the selector name for ASIS use.
769
770       procedure Set_Analyzed_Formal;
771       --  Find the node in the generic copy that corresponds to a given formal.
772       --  The semantic information on this node is used to perform legality
773       --  checks on the actuals. Because semantic analysis can introduce some
774       --  anonymous entities or modify the declaration node itself, the
775       --  correspondence between the two lists is not one-one. In addition to
776       --  anonymous types, the presence a formal equality will introduce an
777       --  implicit declaration for the corresponding inequality.
778
779       ---------------------
780       -- Matching_Actual --
781       ---------------------
782
783       function Matching_Actual
784         (F    : Entity_Id;
785          A_F  : Entity_Id)
786          return Node_Id
787       is
788          Found : Node_Id;
789          Prev  : Node_Id;
790
791       begin
792          Is_Named_Assoc := False;
793
794          --  End of list of purely positional parameters
795
796          if No (Actual) then
797             Found := Empty;
798
799          --  Case of positional parameter corresponding to current formal
800
801          elsif No (Selector_Name (Actual)) then
802             Found := Explicit_Generic_Actual_Parameter (Actual);
803             Found_Assoc := Actual;
804             Num_Matched := Num_Matched + 1;
805             Next (Actual);
806
807          --  Otherwise scan list of named actuals to find the one with the
808          --  desired name. All remaining actuals have explicit names.
809
810          else
811             Is_Named_Assoc := True;
812             Found := Empty;
813             Prev  := Empty;
814
815             while Present (Actual) loop
816                if Chars (Selector_Name (Actual)) = Chars (F) then
817                   Found := Explicit_Generic_Actual_Parameter (Actual);
818                   Set_Entity (Selector_Name (Actual), A_F);
819                   Set_Etype  (Selector_Name (Actual), Etype (A_F));
820                   Found_Assoc := Actual;
821                   Num_Matched := Num_Matched + 1;
822                   exit;
823                end if;
824
825                Prev := Actual;
826                Next (Actual);
827             end loop;
828
829             --  Reset for subsequent searches. In most cases the named
830             --  associations are in order. If they are not, we reorder them
831             --  to avoid scanning twice the same actual. This is not just a
832             --  question of efficiency: there may be multiple defaults with
833             --  boxes that have the same name. In a nested instantiation we
834             --  insert actuals for those defaults, and cannot rely on their
835             --  names to disambiguate them.
836
837             if Actual = First_Named  then
838                Next (First_Named);
839
840             elsif Present (Actual) then
841                Insert_Before (First_Named, Remove_Next (Prev));
842             end if;
843
844             Actual := First_Named;
845          end if;
846
847          return Found;
848       end Matching_Actual;
849
850       -------------------------
851       -- Set_Analyzed_Formal --
852       -------------------------
853
854       procedure Set_Analyzed_Formal is
855          Kind : Node_Kind;
856       begin
857          while Present (Analyzed_Formal) loop
858             Kind := Nkind (Analyzed_Formal);
859
860             case Nkind (Formal) is
861
862                when N_Formal_Subprogram_Declaration =>
863                   exit when Kind = N_Formal_Subprogram_Declaration
864                     and then
865                       Chars
866                         (Defining_Unit_Name (Specification (Formal))) =
867                       Chars
868                         (Defining_Unit_Name (Specification (Analyzed_Formal)));
869
870                when N_Formal_Package_Declaration =>
871                   exit when
872                     Kind = N_Formal_Package_Declaration
873                       or else
874                     Kind = N_Generic_Package_Declaration;
875
876                when N_Use_Package_Clause | N_Use_Type_Clause => exit;
877
878                when others =>
879
880                   --  Skip freeze nodes, and nodes inserted to replace
881                   --  unrecognized pragmas.
882
883                   exit when
884                     Kind /= N_Formal_Subprogram_Declaration
885                       and then Kind /= N_Subprogram_Declaration
886                       and then Kind /= N_Freeze_Entity
887                       and then Kind /= N_Null_Statement
888                       and then Kind /= N_Itype_Reference
889                       and then Chars (Defining_Identifier (Formal)) =
890                                Chars (Defining_Identifier (Analyzed_Formal));
891             end case;
892
893             Next (Analyzed_Formal);
894          end loop;
895
896       end Set_Analyzed_Formal;
897
898    --  Start of processing for Analyze_Associations
899
900    begin
901       --  If named associations are present, save the first named association
902       --  (it may of course be Empty) to facilitate subsequent name search.
903
904       if Present (Actuals) then
905          First_Named := First (Actuals);
906
907          while Present (First_Named)
908            and then No (Selector_Name (First_Named))
909          loop
910             Num_Actuals := Num_Actuals + 1;
911             Next (First_Named);
912          end loop;
913       end if;
914
915       Named := First_Named;
916       while Present (Named) loop
917          if No (Selector_Name (Named)) then
918             Error_Msg_N ("invalid positional actual after named one", Named);
919             Abandon_Instantiation (Named);
920          end if;
921
922          Num_Actuals := Num_Actuals + 1;
923          Next (Named);
924       end loop;
925
926       if Present (Formals) then
927          Formal := First_Non_Pragma (Formals);
928          Analyzed_Formal := First_Non_Pragma (F_Copy);
929
930          if Present (Actuals) then
931             Actual := First (Actuals);
932
933          --  All formals should have default values
934
935          else
936             Actual := Empty;
937          end if;
938
939          while Present (Formal) loop
940             Set_Analyzed_Formal;
941             Next_Formal := Next_Non_Pragma (Formal);
942
943             case Nkind (Formal) is
944                when N_Formal_Object_Declaration =>
945                   Match :=
946                     Matching_Actual (
947                       Defining_Identifier (Formal),
948                       Defining_Identifier (Analyzed_Formal));
949
950                   Append_List
951                     (Instantiate_Object (Formal, Match, Analyzed_Formal),
952                      Assoc);
953
954                when N_Formal_Type_Declaration =>
955                   Match :=
956                     Matching_Actual (
957                       Defining_Identifier (Formal),
958                       Defining_Identifier (Analyzed_Formal));
959
960                   if No (Match) then
961                      Error_Msg_NE ("missing actual for instantiation of &",
962                         Instantiation_Node, Defining_Identifier (Formal));
963                      Abandon_Instantiation (Instantiation_Node);
964
965                   else
966                      Analyze (Match);
967                      Append_To (Assoc,
968                        Instantiate_Type (Formal, Match, Analyzed_Formal));
969
970                      --  an instantiation is a freeze point for the actuals,
971                      --  unless this is a rewritten formal package.
972
973                      if Nkind (I_Node) /= N_Formal_Package_Declaration then
974                         Append_Elmt (Entity (Match), Actual_Types);
975                      end if;
976                   end if;
977
978                   --  A remote access-to-class-wide type must not be an
979                   --  actual parameter for a generic formal of an access
980                   --  type (E.2.2 (17)).
981
982                   if Nkind (Analyzed_Formal) = N_Formal_Type_Declaration
983                     and then
984                       Nkind (Formal_Type_Definition (Analyzed_Formal)) =
985                                             N_Access_To_Object_Definition
986                   then
987                      Validate_Remote_Access_To_Class_Wide_Type (Match);
988                   end if;
989
990                when N_Formal_Subprogram_Declaration =>
991                   Match :=
992                     Matching_Actual (
993                       Defining_Unit_Name (Specification (Formal)),
994                       Defining_Unit_Name (Specification (Analyzed_Formal)));
995
996                   --  If the formal subprogram has the same name as
997                   --  another formal subprogram of the generic, then
998                   --  a named association is illegal (12.3(9)). Exclude
999                   --  named associations that are generated for a nested
1000                   --  instance.
1001
1002                   if Present (Match)
1003                     and then Is_Named_Assoc
1004                     and then Comes_From_Source (Found_Assoc)
1005                   then
1006                      Temp_Formal := First (Formals);
1007                      while Present (Temp_Formal) loop
1008                         if Nkind (Temp_Formal) =
1009                              N_Formal_Subprogram_Declaration
1010                           and then Temp_Formal /= Formal
1011                           and then
1012                             Chars (Selector_Name (Found_Assoc)) =
1013                               Chars (Defining_Unit_Name
1014                                        (Specification (Temp_Formal)))
1015                         then
1016                            Error_Msg_N
1017                              ("name not allowed for overloaded formal",
1018                               Found_Assoc);
1019                            Abandon_Instantiation (Instantiation_Node);
1020                         end if;
1021
1022                         Next (Temp_Formal);
1023                      end loop;
1024                   end if;
1025
1026                   Append_To (Assoc,
1027                     Instantiate_Formal_Subprogram
1028                       (Formal, Match, Analyzed_Formal));
1029
1030                   if No (Match)
1031                     and then Box_Present (Formal)
1032                   then
1033                      Append_Elmt
1034                        (Defining_Unit_Name (Specification (Last (Assoc))),
1035                          Defaults);
1036                   end if;
1037
1038                when N_Formal_Package_Declaration =>
1039                   Match :=
1040                     Matching_Actual (
1041                       Defining_Identifier (Formal),
1042                       Defining_Identifier (Original_Node (Analyzed_Formal)));
1043
1044                   if No (Match) then
1045                      Error_Msg_NE
1046                        ("missing actual for instantiation of&",
1047                         Instantiation_Node,
1048                         Defining_Identifier (Formal));
1049
1050                      Abandon_Instantiation (Instantiation_Node);
1051
1052                   else
1053                      Analyze (Match);
1054                      Append_List
1055                        (Instantiate_Formal_Package
1056                          (Formal, Match, Analyzed_Formal),
1057                         Assoc);
1058                   end if;
1059
1060                --  For use type and use package appearing in the context
1061                --  clause, we have already copied them, so we can just
1062                --  move them where they belong (we mustn't recopy them
1063                --  since this would mess up the Sloc values).
1064
1065                when N_Use_Package_Clause |
1066                     N_Use_Type_Clause    =>
1067                   Remove (Formal);
1068                   Append (Formal, Assoc);
1069
1070                when others =>
1071                   raise Program_Error;
1072
1073             end case;
1074
1075             Formal := Next_Formal;
1076             Next_Non_Pragma (Analyzed_Formal);
1077          end loop;
1078
1079          if Num_Actuals > Num_Matched then
1080             Error_Msg_N
1081               ("unmatched actuals in instantiation", Instantiation_Node);
1082          end if;
1083
1084       elsif Present (Actuals) then
1085          Error_Msg_N
1086            ("too many actuals in generic instantiation", Instantiation_Node);
1087       end if;
1088
1089       declare
1090          Elmt : Elmt_Id := First_Elmt (Actual_Types);
1091
1092       begin
1093          while Present (Elmt) loop
1094             Freeze_Before (I_Node, Node (Elmt));
1095             Next_Elmt (Elmt);
1096          end loop;
1097       end;
1098
1099       --  If there are default subprograms, normalize the tree by adding
1100       --  explicit associations for them. This is required if the instance
1101       --  appears within a generic.
1102
1103       declare
1104          Elmt  : Elmt_Id;
1105          Subp  : Entity_Id;
1106          New_D : Node_Id;
1107
1108       begin
1109          Elmt := First_Elmt (Defaults);
1110          while Present (Elmt) loop
1111             if No (Actuals) then
1112                Actuals := New_List;
1113                Set_Generic_Associations (I_Node, Actuals);
1114             end if;
1115
1116             Subp := Node (Elmt);
1117             New_D :=
1118               Make_Generic_Association (Sloc (Subp),
1119                 Selector_Name => New_Occurrence_Of (Subp, Sloc (Subp)),
1120                   Explicit_Generic_Actual_Parameter =>
1121                     New_Occurrence_Of (Subp, Sloc (Subp)));
1122             Mark_Rewrite_Insertion (New_D);
1123             Append_To (Actuals, New_D);
1124             Next_Elmt (Elmt);
1125          end loop;
1126       end;
1127
1128       return Assoc;
1129    end Analyze_Associations;
1130
1131    -------------------------------
1132    -- Analyze_Formal_Array_Type --
1133    -------------------------------
1134
1135    procedure Analyze_Formal_Array_Type
1136      (T   : in out Entity_Id;
1137       Def : Node_Id)
1138    is
1139       DSS : Node_Id;
1140
1141    begin
1142       --  Treated like a non-generic array declaration, with
1143       --  additional semantic checks.
1144
1145       Enter_Name (T);
1146
1147       if Nkind (Def) = N_Constrained_Array_Definition then
1148          DSS := First (Discrete_Subtype_Definitions (Def));
1149          while Present (DSS) loop
1150             if Nkind (DSS) = N_Subtype_Indication
1151               or else Nkind (DSS) = N_Range
1152               or else Nkind (DSS) = N_Attribute_Reference
1153             then
1154                Error_Msg_N ("only a subtype mark is allowed in a formal", DSS);
1155             end if;
1156
1157             Next (DSS);
1158          end loop;
1159       end if;
1160
1161       Array_Type_Declaration (T, Def);
1162       Set_Is_Generic_Type (Base_Type (T));
1163
1164       if Ekind (Component_Type (T)) = E_Incomplete_Type
1165         and then No (Full_View (Component_Type (T)))
1166       then
1167          Error_Msg_N ("premature usage of incomplete type", Def);
1168
1169       elsif Is_Internal (Component_Type (T))
1170         and then Nkind (Original_Node (Subtype_Indication (Def)))
1171           /= N_Attribute_Reference
1172       then
1173          Error_Msg_N
1174            ("only a subtype mark is allowed in a formal",
1175               Subtype_Indication (Def));
1176       end if;
1177
1178    end Analyze_Formal_Array_Type;
1179
1180    ---------------------------------------------
1181    -- Analyze_Formal_Decimal_Fixed_Point_Type --
1182    ---------------------------------------------
1183
1184    --  As for other generic types, we create a valid type representation
1185    --  with legal but arbitrary attributes, whose values are never considered
1186    --  static. For all scalar types we introduce an anonymous base type, with
1187    --  the same attributes. We choose the corresponding integer type to be
1188    --  Standard_Integer.
1189
1190    procedure Analyze_Formal_Decimal_Fixed_Point_Type
1191      (T   : Entity_Id;
1192       Def : Node_Id)
1193    is
1194       Loc       : constant Source_Ptr := Sloc (Def);
1195       Base      : constant Entity_Id :=
1196                     New_Internal_Entity
1197                       (E_Decimal_Fixed_Point_Type,
1198                        Current_Scope, Sloc (Def), 'G');
1199       Int_Base  : constant Entity_Id := Standard_Integer;
1200       Delta_Val : constant Ureal := Ureal_1;
1201       Digs_Val  : constant Uint  := Uint_6;
1202
1203    begin
1204       Enter_Name (T);
1205
1206       Set_Etype          (Base, Base);
1207       Set_Size_Info      (Base, Int_Base);
1208       Set_RM_Size        (Base, RM_Size (Int_Base));
1209       Set_First_Rep_Item (Base, First_Rep_Item (Int_Base));
1210       Set_Digits_Value   (Base, Digs_Val);
1211       Set_Delta_Value    (Base, Delta_Val);
1212       Set_Small_Value    (Base, Delta_Val);
1213       Set_Scalar_Range   (Base,
1214         Make_Range (Loc,
1215           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1216           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1217
1218       Set_Is_Generic_Type (Base);
1219       Set_Parent          (Base, Parent (Def));
1220
1221       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
1222       Set_Etype          (T, Base);
1223       Set_Size_Info      (T, Int_Base);
1224       Set_RM_Size        (T, RM_Size (Int_Base));
1225       Set_First_Rep_Item (T, First_Rep_Item (Int_Base));
1226       Set_Digits_Value   (T, Digs_Val);
1227       Set_Delta_Value    (T, Delta_Val);
1228       Set_Small_Value    (T, Delta_Val);
1229       Set_Scalar_Range   (T, Scalar_Range (Base));
1230
1231    end Analyze_Formal_Decimal_Fixed_Point_Type;
1232
1233    ---------------------------------
1234    -- Analyze_Formal_Derived_Type --
1235    ---------------------------------
1236
1237    procedure Analyze_Formal_Derived_Type
1238      (N   : Node_Id;
1239       T   : Entity_Id;
1240       Def : Node_Id)
1241    is
1242       Loc      : constant Source_Ptr := Sloc (Def);
1243       New_N    : Node_Id;
1244       Unk_Disc : Boolean := Unknown_Discriminants_Present (N);
1245
1246    begin
1247       Set_Is_Generic_Type (T);
1248
1249       if Private_Present (Def) then
1250          New_N :=
1251            Make_Private_Extension_Declaration (Loc,
1252              Defining_Identifier           => T,
1253              Discriminant_Specifications   => Discriminant_Specifications (N),
1254              Unknown_Discriminants_Present => Unk_Disc,
1255              Subtype_Indication            => Subtype_Mark (Def));
1256
1257          Set_Abstract_Present (New_N, Abstract_Present (Def));
1258
1259       else
1260          New_N :=
1261            Make_Full_Type_Declaration (Loc,
1262              Defining_Identifier => T,
1263              Discriminant_Specifications =>
1264                Discriminant_Specifications (Parent (T)),
1265               Type_Definition =>
1266                 Make_Derived_Type_Definition (Loc,
1267                   Subtype_Indication => Subtype_Mark (Def)));
1268
1269          Set_Abstract_Present
1270            (Type_Definition (New_N), Abstract_Present (Def));
1271       end if;
1272
1273       Rewrite (N, New_N);
1274       Analyze (N);
1275
1276       if Unk_Disc then
1277          if not Is_Composite_Type (T) then
1278             Error_Msg_N
1279               ("unknown discriminants not allowed for elementary types", N);
1280          else
1281             Set_Has_Unknown_Discriminants (T);
1282             Set_Is_Constrained (T, False);
1283          end if;
1284       end if;
1285
1286       --  If the parent type has a known size, so does the formal, which
1287       --  makes legal representation clauses that involve the formal.
1288
1289       Set_Size_Known_At_Compile_Time
1290         (T, Size_Known_At_Compile_Time (Entity (Subtype_Mark (Def))));
1291
1292    end Analyze_Formal_Derived_Type;
1293
1294    ----------------------------------
1295    -- Analyze_Formal_Discrete_Type --
1296    ----------------------------------
1297
1298    --  The operations defined for a discrete types are those of an
1299    --  enumeration type. The size is set to an arbitrary value, for use
1300    --  in analyzing the generic unit.
1301
1302    procedure Analyze_Formal_Discrete_Type (T : Entity_Id; Def : Node_Id) is
1303       Loc : constant Source_Ptr := Sloc (Def);
1304       Lo  : Node_Id;
1305       Hi  : Node_Id;
1306
1307    begin
1308       Enter_Name     (T);
1309       Set_Ekind      (T, E_Enumeration_Type);
1310       Set_Etype      (T, T);
1311       Init_Size      (T, 8);
1312       Init_Alignment (T);
1313
1314       --  For semantic analysis, the bounds of the type must be set to some
1315       --  non-static value. The simplest is to create attribute nodes for
1316       --  those bounds, that refer to the type itself. These bounds are never
1317       --  analyzed but serve as place-holders.
1318
1319       Lo :=
1320         Make_Attribute_Reference (Loc,
1321           Attribute_Name => Name_First,
1322           Prefix => New_Reference_To (T, Loc));
1323       Set_Etype (Lo, T);
1324
1325       Hi :=
1326         Make_Attribute_Reference (Loc,
1327           Attribute_Name => Name_Last,
1328           Prefix => New_Reference_To (T, Loc));
1329       Set_Etype (Hi, T);
1330
1331       Set_Scalar_Range (T,
1332         Make_Range (Loc,
1333           Low_Bound => Lo,
1334           High_Bound => Hi));
1335
1336    end Analyze_Formal_Discrete_Type;
1337
1338    ----------------------------------
1339    -- Analyze_Formal_Floating_Type --
1340    ---------------------------------
1341
1342    procedure Analyze_Formal_Floating_Type (T : Entity_Id; Def : Node_Id) is
1343       Base : constant Entity_Id :=
1344                New_Internal_Entity
1345                  (E_Floating_Point_Type, Current_Scope, Sloc (Def), 'G');
1346
1347    begin
1348       --  The various semantic attributes are taken from the predefined type
1349       --  Float, just so that all of them are initialized. Their values are
1350       --  never used because no constant folding or expansion takes place in
1351       --  the generic itself.
1352
1353       Enter_Name (T);
1354       Set_Ekind        (T, E_Floating_Point_Subtype);
1355       Set_Etype        (T, Base);
1356       Set_Size_Info    (T,              (Standard_Float));
1357       Set_RM_Size      (T, RM_Size      (Standard_Float));
1358       Set_Digits_Value (T, Digits_Value (Standard_Float));
1359       Set_Scalar_Range (T, Scalar_Range (Standard_Float));
1360
1361       Set_Is_Generic_Type (Base);
1362       Set_Etype           (Base, Base);
1363       Set_Size_Info       (Base,              (Standard_Float));
1364       Set_RM_Size         (Base, RM_Size      (Standard_Float));
1365       Set_Digits_Value    (Base, Digits_Value (Standard_Float));
1366       Set_Scalar_Range    (Base, Scalar_Range (Standard_Float));
1367       Set_Parent          (Base, Parent (Def));
1368    end Analyze_Formal_Floating_Type;
1369
1370    ---------------------------------
1371    -- Analyze_Formal_Modular_Type --
1372    ---------------------------------
1373
1374    procedure Analyze_Formal_Modular_Type (T : Entity_Id; Def : Node_Id) is
1375    begin
1376       --  Apart from their entity kind, generic modular types are treated
1377       --  like signed integer types, and have the same attributes.
1378
1379       Analyze_Formal_Signed_Integer_Type (T, Def);
1380       Set_Ekind (T, E_Modular_Integer_Subtype);
1381       Set_Ekind (Etype (T), E_Modular_Integer_Type);
1382
1383    end Analyze_Formal_Modular_Type;
1384
1385    ---------------------------------------
1386    -- Analyze_Formal_Object_Declaration --
1387    ---------------------------------------
1388
1389    procedure Analyze_Formal_Object_Declaration (N : Node_Id) is
1390       E  : constant Node_Id := Expression (N);
1391       Id : Node_Id := Defining_Identifier (N);
1392       K  : Entity_Kind;
1393       T  : Node_Id;
1394
1395    begin
1396       Enter_Name (Id);
1397
1398       --  Determine the mode of the formal object
1399
1400       if Out_Present (N) then
1401          K := E_Generic_In_Out_Parameter;
1402
1403          if not In_Present (N) then
1404             Error_Msg_N ("formal generic objects cannot have mode OUT", N);
1405          end if;
1406
1407       else
1408          K := E_Generic_In_Parameter;
1409       end if;
1410
1411       Find_Type (Subtype_Mark (N));
1412       T  := Entity (Subtype_Mark (N));
1413
1414       if Ekind (T) = E_Incomplete_Type then
1415          Error_Msg_N ("premature usage of incomplete type", Subtype_Mark (N));
1416       end if;
1417
1418       if K = E_Generic_In_Parameter then
1419          if Is_Limited_Type (T) then
1420             Error_Msg_N
1421               ("generic formal of mode IN must not be of limited type", N);
1422          end if;
1423
1424          if Is_Abstract (T) then
1425             Error_Msg_N
1426               ("generic formal of mode IN must not be of abstract type", N);
1427          end if;
1428
1429          if Present (E) then
1430             Analyze_Default_Expression (E, T);
1431          end if;
1432
1433          Set_Ekind (Id, K);
1434          Set_Etype (Id, T);
1435
1436       --  Case of generic IN OUT parameter.
1437
1438       else
1439          --  If the formal has an unconstrained type, construct its
1440          --  actual subtype, as is done for subprogram formals. In this
1441          --  fashion, all its uses can refer to specific bounds.
1442
1443          Set_Ekind (Id, K);
1444          Set_Etype (Id, T);
1445
1446          if (Is_Array_Type (T)
1447               and then not Is_Constrained (T))
1448            or else
1449             (Ekind (T) = E_Record_Type
1450               and then Has_Discriminants (T))
1451          then
1452             declare
1453                Non_Freezing_Ref : constant Node_Id :=
1454                                     New_Reference_To (Id, Sloc (Id));
1455                Decl : Node_Id;
1456
1457             begin
1458                --  Make sure that the actual subtype doesn't generate
1459                --  bogus freezing.
1460
1461                Set_Must_Not_Freeze (Non_Freezing_Ref);
1462                Decl := Build_Actual_Subtype (T, Non_Freezing_Ref);
1463                Insert_Before_And_Analyze (N, Decl);
1464                Set_Actual_Subtype (Id, Defining_Identifier (Decl));
1465             end;
1466          else
1467             Set_Actual_Subtype (Id, T);
1468          end if;
1469
1470          if Present (E) then
1471             Error_Msg_N
1472               ("initialization not allowed for `IN OUT` formals", N);
1473          end if;
1474       end if;
1475
1476    end Analyze_Formal_Object_Declaration;
1477
1478    ----------------------------------------------
1479    -- Analyze_Formal_Ordinary_Fixed_Point_Type --
1480    ----------------------------------------------
1481
1482    procedure Analyze_Formal_Ordinary_Fixed_Point_Type
1483      (T   : Entity_Id;
1484       Def : Node_Id)
1485    is
1486       Loc  : constant Source_Ptr := Sloc (Def);
1487       Base : constant Entity_Id :=
1488                New_Internal_Entity
1489                  (E_Ordinary_Fixed_Point_Type, Current_Scope, Sloc (Def), 'G');
1490    begin
1491       --  The semantic attributes are set for completeness only, their
1492       --  values will never be used, because all properties of the type
1493       --  are non-static.
1494
1495       Enter_Name (T);
1496       Set_Ekind            (T, E_Ordinary_Fixed_Point_Subtype);
1497       Set_Etype            (T, Base);
1498       Set_Size_Info        (T, Standard_Integer);
1499       Set_RM_Size          (T, RM_Size (Standard_Integer));
1500       Set_Small_Value      (T, Ureal_1);
1501       Set_Delta_Value      (T, Ureal_1);
1502       Set_Scalar_Range     (T,
1503         Make_Range (Loc,
1504           Low_Bound  => Make_Real_Literal (Loc, Ureal_1),
1505           High_Bound => Make_Real_Literal (Loc, Ureal_1)));
1506
1507       Set_Is_Generic_Type (Base);
1508       Set_Etype           (Base, Base);
1509       Set_Size_Info       (Base, Standard_Integer);
1510       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1511       Set_Small_Value     (Base, Ureal_1);
1512       Set_Delta_Value     (Base, Ureal_1);
1513       Set_Scalar_Range    (Base, Scalar_Range (T));
1514       Set_Parent          (Base, Parent (Def));
1515    end Analyze_Formal_Ordinary_Fixed_Point_Type;
1516
1517    ----------------------------
1518    -- Analyze_Formal_Package --
1519    ----------------------------
1520
1521    procedure Analyze_Formal_Package (N : Node_Id) is
1522       Loc              : constant Source_Ptr := Sloc (N);
1523       Formal           : Entity_Id := Defining_Identifier (N);
1524       Gen_Id           : constant Node_Id   := Name (N);
1525       Gen_Decl         : Node_Id;
1526       Gen_Unit         : Entity_Id;
1527       New_N            : Node_Id;
1528       Parent_Installed : Boolean := False;
1529       Renaming         : Node_Id;
1530       Parent_Instance  : Entity_Id;
1531       Renaming_In_Par  : Entity_Id;
1532
1533    begin
1534       Text_IO_Kludge (Gen_Id);
1535
1536       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
1537       Gen_Unit := Entity (Gen_Id);
1538
1539       if Ekind (Gen_Unit) /= E_Generic_Package then
1540          Error_Msg_N ("expect generic package name", Gen_Id);
1541          return;
1542
1543       elsif  Gen_Unit = Current_Scope then
1544          Error_Msg_N
1545            ("generic package cannot be used as a formal package of itself",
1546              Gen_Id);
1547          return;
1548       end if;
1549
1550       --  Check for a formal package that is a package renaming.
1551
1552       if Present (Renamed_Object (Gen_Unit)) then
1553          Gen_Unit := Renamed_Object (Gen_Unit);
1554       end if;
1555
1556       --  The formal package is treated like a regular instance, but only
1557       --  the specification needs to be instantiated, to make entities visible.
1558
1559       if not Box_Present (N) then
1560          Hidden_Entities := New_Elmt_List;
1561          Analyze_Package_Instantiation (N);
1562
1563          if Parent_Installed then
1564             Remove_Parent;
1565          end if;
1566
1567       else
1568          --  If there are no generic associations, the generic parameters
1569          --  appear as local entities and are instantiated like them. We copy
1570          --  the generic package declaration as if it were an instantiation,
1571          --  and analyze it like a regular package, except that we treat the
1572          --  formals as additional visible components.
1573
1574          Save_Env (Gen_Unit, Formal);
1575
1576          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
1577
1578          if In_Extended_Main_Source_Unit (N) then
1579             Set_Is_Instantiated (Gen_Unit);
1580             Generate_Reference  (Gen_Unit, N);
1581          end if;
1582
1583          New_N :=
1584            Copy_Generic_Node
1585              (Original_Node (Gen_Decl), Empty, Instantiating => True);
1586          Set_Defining_Unit_Name (Specification (New_N), Formal);
1587          Rewrite (N, New_N);
1588
1589          Enter_Name (Formal);
1590          Set_Ekind  (Formal, E_Generic_Package);
1591          Set_Etype  (Formal, Standard_Void_Type);
1592          Set_Inner_Instances (Formal, New_Elmt_List);
1593          New_Scope  (Formal);
1594
1595          --  Within the formal, the name of the generic package is a renaming
1596          --  of the formal (as for a regular instantiation).
1597
1598          Renaming := Make_Package_Renaming_Declaration (Loc,
1599              Defining_Unit_Name =>
1600                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
1601              Name => New_Reference_To (Formal, Loc));
1602
1603          if Present (Visible_Declarations (Specification (N))) then
1604             Prepend (Renaming, To => Visible_Declarations (Specification (N)));
1605          elsif Present (Private_Declarations (Specification (N))) then
1606             Prepend (Renaming, To => Private_Declarations (Specification (N)));
1607          end if;
1608
1609          if Is_Child_Unit (Gen_Unit)
1610            and then Parent_Installed
1611          then
1612             --  Similarly, we have to make the name of the formal visible in
1613             --  the parent instance, to resolve properly fully qualified names
1614             --  that may appear in the generic unit. The parent instance has
1615             --  been placed on the scope stack ahead of the current scope.
1616
1617             Parent_Instance := Scope_Stack.Table (Scope_Stack.Last - 1).Entity;
1618
1619             Renaming_In_Par :=
1620               Make_Defining_Identifier (Loc, Chars (Gen_Unit));
1621             Set_Ekind (Renaming_In_Par, E_Package);
1622             Set_Etype (Renaming_In_Par, Standard_Void_Type);
1623             Set_Scope (Renaming_In_Par, Parent_Instance);
1624             Set_Parent (Renaming_In_Par, Parent (Formal));
1625             Set_Renamed_Object (Renaming_In_Par, Formal);
1626             Append_Entity (Renaming_In_Par, Parent_Instance);
1627          end if;
1628
1629          Analyze_Generic_Formal_Part (N);
1630          Analyze (Specification (N));
1631          End_Package_Scope (Formal);
1632
1633          if Parent_Installed then
1634             Remove_Parent;
1635          end if;
1636
1637          Restore_Env;
1638
1639          --  Inside the generic unit, the formal package is a regular
1640          --  package, but no body is needed for it. Note that after
1641          --  instantiation, the defining_unit_name we need is in the
1642          --  new tree and not in the original. (see Package_Instantiation).
1643          --  A generic formal package is an instance, and can be used as
1644          --  an actual for an inner instance. Mark its generic parent.
1645
1646          Set_Ekind (Formal, E_Package);
1647          Set_Generic_Parent (Specification (N), Gen_Unit);
1648          Set_Has_Completion (Formal, True);
1649       end if;
1650    end Analyze_Formal_Package;
1651
1652    ---------------------------------
1653    -- Analyze_Formal_Private_Type --
1654    ---------------------------------
1655
1656    procedure Analyze_Formal_Private_Type
1657      (N   : Node_Id;
1658       T   : Entity_Id;
1659       Def : Node_Id)
1660    is
1661    begin
1662       New_Private_Type (N, T, Def);
1663
1664       --  Set the size to an arbitrary but legal value.
1665
1666       Set_Size_Info (T, Standard_Integer);
1667       Set_RM_Size   (T, RM_Size (Standard_Integer));
1668    end Analyze_Formal_Private_Type;
1669
1670    ----------------------------------------
1671    -- Analyze_Formal_Signed_Integer_Type --
1672    ----------------------------------------
1673
1674    procedure Analyze_Formal_Signed_Integer_Type
1675      (T   : Entity_Id;
1676       Def : Node_Id)
1677    is
1678       Base : constant Entity_Id :=
1679                New_Internal_Entity
1680                  (E_Signed_Integer_Type, Current_Scope, Sloc (Def), 'G');
1681
1682    begin
1683       Enter_Name (T);
1684
1685       Set_Ekind        (T, E_Signed_Integer_Subtype);
1686       Set_Etype        (T, Base);
1687       Set_Size_Info    (T, Standard_Integer);
1688       Set_RM_Size      (T, RM_Size (Standard_Integer));
1689       Set_Scalar_Range (T, Scalar_Range (Standard_Integer));
1690
1691       Set_Is_Generic_Type (Base);
1692       Set_Size_Info       (Base, Standard_Integer);
1693       Set_RM_Size         (Base, RM_Size (Standard_Integer));
1694       Set_Etype           (Base, Base);
1695       Set_Scalar_Range    (Base, Scalar_Range (Standard_Integer));
1696       Set_Parent          (Base, Parent (Def));
1697    end Analyze_Formal_Signed_Integer_Type;
1698
1699    -------------------------------
1700    -- Analyze_Formal_Subprogram --
1701    -------------------------------
1702
1703    procedure Analyze_Formal_Subprogram (N : Node_Id) is
1704       Spec : constant Node_Id   := Specification (N);
1705       Def  : constant Node_Id   := Default_Name (N);
1706       Nam  : constant Entity_Id := Defining_Unit_Name (Spec);
1707       Subp : Entity_Id;
1708
1709    begin
1710       if Nam = Error then
1711          return;
1712       end if;
1713
1714       if Nkind (Nam) = N_Defining_Program_Unit_Name then
1715          Error_Msg_N ("name of formal subprogram must be a direct name", Nam);
1716          return;
1717       end if;
1718
1719       Analyze_Subprogram_Declaration (N);
1720       Set_Is_Formal_Subprogram (Nam);
1721       Set_Has_Completion (Nam);
1722
1723       --  Default name is resolved at the point of instantiation
1724
1725       if Box_Present (N) then
1726          null;
1727
1728       --  Else default is bound at the point of generic declaration
1729
1730       elsif Present (Def) then
1731          if Nkind (Def) = N_Operator_Symbol then
1732             Find_Direct_Name (Def);
1733
1734          elsif Nkind (Def) /= N_Attribute_Reference then
1735             Analyze (Def);
1736
1737          else
1738             --  For an attribute reference, analyze the prefix and verify
1739             --  that it has the proper profile for the subprogram.
1740
1741             Analyze (Prefix (Def));
1742             Valid_Default_Attribute (Nam, Def);
1743             return;
1744          end if;
1745
1746          --  Default name may be overloaded, in which case the interpretation
1747          --  with the correct profile must be  selected, as for a renaming.
1748
1749          if Etype (Def) = Any_Type then
1750             return;
1751
1752          elsif Nkind (Def) = N_Selected_Component then
1753             Subp := Entity (Selector_Name (Def));
1754
1755             if Ekind (Subp) /= E_Entry then
1756                Error_Msg_N ("expect valid subprogram name as default", Def);
1757                return;
1758             end if;
1759
1760          elsif Nkind (Def) = N_Indexed_Component then
1761
1762             if  Nkind (Prefix (Def)) /= N_Selected_Component then
1763                Error_Msg_N ("expect valid subprogram name as default", Def);
1764                return;
1765
1766             else
1767                Subp := Entity (Selector_Name (Prefix (Def)));
1768
1769                if Ekind (Subp) /= E_Entry_Family then
1770                   Error_Msg_N ("expect valid subprogram name as default", Def);
1771                   return;
1772                end if;
1773             end if;
1774
1775          elsif Nkind (Def) = N_Character_Literal then
1776
1777             --  Needs some type checks: subprogram should be parameterless???
1778
1779             Resolve (Def, (Etype (Nam)));
1780
1781          elsif (not Is_Entity_Name (Def)
1782            or else not Is_Overloadable (Entity (Def)))
1783          then
1784             Error_Msg_N ("expect valid subprogram name as default", Def);
1785             return;
1786
1787          elsif not Is_Overloaded (Def) then
1788             Subp := Entity (Def);
1789
1790             if Subp = Nam then
1791                Error_Msg_N ("premature usage of formal subprogram", Def);
1792
1793             elsif not Entity_Matches_Spec (Subp, Nam) then
1794                Error_Msg_N ("no visible entity matches specification", Def);
1795             end if;
1796
1797          else
1798             declare
1799                I   : Interp_Index;
1800                I1  : Interp_Index := 0;
1801                It  : Interp;
1802                It1 : Interp;
1803
1804             begin
1805                Subp := Any_Id;
1806                Get_First_Interp (Def, I, It);
1807                while Present (It.Nam) loop
1808
1809                   if Entity_Matches_Spec (It.Nam, Nam) then
1810                      if Subp /= Any_Id then
1811                         It1 := Disambiguate (Def, I1, I, Etype (Subp));
1812
1813                         if It1 = No_Interp then
1814                            Error_Msg_N ("ambiguous default subprogram", Def);
1815                         else
1816                            Subp := It1.Nam;
1817                         end if;
1818
1819                         exit;
1820
1821                      else
1822                         I1  := I;
1823                         Subp := It.Nam;
1824                      end if;
1825                   end if;
1826
1827                   Get_Next_Interp (I, It);
1828                end loop;
1829             end;
1830
1831             if Subp /= Any_Id then
1832                Set_Entity (Def, Subp);
1833
1834                if Subp = Nam then
1835                   Error_Msg_N ("premature usage of formal subprogram", Def);
1836
1837                elsif Ekind (Subp) /= E_Operator then
1838                   Check_Mode_Conformant (Subp, Nam);
1839                end if;
1840
1841             else
1842                Error_Msg_N ("no visible subprogram matches specification", N);
1843             end if;
1844          end if;
1845       end if;
1846    end Analyze_Formal_Subprogram;
1847
1848    -------------------------------------
1849    -- Analyze_Formal_Type_Declaration --
1850    -------------------------------------
1851
1852    procedure Analyze_Formal_Type_Declaration (N : Node_Id) is
1853       Def : constant Node_Id := Formal_Type_Definition (N);
1854       T   : Entity_Id;
1855
1856    begin
1857       T := Defining_Identifier (N);
1858
1859       if Present (Discriminant_Specifications (N))
1860         and then Nkind (Def) /= N_Formal_Private_Type_Definition
1861       then
1862          Error_Msg_N
1863            ("discriminants not allowed for this formal type",
1864             Defining_Identifier (First (Discriminant_Specifications (N))));
1865       end if;
1866
1867       --  Enter the new name, and branch to specific routine.
1868
1869       case Nkind (Def) is
1870          when N_Formal_Private_Type_Definition         =>
1871             Analyze_Formal_Private_Type (N, T, Def);
1872
1873          when N_Formal_Derived_Type_Definition         =>
1874             Analyze_Formal_Derived_Type (N, T, Def);
1875
1876          when N_Formal_Discrete_Type_Definition        =>
1877             Analyze_Formal_Discrete_Type (T, Def);
1878
1879          when N_Formal_Signed_Integer_Type_Definition  =>
1880             Analyze_Formal_Signed_Integer_Type (T, Def);
1881
1882          when N_Formal_Modular_Type_Definition         =>
1883             Analyze_Formal_Modular_Type (T, Def);
1884
1885          when N_Formal_Floating_Point_Definition       =>
1886             Analyze_Formal_Floating_Type (T, Def);
1887
1888          when N_Formal_Ordinary_Fixed_Point_Definition =>
1889             Analyze_Formal_Ordinary_Fixed_Point_Type (T, Def);
1890
1891          when N_Formal_Decimal_Fixed_Point_Definition  =>
1892             Analyze_Formal_Decimal_Fixed_Point_Type (T, Def);
1893
1894          when N_Array_Type_Definition =>
1895             Analyze_Formal_Array_Type (T, Def);
1896
1897          when N_Access_To_Object_Definition            |
1898               N_Access_Function_Definition             |
1899               N_Access_Procedure_Definition            =>
1900             Analyze_Generic_Access_Type (T, Def);
1901
1902          when N_Error                                  =>
1903             null;
1904
1905          when others                                   =>
1906             raise Program_Error;
1907
1908       end case;
1909
1910       Set_Is_Generic_Type (T);
1911    end Analyze_Formal_Type_Declaration;
1912
1913    ------------------------------------
1914    -- Analyze_Function_Instantiation --
1915    ------------------------------------
1916
1917    procedure Analyze_Function_Instantiation (N : Node_Id) is
1918    begin
1919       Analyze_Subprogram_Instantiation (N, E_Function);
1920    end Analyze_Function_Instantiation;
1921
1922    ---------------------------------
1923    -- Analyze_Generic_Access_Type --
1924    ---------------------------------
1925
1926    procedure Analyze_Generic_Access_Type (T : Entity_Id; Def : Node_Id) is
1927    begin
1928       Enter_Name (T);
1929
1930       if Nkind (Def) = N_Access_To_Object_Definition then
1931          Access_Type_Declaration (T, Def);
1932
1933          if Is_Incomplete_Or_Private_Type (Designated_Type (T))
1934            and then No (Full_View (Designated_Type (T)))
1935            and then not Is_Generic_Type (Designated_Type (T))
1936          then
1937             Error_Msg_N ("premature usage of incomplete type", Def);
1938
1939          elsif Is_Internal (Designated_Type (T)) then
1940             Error_Msg_N
1941               ("only a subtype mark is allowed in a formal", Def);
1942          end if;
1943
1944       else
1945          Access_Subprogram_Declaration (T, Def);
1946       end if;
1947    end Analyze_Generic_Access_Type;
1948
1949    ---------------------------------
1950    -- Analyze_Generic_Formal_Part --
1951    ---------------------------------
1952
1953    procedure Analyze_Generic_Formal_Part (N : Node_Id) is
1954       Gen_Parm_Decl : Node_Id;
1955
1956    begin
1957       --  The generic formals are processed in the scope of the generic
1958       --  unit, where they are immediately visible. The scope is installed
1959       --  by the caller.
1960
1961       Gen_Parm_Decl := First (Generic_Formal_Declarations (N));
1962
1963       while Present (Gen_Parm_Decl) loop
1964          Analyze (Gen_Parm_Decl);
1965          Next (Gen_Parm_Decl);
1966       end loop;
1967    end Analyze_Generic_Formal_Part;
1968
1969    ------------------------------------------
1970    -- Analyze_Generic_Package_Declaration  --
1971    ------------------------------------------
1972
1973    procedure Analyze_Generic_Package_Declaration (N : Node_Id) is
1974       Id          : Entity_Id;
1975       New_N       : Node_Id;
1976       Save_Parent : Node_Id;
1977
1978    begin
1979       --  Create copy of generic unit, and save for instantiation.
1980       --  If the unit is a child unit, do not copy the specifications
1981       --  for the parent, which are not part of the generic tree.
1982
1983       Save_Parent := Parent_Spec (N);
1984       Set_Parent_Spec (N, Empty);
1985
1986       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
1987       Set_Parent_Spec (New_N, Save_Parent);
1988       Rewrite (N, New_N);
1989       Id := Defining_Entity (N);
1990       Generate_Definition (Id);
1991
1992       --  Expansion is not applied to generic units.
1993
1994       Start_Generic;
1995
1996       Enter_Name (Id);
1997       Set_Ekind (Id, E_Generic_Package);
1998       Set_Etype (Id, Standard_Void_Type);
1999       New_Scope (Id);
2000       Enter_Generic_Scope (Id);
2001       Set_Inner_Instances (Id, New_Elmt_List);
2002
2003       Set_Categorization_From_Pragmas (N);
2004       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2005
2006       --  For a library unit, we have reconstructed the entity for the
2007       --  unit, and must reset it in the library tables.
2008
2009       if Nkind (Parent (N)) = N_Compilation_Unit then
2010          Set_Cunit_Entity (Current_Sem_Unit, Id);
2011       end if;
2012
2013       Analyze_Generic_Formal_Part (N);
2014
2015       --  After processing the generic formals, analysis proceeds
2016       --  as for a non-generic package.
2017
2018       Analyze (Specification (N));
2019
2020       Validate_Categorization_Dependency (N, Id);
2021
2022       End_Generic;
2023
2024       End_Package_Scope (Id);
2025       Exit_Generic_Scope (Id);
2026
2027       if Nkind (Parent (N)) /= N_Compilation_Unit then
2028          Move_Freeze_Nodes (Id, N, Visible_Declarations (Specification (N)));
2029          Move_Freeze_Nodes (Id, N, Private_Declarations (Specification (N)));
2030          Move_Freeze_Nodes (Id, N, Generic_Formal_Declarations (N));
2031
2032       else
2033          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2034          Validate_RT_RAT_Component (N);
2035       end if;
2036
2037    end Analyze_Generic_Package_Declaration;
2038
2039    --------------------------------------------
2040    -- Analyze_Generic_Subprogram_Declaration --
2041    --------------------------------------------
2042
2043    procedure Analyze_Generic_Subprogram_Declaration (N : Node_Id) is
2044       Spec        : Node_Id;
2045       Id          : Entity_Id;
2046       Formals     : List_Id;
2047       New_N       : Node_Id;
2048       Save_Parent : Node_Id;
2049
2050    begin
2051       --  Create copy of generic unit,and save for instantiation.
2052       --  If the unit is a child unit, do not copy the specifications
2053       --  for the parent, which are not part of the generic tree.
2054
2055       Save_Parent := Parent_Spec (N);
2056       Set_Parent_Spec (N, Empty);
2057
2058       New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
2059       Set_Parent_Spec (New_N, Save_Parent);
2060       Rewrite (N, New_N);
2061
2062       Spec := Specification (N);
2063       Id := Defining_Entity (Spec);
2064       Generate_Definition (Id);
2065
2066       if Nkind (Id) = N_Defining_Operator_Symbol then
2067          Error_Msg_N
2068            ("operator symbol not allowed for generic subprogram", Id);
2069       end if;
2070
2071       Start_Generic;
2072
2073       Enter_Name (Id);
2074
2075       Set_Scope_Depth_Value (Id, Scope_Depth (Current_Scope) + 1);
2076       New_Scope (Id);
2077       Enter_Generic_Scope (Id);
2078       Set_Inner_Instances (Id, New_Elmt_List);
2079       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2080
2081       Analyze_Generic_Formal_Part (N);
2082
2083       Formals := Parameter_Specifications (Spec);
2084
2085       if Present (Formals) then
2086          Process_Formals (Id, Formals, Spec);
2087       end if;
2088
2089       if Nkind (Spec) = N_Function_Specification then
2090          Set_Ekind (Id, E_Generic_Function);
2091          Find_Type (Subtype_Mark (Spec));
2092          Set_Etype (Id, Entity (Subtype_Mark (Spec)));
2093       else
2094          Set_Ekind (Id, E_Generic_Procedure);
2095          Set_Etype (Id, Standard_Void_Type);
2096       end if;
2097
2098       --  For a library unit, we have reconstructed the entity for the
2099       --  unit, and must reset it in the library tables. We also need
2100       --  to make sure that Body_Required is set properly in the original
2101       --  compilation unit node.
2102
2103       if Nkind (Parent (N)) = N_Compilation_Unit then
2104          Set_Cunit_Entity (Current_Sem_Unit, Id);
2105          Set_Body_Required (Parent (N), Unit_Requires_Body (Id));
2106       end if;
2107
2108       Set_Categorization_From_Pragmas (N);
2109       Validate_Categorization_Dependency (N, Id);
2110
2111       Save_Global_References (Original_Node (N));
2112
2113       End_Generic;
2114       End_Scope;
2115       Exit_Generic_Scope (Id);
2116
2117    end Analyze_Generic_Subprogram_Declaration;
2118
2119    -----------------------------------
2120    -- Analyze_Package_Instantiation --
2121    -----------------------------------
2122
2123    --  Note: this procedure is also used for formal package declarations,
2124    --  in which case the argument N is an N_Formal_Package_Declaration
2125    --  node. This should really be noted in the spec! ???
2126
2127    procedure Analyze_Package_Instantiation (N : Node_Id) is
2128       Loc     : constant Source_Ptr := Sloc (N);
2129       Gen_Id  : constant Node_Id    := Name (N);
2130
2131       Act_Decl      : Node_Id;
2132       Act_Decl_Name : Node_Id;
2133       Act_Decl_Id   : Entity_Id;
2134       Act_Spec      : Node_Id;
2135       Act_Tree      : Node_Id;
2136
2137       Gen_Decl : Node_Id;
2138       Gen_Unit : Entity_Id;
2139
2140       Is_Actual_Pack   : Boolean := Is_Internal (Defining_Entity (N));
2141       Parent_Installed : Boolean := False;
2142       Renaming_List    : List_Id;
2143       Unit_Renaming    : Node_Id;
2144       Needs_Body       : Boolean;
2145       Inline_Now       : Boolean := False;
2146
2147       procedure Delay_Descriptors (E : Entity_Id);
2148       --  Delay generation of subprogram descriptors for given entity
2149
2150       function Might_Inline_Subp return Boolean;
2151       --  If inlining is active and the generic contains inlined subprograms,
2152       --  we instantiate the body. This may cause superfluous instantiations,
2153       --  but it is simpler than detecting the need for the body at the point
2154       --  of inlining, when the context of the instance is not available.
2155
2156       -----------------------
2157       -- Delay_Descriptors --
2158       -----------------------
2159
2160       procedure Delay_Descriptors (E : Entity_Id) is
2161       begin
2162          if not Delay_Subprogram_Descriptors (E) then
2163             Set_Delay_Subprogram_Descriptors (E);
2164             Pending_Descriptor.Increment_Last;
2165             Pending_Descriptor.Table (Pending_Descriptor.Last) := E;
2166          end if;
2167       end Delay_Descriptors;
2168
2169       -----------------------
2170       -- Might_Inline_Subp --
2171       -----------------------
2172
2173       function Might_Inline_Subp return Boolean is
2174          E : Entity_Id;
2175
2176       begin
2177          if not Inline_Processing_Required then
2178             return False;
2179
2180          else
2181             E := First_Entity (Gen_Unit);
2182
2183             while Present (E) loop
2184
2185                if Is_Subprogram (E)
2186                  and then Is_Inlined (E)
2187                then
2188                   return True;
2189                end if;
2190
2191                Next_Entity (E);
2192             end loop;
2193          end if;
2194
2195          return False;
2196       end Might_Inline_Subp;
2197
2198    --  Start of processing for Analyze_Package_Instantiation
2199
2200    begin
2201       --  Very first thing: apply the special kludge for Text_IO processing
2202       --  in case we are instantiating one of the children of [Wide_]Text_IO.
2203
2204       Text_IO_Kludge (Name (N));
2205
2206       --  Make node global for error reporting.
2207
2208       Instantiation_Node := N;
2209
2210       --  Case of instantiation of a generic package
2211
2212       if Nkind (N) = N_Package_Instantiation then
2213          Act_Decl_Id := New_Copy (Defining_Entity (N));
2214          Set_Comes_From_Source (Act_Decl_Id, True);
2215
2216          if Nkind (Defining_Unit_Name (N)) = N_Defining_Program_Unit_Name then
2217             Act_Decl_Name :=
2218               Make_Defining_Program_Unit_Name (Loc,
2219                 Name => New_Copy_Tree (Name (Defining_Unit_Name (N))),
2220                 Defining_Identifier => Act_Decl_Id);
2221          else
2222             Act_Decl_Name :=  Act_Decl_Id;
2223          end if;
2224
2225       --  Case of instantiation of a formal package
2226
2227       else
2228          Act_Decl_Id   := Defining_Identifier (N);
2229          Act_Decl_Name := Act_Decl_Id;
2230       end if;
2231
2232       Generate_Definition (Act_Decl_Id);
2233       Pre_Analyze_Actuals (N);
2234
2235       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
2236       Gen_Unit := Entity (Gen_Id);
2237
2238       --  Verify that it is the name of a generic package
2239
2240       if Etype (Gen_Unit) = Any_Type then
2241          return;
2242
2243       elsif Ekind (Gen_Unit) /= E_Generic_Package then
2244          Error_Msg_N
2245            ("expect name of generic package in instantiation", Gen_Id);
2246          return;
2247       end if;
2248
2249       if In_Extended_Main_Source_Unit (N) then
2250          Set_Is_Instantiated (Gen_Unit);
2251          Generate_Reference  (Gen_Unit, N);
2252
2253          if Present (Renamed_Object (Gen_Unit)) then
2254             Set_Is_Instantiated (Renamed_Object (Gen_Unit));
2255             Generate_Reference  (Renamed_Object (Gen_Unit), N);
2256          end if;
2257       end if;
2258
2259       if Nkind (Gen_Id) = N_Identifier
2260         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
2261       then
2262          Error_Msg_NE
2263            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
2264
2265       elsif Nkind (Gen_Id) = N_Expanded_Name
2266         and then Is_Child_Unit (Gen_Unit)
2267         and then Nkind (Prefix (Gen_Id)) = N_Identifier
2268         and then Chars (Act_Decl_Id) = Chars (Prefix (Gen_Id))
2269       then
2270          Error_Msg_N
2271            ("& is hidden within declaration of instance ", Prefix (Gen_Id));
2272       end if;
2273
2274       --  If renaming, indicate this is an instantiation of renamed unit.
2275
2276       if Present (Renamed_Object (Gen_Unit))
2277         and then Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Package
2278       then
2279          Gen_Unit := Renamed_Object (Gen_Unit);
2280          Set_Entity (Gen_Id, Gen_Unit);
2281       end if;
2282
2283       --  Verify that there are no circular instantiations.
2284
2285       if In_Open_Scopes (Gen_Unit) then
2286          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
2287          return;
2288
2289       elsif Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
2290          Error_Msg_Node_2 := Current_Scope;
2291          Error_Msg_NE
2292            ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
2293          Circularity_Detected := True;
2294          return;
2295
2296       else
2297          Save_Env (Gen_Unit, Act_Decl_Id);
2298          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
2299
2300          --  Initialize renamings map, for error checking, and the list
2301          --  that holds private entities whose views have changed between
2302          --  generic definition and instantiation. If this is the instance
2303          --  created to validate an actual package, the instantiation
2304          --  environment is that of the enclosing instance.
2305
2306          Generic_Renamings.Set_Last (0);
2307          Generic_Renamings_HTable.Reset;
2308
2309          Create_Instantiation_Source (N, Gen_Unit, S_Adjustment);
2310
2311          --  Copy original generic tree, to produce text for instantiation.
2312
2313          Act_Tree :=
2314            Copy_Generic_Node
2315              (Original_Node (Gen_Decl), Empty, Instantiating => True);
2316
2317          Act_Spec := Specification (Act_Tree);
2318
2319          --  If this is the instance created to validate an actual package,
2320          --  only the formals matter, do not examine the package spec itself.
2321
2322          if Is_Actual_Pack then
2323             Set_Visible_Declarations (Act_Spec, New_List);
2324             Set_Private_Declarations (Act_Spec, New_List);
2325          end if;
2326
2327          Renaming_List :=
2328            Analyze_Associations
2329              (N,
2330               Generic_Formal_Declarations (Act_Tree),
2331               Generic_Formal_Declarations (Gen_Decl));
2332
2333          Set_Defining_Unit_Name (Act_Spec, Act_Decl_Name);
2334          Set_Is_Generic_Instance (Act_Decl_Id);
2335
2336          Set_Generic_Parent (Act_Spec, Gen_Unit);
2337
2338          --  References to the generic in its own declaration or its body
2339          --  are references to the instance. Add a renaming declaration for
2340          --  the generic unit itself. This declaration, as well as the renaming
2341          --  declarations for the generic formals, must remain private to the
2342          --  unit: the formals, because this is the language semantics, and
2343          --  the unit because its use is an artifact of the implementation.
2344
2345          Unit_Renaming :=
2346            Make_Package_Renaming_Declaration (Loc,
2347              Defining_Unit_Name =>
2348                Make_Defining_Identifier (Loc, Chars (Gen_Unit)),
2349              Name => New_Reference_To (Act_Decl_Id, Loc));
2350
2351          Append (Unit_Renaming, Renaming_List);
2352
2353          --  The renaming declarations are the first local declarations of
2354          --  the new unit.
2355
2356          if Is_Non_Empty_List (Visible_Declarations (Act_Spec)) then
2357             Insert_List_Before
2358               (First (Visible_Declarations (Act_Spec)), Renaming_List);
2359          else
2360             Set_Visible_Declarations (Act_Spec, Renaming_List);
2361          end if;
2362
2363          Act_Decl :=
2364            Make_Package_Declaration (Loc,
2365              Specification => Act_Spec);
2366
2367          --  Save the instantiation node, for subsequent instantiation
2368          --  of the body, if there is one and we are generating code for
2369          --  the current unit. Mark the unit as having a body, to avoid
2370          --  a premature error message.
2371
2372          --  We instantiate the body if we are generating code, if we are
2373          --  generating cross-reference information, or if we are building
2374          --  trees for ASIS use.
2375
2376          declare
2377             Enclosing_Body_Present : Boolean := False;
2378             Scop : Entity_Id;
2379
2380          begin
2381             if Scope (Gen_Unit) /= Standard_Standard
2382               and then not Is_Child_Unit (Gen_Unit)
2383             then
2384                Scop := Scope (Gen_Unit);
2385
2386                while Present (Scop)
2387                  and then Scop /= Standard_Standard
2388                loop
2389                   if Unit_Requires_Body (Scop) then
2390                      Enclosing_Body_Present := True;
2391                      exit;
2392                   end if;
2393
2394                   Scop := Scope (Scop);
2395                end loop;
2396             end if;
2397
2398             --  If front-end inlining is enabled, and this is a unit for which
2399             --  code will be generated, we instantiate the body at once.
2400             --  This is done if the instance is not the main unit, and if the
2401             --  generic is not a child unit, to avoid scope problems.
2402
2403             if Front_End_Inlining
2404               and then Expander_Active
2405               and then not Is_Child_Unit (Gen_Unit)
2406               and then Is_In_Main_Unit (N)
2407               and then Nkind (Parent (N)) /= N_Compilation_Unit
2408               and then Might_Inline_Subp
2409             then
2410                Inline_Now := True;
2411             end if;
2412
2413             Needs_Body :=
2414               (Unit_Requires_Body (Gen_Unit)
2415                   or else Enclosing_Body_Present
2416                   or else Present (Corresponding_Body (Gen_Decl)))
2417                 and then (Is_In_Main_Unit (N)
2418                            or else Might_Inline_Subp)
2419                 and then not Is_Actual_Pack
2420                 and then not Inline_Now
2421
2422                 and then (Operating_Mode = Generate_Code
2423                             or else (Operating_Mode = Check_Semantics
2424                                       and then Tree_Output));
2425
2426             --  If front_end_inlining is enabled, do not instantiate a
2427             --  body if within a generic context.
2428
2429             if Front_End_Inlining
2430               and then not Expander_Active
2431             then
2432                Needs_Body := False;
2433             end if;
2434
2435          end;
2436
2437          --  If we are generating the calling stubs from the instantiation
2438          --  of a generic RCI package, we will not use the body of the
2439          --  generic package.
2440
2441          if Distribution_Stub_Mode = Generate_Caller_Stub_Body
2442            and then Is_Compilation_Unit (Defining_Entity (N))
2443          then
2444             Needs_Body := False;
2445          end if;
2446
2447          if Needs_Body then
2448
2449             --  Here is a defence against a ludicrous number of instantiations
2450             --  caused by a circular set of instantiation attempts.
2451
2452             if Pending_Instantiations.Last >
2453                  Hostparm.Max_Instantiations
2454             then
2455                Error_Msg_N ("too many instantiations", N);
2456                raise Unrecoverable_Error;
2457             end if;
2458
2459             --  Indicate that the enclosing scopes contain an instantiation,
2460             --  and that cleanup actions should be delayed until after the
2461             --  instance body is expanded.
2462
2463             Check_Forward_Instantiation (N, Gen_Decl);
2464             if Nkind (N) = N_Package_Instantiation then
2465                declare
2466                   Enclosing_Master : Entity_Id := Current_Scope;
2467
2468                begin
2469                   while Enclosing_Master /= Standard_Standard loop
2470
2471                      if Ekind (Enclosing_Master) = E_Package then
2472                         if Is_Compilation_Unit (Enclosing_Master) then
2473                            if In_Package_Body (Enclosing_Master) then
2474                               Delay_Descriptors
2475                                 (Body_Entity (Enclosing_Master));
2476                            else
2477                               Delay_Descriptors
2478                                 (Enclosing_Master);
2479                            end if;
2480
2481                            exit;
2482
2483                         else
2484                            Enclosing_Master := Scope (Enclosing_Master);
2485                         end if;
2486
2487                      elsif Ekind (Enclosing_Master) = E_Generic_Package then
2488                         Enclosing_Master := Scope (Enclosing_Master);
2489
2490                      elsif Ekind (Enclosing_Master) = E_Generic_Function
2491                        or else Ekind (Enclosing_Master) = E_Generic_Procedure
2492                        or else Ekind (Enclosing_Master) = E_Void
2493                      then
2494                         --  Cleanup actions will eventually be performed on
2495                         --  the enclosing instance, if any. enclosing scope
2496                         --  is void in the formal part of a generic subp.
2497
2498                         exit;
2499
2500                      else
2501                         if Ekind (Enclosing_Master) = E_Entry
2502                           and then
2503                             Ekind (Scope (Enclosing_Master)) = E_Protected_Type
2504                         then
2505                            Enclosing_Master :=
2506                              Protected_Body_Subprogram (Enclosing_Master);
2507                         end if;
2508
2509                         Set_Delay_Cleanups (Enclosing_Master);
2510
2511                         while Ekind (Enclosing_Master) = E_Block loop
2512                            Enclosing_Master := Scope (Enclosing_Master);
2513                         end loop;
2514
2515                         if Is_Subprogram (Enclosing_Master) then
2516                            Delay_Descriptors (Enclosing_Master);
2517
2518                         elsif Is_Task_Type (Enclosing_Master) then
2519                            declare
2520                               TBP : constant Node_Id :=
2521                                       Get_Task_Body_Procedure
2522                                         (Enclosing_Master);
2523
2524                            begin
2525                               if Present (TBP) then
2526                                  Delay_Descriptors  (TBP);
2527                                  Set_Delay_Cleanups (TBP);
2528                               end if;
2529                            end;
2530                         end if;
2531
2532                         exit;
2533                      end if;
2534                   end loop;
2535                end;
2536
2537                --  Make entry in table
2538
2539                Pending_Instantiations.Increment_Last;
2540                Pending_Instantiations.Table (Pending_Instantiations.Last) :=
2541                  (N, Act_Decl, Expander_Active, Current_Sem_Unit);
2542             end if;
2543          end if;
2544
2545          Set_Categorization_From_Pragmas (Act_Decl);
2546
2547          if Parent_Installed then
2548             Hide_Current_Scope;
2549          end if;
2550
2551          Set_Instance_Spec (N, Act_Decl);
2552
2553          --  If not a compilation unit, insert the package declaration
2554          --  after the instantiation node.
2555
2556          if Nkind (Parent (N)) /= N_Compilation_Unit then
2557             Mark_Rewrite_Insertion (Act_Decl);
2558             Insert_Before (N, Act_Decl);
2559             Analyze (Act_Decl);
2560
2561          --  For an instantiation that is a compilation unit, place
2562          --  declaration on current node so context is complete
2563          --  for analysis (including nested instantiations). It this
2564          --  is the main unit, the declaration eventually replaces the
2565          --  instantiation node. If the instance body is later created, it
2566          --  replaces the instance node, and the declation is attached to
2567          --  it (see Build_Instance_Compilation_Unit_Nodes).
2568
2569          else
2570             if Cunit_Entity (Current_Sem_Unit) = Defining_Entity (N) then
2571
2572                --  The entity for the current unit is the newly created one,
2573                --  and all semantic information is attached to it.
2574
2575                Set_Cunit_Entity (Current_Sem_Unit, Act_Decl_Id);
2576
2577                --  If this is the main unit, replace the main entity as well.
2578
2579                if Current_Sem_Unit = Main_Unit then
2580                   Main_Unit_Entity := Act_Decl_Id;
2581                end if;
2582             end if;
2583
2584             Set_Unit (Parent (N), Act_Decl);
2585             Set_Parent_Spec (Act_Decl, Parent_Spec (N));
2586             Analyze (Act_Decl);
2587             Set_Unit (Parent (N), N);
2588             Set_Body_Required (Parent (N), False);
2589
2590             --  We never need elaboration checks on instantiations, since
2591             --  by definition, the body instantiation is elaborated at the
2592             --  same time as the spec instantiation.
2593
2594             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
2595             Set_Suppress_Elaboration_Checks   (Act_Decl_Id);
2596          end if;
2597
2598          Check_Elab_Instantiation (N);
2599
2600          if ABE_Is_Certain (N) and then Needs_Body then
2601             Pending_Instantiations.Decrement_Last;
2602          end if;
2603          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
2604
2605          Set_First_Private_Entity (Defining_Unit_Name (Unit_Renaming),
2606            First_Private_Entity (Act_Decl_Id));
2607
2608          if Nkind (Parent (N)) = N_Compilation_Unit
2609            and then not Needs_Body
2610          then
2611             Rewrite (N, Act_Decl);
2612          end if;
2613
2614          if Present (Corresponding_Body (Gen_Decl))
2615            or else Unit_Requires_Body (Gen_Unit)
2616          then
2617             Set_Has_Completion (Act_Decl_Id);
2618          end if;
2619
2620          Check_Formal_Packages (Act_Decl_Id);
2621
2622          Restore_Private_Views (Act_Decl_Id);
2623
2624          if not Generic_Separately_Compiled (Gen_Unit) then
2625             Inherit_Context (Gen_Decl, N);
2626          end if;
2627
2628          if Parent_Installed then
2629             Remove_Parent;
2630          end if;
2631
2632          Restore_Env;
2633       end if;
2634
2635       Validate_Categorization_Dependency (N, Act_Decl_Id);
2636
2637       --  Check restriction, but skip this if something went wrong in
2638       --  the above analysis, indicated by Act_Decl_Id being void.
2639
2640       if Ekind (Act_Decl_Id) /= E_Void
2641         and then not Is_Library_Level_Entity (Act_Decl_Id)
2642       then
2643          Check_Restriction (No_Local_Allocators, N);
2644       end if;
2645
2646       if Inline_Now then
2647          Inline_Instance_Body (N, Gen_Unit, Act_Decl);
2648       end if;
2649
2650    exception
2651       when Instantiation_Error =>
2652          if Parent_Installed then
2653             Remove_Parent;
2654          end if;
2655
2656    end Analyze_Package_Instantiation;
2657
2658    ---------------------------
2659    --  Inline_Instance_Body --
2660    ---------------------------
2661
2662    procedure Inline_Instance_Body
2663      (N        : Node_Id;
2664       Gen_Unit : Entity_Id;
2665       Act_Decl : Node_Id)
2666    is
2667       Vis          : Boolean;
2668       Gen_Comp     : constant Entity_Id :=
2669                       Cunit_Entity (Get_Source_Unit (Gen_Unit));
2670       Curr_Comp    : constant Node_Id := Cunit (Current_Sem_Unit);
2671       Curr_Scope   : Entity_Id := Empty;
2672       Curr_Unit    : constant Entity_Id :=
2673                        Cunit_Entity (Current_Sem_Unit);
2674       Removed      : Boolean := False;
2675       Num_Scopes   : Int := 0;
2676       Use_Clauses  : array (1 .. Scope_Stack.Last) of Node_Id;
2677       Instances    : array (1 .. Scope_Stack.Last) of Entity_Id;
2678       Inner_Scopes : array (1 .. Scope_Stack.Last) of Entity_Id;
2679       Num_Inner    : Int := 0;
2680       N_Instances  : Int := 0;
2681       S            : Entity_Id;
2682
2683    begin
2684       --  Case of generic unit defined in another unit
2685
2686       if Gen_Comp /= Cunit_Entity (Current_Sem_Unit) then
2687          Vis := Is_Immediately_Visible (Gen_Comp);
2688
2689          S := Current_Scope;
2690
2691          while Present (S)
2692            and then S /= Standard_Standard
2693          loop
2694             Num_Scopes := Num_Scopes + 1;
2695
2696             Use_Clauses (Num_Scopes) :=
2697               (Scope_Stack.Table
2698                  (Scope_Stack.Last - Num_Scopes + 1).
2699                     First_Use_Clause);
2700             End_Use_Clauses (Use_Clauses (Num_Scopes));
2701
2702             exit when Is_Generic_Instance (S)
2703               and then (In_Package_Body (S)
2704                           or else Ekind (S) = E_Procedure
2705                           or else Ekind (S) = E_Function);
2706             S := Scope (S);
2707          end loop;
2708
2709          --  Find and save all enclosing instances
2710
2711          S := Current_Scope;
2712
2713          while Present (S)
2714            and then S /= Standard_Standard
2715          loop
2716             if Is_Generic_Instance (S) then
2717                N_Instances := N_Instances + 1;
2718                Instances (N_Instances) := S;
2719             end if;
2720
2721             S := Scope (S);
2722          end loop;
2723
2724          --  Remove context of current compilation unit, unless we
2725          --  are within a nested package instantiation, in which case
2726          --  the context has been removed previously.
2727
2728          --  If current scope is the body of a child unit, remove context
2729          --  of spec as well.
2730
2731          S := Current_Scope;
2732
2733          while Present (S)
2734            and then S /= Standard_Standard
2735          loop
2736             exit when Is_Generic_Instance (S)
2737                  and then (In_Package_Body (S)
2738                             or else Ekind (S) = E_Procedure
2739                             or else Ekind (S) = E_Function);
2740
2741             if S = Curr_Unit
2742               or else (Ekind (Curr_Unit) = E_Package_Body
2743                         and then S = Spec_Entity (Curr_Unit))
2744             then
2745                Removed := True;
2746
2747                --  Remove entities in current scopes from visibility, so
2748                --  than instance body is compiled in a clean environment.
2749
2750                Save_Scope_Stack;
2751
2752                if Is_Child_Unit (S) then
2753
2754                   --  Remove child unit from stack, as well as inner scopes.
2755                   --  Removing the context of a child unit removes parent
2756                   --  units as well.
2757
2758                   while Current_Scope /= S loop
2759                      Num_Inner := Num_Inner + 1;
2760                      Inner_Scopes (Num_Inner) := Current_Scope;
2761                      Pop_Scope;
2762                   end loop;
2763
2764                   Pop_Scope;
2765                   Remove_Context (Curr_Comp);
2766                   Curr_Scope := S;
2767
2768                else
2769                   Remove_Context (Curr_Comp);
2770                end if;
2771
2772                if Ekind (Curr_Unit) = E_Package_Body then
2773                   Remove_Context (Library_Unit (Curr_Comp));
2774                end if;
2775             end if;
2776
2777             S := Scope (S);
2778          end loop;
2779
2780          New_Scope (Standard_Standard);
2781          Instantiate_Package_Body
2782            ((N, Act_Decl, Expander_Active, Current_Sem_Unit));
2783          Pop_Scope;
2784
2785          --  Restore context
2786
2787          Set_Is_Immediately_Visible (Gen_Comp, Vis);
2788
2789          --  Reset Generic_Instance flag so that use clauses can be installed
2790          --  in the proper order. (See Use_One_Package for effect of enclosing
2791          --  instances on processing of use clauses).
2792
2793          for J in 1 .. N_Instances loop
2794             Set_Is_Generic_Instance (Instances (J), False);
2795          end loop;
2796
2797          if Removed then
2798             Install_Context (Curr_Comp);
2799
2800             if Present (Curr_Scope)
2801               and then Is_Child_Unit (Curr_Scope)
2802             then
2803                New_Scope (Curr_Scope);
2804                Set_Is_Immediately_Visible (Curr_Scope);
2805
2806                --  Finally, restore inner scopes as well.
2807
2808                for J in reverse 1 .. Num_Inner loop
2809                   New_Scope (Inner_Scopes (J));
2810                end loop;
2811             end if;
2812
2813             Restore_Scope_Stack;
2814          end if;
2815
2816          for J in reverse 1 .. Num_Scopes loop
2817             Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause :=
2818               Use_Clauses (J);
2819             Install_Use_Clauses (Use_Clauses (J));
2820          end  loop;
2821
2822          for J in 1 .. N_Instances loop
2823             Set_Is_Generic_Instance (Instances (J), True);
2824          end loop;
2825
2826       --  If generic unit is in current unit, current context is correct.
2827
2828       else
2829          Instantiate_Package_Body
2830            ((N, Act_Decl, Expander_Active, Current_Sem_Unit));
2831       end if;
2832    end Inline_Instance_Body;
2833
2834    -------------------------------------
2835    -- Analyze_Procedure_Instantiation --
2836    -------------------------------------
2837
2838    procedure Analyze_Procedure_Instantiation (N : Node_Id) is
2839    begin
2840       Analyze_Subprogram_Instantiation (N, E_Procedure);
2841    end Analyze_Procedure_Instantiation;
2842
2843    --------------------------------------
2844    -- Analyze_Subprogram_Instantiation --
2845    --------------------------------------
2846
2847    procedure Analyze_Subprogram_Instantiation
2848      (N : Node_Id;
2849       K : Entity_Kind)
2850    is
2851       Loc              : constant Source_Ptr := Sloc (N);
2852       Gen_Id           : constant Node_Id    := Name (N);
2853
2854       Act_Decl_Id      : Entity_Id;
2855       Anon_Id          : Entity_Id :=
2856                            Make_Defining_Identifier
2857                              (Sloc (Defining_Entity (N)),
2858                              New_External_Name
2859                                (Chars (Defining_Entity (N)), 'R'));
2860       Act_Decl         : Node_Id;
2861       Act_Spec         : Node_Id;
2862       Act_Tree         : Node_Id;
2863
2864       Gen_Unit         : Entity_Id;
2865       Gen_Decl         : Node_Id;
2866       Pack_Id          : Entity_Id;
2867       Parent_Installed : Boolean := False;
2868       Renaming_List    : List_Id;
2869       Spec             : Node_Id;
2870
2871       procedure Analyze_Instance_And_Renamings;
2872       --  The instance must be analyzed in a context that includes the
2873       --  mappings of generic parameters into actuals. We create a package
2874       --  declaration for this purpose, and a subprogram with an internal
2875       --  name within the package. The subprogram instance is simply an
2876       --  alias for the internal subprogram, declared in the current scope.
2877
2878       ------------------------------------
2879       -- Analyze_Instance_And_Renamings --
2880       ------------------------------------
2881
2882       procedure Analyze_Instance_And_Renamings is
2883          Def_Ent   : constant Entity_Id := Defining_Entity (N);
2884          Pack_Decl : Node_Id;
2885
2886       begin
2887          if Nkind (Parent (N)) = N_Compilation_Unit then
2888
2889             --  For the case of a compilation unit, the container package
2890             --  has the same name as the instantiation, to insure that the
2891             --  binder calls the elaboration procedure with the right name.
2892             --  Copy the entity of the instance, which may have compilation
2893             --  level flags (eg. is_child_unit) set.
2894
2895             Pack_Id := New_Copy (Def_Ent);
2896
2897          else
2898             --  Otherwise we use the name of the instantiation concatenated
2899             --  with its source position to ensure uniqueness if there are
2900             --  several instantiations with the same name.
2901
2902             Pack_Id :=
2903               Make_Defining_Identifier (Loc,
2904                 Chars => New_External_Name
2905                            (Related_Id   => Chars (Def_Ent),
2906                             Suffix       => "GP",
2907                             Suffix_Index => Source_Offset (Sloc (Def_Ent))));
2908          end if;
2909
2910          Pack_Decl := Make_Package_Declaration (Loc,
2911            Specification => Make_Package_Specification (Loc,
2912              Defining_Unit_Name   => Pack_Id,
2913              Visible_Declarations => Renaming_List,
2914              End_Label            => Empty));
2915
2916          Set_Instance_Spec (N, Pack_Decl);
2917          Set_Is_Generic_Instance (Pack_Id);
2918
2919          --  Case of not a compilation unit
2920
2921          if Nkind (Parent (N)) /= N_Compilation_Unit then
2922             Mark_Rewrite_Insertion (Pack_Decl);
2923             Insert_Before (N, Pack_Decl);
2924             Set_Has_Completion (Pack_Id);
2925
2926          --  Case of an instantiation that is a compilation unit
2927
2928          --  Place declaration on current node so context is complete
2929          --  for analysis (including nested instantiations), and for
2930          --  use in a context_clause (see Analyze_With_Clause).
2931
2932          else
2933             Set_Unit (Parent (N), Pack_Decl);
2934             Set_Parent_Spec (Pack_Decl, Parent_Spec (N));
2935          end if;
2936
2937          Analyze (Pack_Decl);
2938          Check_Formal_Packages (Pack_Id);
2939          Set_Is_Generic_Instance (Pack_Id, False);
2940
2941          --  Body of the enclosing package is supplied when instantiating
2942          --  the subprogram body, after semantic  analysis is completed.
2943
2944          if Nkind (Parent (N)) = N_Compilation_Unit then
2945
2946             --  Remove package itself from visibility, so it does not
2947             --  conflict with subprogram.
2948
2949             Set_Name_Entity_Id (Chars (Pack_Id), Homonym (Pack_Id));
2950
2951             --  Set name and scope of internal subprogram so that the
2952             --  proper external name will be generated. The proper scope
2953             --  is the scope of the wrapper package.
2954
2955             Set_Chars (Anon_Id, Chars (Defining_Entity (N)));
2956             Set_Scope (Anon_Id, Scope (Pack_Id));
2957          end if;
2958
2959          Set_Is_Generic_Instance (Anon_Id);
2960          Act_Decl_Id := New_Copy (Anon_Id);
2961
2962          Set_Parent            (Act_Decl_Id, Parent (Anon_Id));
2963          Set_Chars             (Act_Decl_Id, Chars (Defining_Entity (N)));
2964          Set_Sloc              (Act_Decl_Id, Sloc (Defining_Entity (N)));
2965          Set_Comes_From_Source (Act_Decl_Id, True);
2966
2967          --  The signature may involve types that are not frozen yet, but
2968          --  the subprogram will be frozen at the point the wrapper package
2969          --  is frozen, so it does not need its own freeze node. In fact, if
2970          --  one is created, it might conflict with the freezing actions from
2971          --  the wrapper package (see 7206-013).
2972
2973          Set_Has_Delayed_Freeze (Anon_Id, False);
2974
2975          --  If the instance is a child unit, mark the Id accordingly. Mark
2976          --  the anonymous entity as well, which is the real subprogram and
2977          --  which is used when the instance appears in a context clause.
2978
2979          Set_Is_Child_Unit (Act_Decl_Id, Is_Child_Unit (Defining_Entity (N)));
2980          Set_Is_Child_Unit (Anon_Id, Is_Child_Unit (Defining_Entity (N)));
2981          New_Overloaded_Entity (Act_Decl_Id);
2982          Check_Eliminated  (Act_Decl_Id);
2983
2984          --  In compilation unit case, kill elaboration checks on the
2985          --  instantiation, since they are never needed -- the body is
2986          --  instantiated at the same point as the spec.
2987
2988          if Nkind (Parent (N)) = N_Compilation_Unit then
2989             Set_Suppress_Elaboration_Warnings (Act_Decl_Id);
2990             Set_Suppress_Elaboration_Checks   (Act_Decl_Id);
2991             Set_Is_Compilation_Unit (Anon_Id);
2992
2993             Set_Cunit_Entity (Current_Sem_Unit, Pack_Id);
2994          end if;
2995
2996          --  The instance is not a freezing point for the new subprogram.
2997
2998          Set_Is_Frozen (Act_Decl_Id, False);
2999
3000          if Nkind (Defining_Entity (N)) = N_Defining_Operator_Symbol then
3001             Valid_Operator_Definition (Act_Decl_Id);
3002          end if;
3003
3004          Set_Alias  (Act_Decl_Id, Anon_Id);
3005          Set_Parent (Act_Decl_Id, Parent (Anon_Id));
3006          Set_Has_Completion (Act_Decl_Id);
3007          Set_Related_Instance (Pack_Id, Act_Decl_Id);
3008
3009          if Nkind (Parent (N)) = N_Compilation_Unit then
3010             Set_Body_Required (Parent (N), False);
3011          end if;
3012
3013       end Analyze_Instance_And_Renamings;
3014
3015    --  Start of processing for Analyze_Subprogram_Instantiation
3016
3017    begin
3018       --  Very first thing: apply the special kludge for Text_IO processing
3019       --  in case we are instantiating one of the children of [Wide_]Text_IO.
3020       --  Of course such an instantiation is bogus (these are packages, not
3021       --  subprograms), but we get a better error message if we do this.
3022
3023       Text_IO_Kludge (Gen_Id);
3024
3025       --  Make node global for error reporting.
3026
3027       Instantiation_Node := N;
3028       Pre_Analyze_Actuals (N);
3029
3030       Check_Generic_Child_Unit (Gen_Id, Parent_Installed);
3031       Gen_Unit := Entity (Gen_Id);
3032
3033       Generate_Reference (Gen_Unit, Gen_Id);
3034
3035       if Nkind (Gen_Id) = N_Identifier
3036         and then Chars (Gen_Unit) = Chars (Defining_Entity (N))
3037       then
3038          Error_Msg_NE
3039            ("& is hidden within declaration of instance", Gen_Id, Gen_Unit);
3040       end if;
3041
3042       if Etype (Gen_Unit) = Any_Type then return; end if;
3043
3044       --  Verify that it is a generic subprogram of the right kind, and that
3045       --  it does not lead to a circular instantiation.
3046
3047       if Ekind (Gen_Unit) /= E_Generic_Procedure
3048         and then Ekind (Gen_Unit) /= E_Generic_Function
3049       then
3050          Error_Msg_N ("expect generic subprogram in instantiation", Gen_Id);
3051
3052       elsif In_Open_Scopes (Gen_Unit) then
3053          Error_Msg_NE ("instantiation of & within itself", N, Gen_Unit);
3054
3055       elsif K = E_Procedure
3056         and then Ekind (Gen_Unit) /= E_Generic_Procedure
3057       then
3058          if Ekind (Gen_Unit) = E_Generic_Function then
3059             Error_Msg_N
3060               ("cannot instantiate generic function as procedure", Gen_Id);
3061          else
3062             Error_Msg_N
3063               ("expect name of generic procedure in instantiation", Gen_Id);
3064          end if;
3065
3066       elsif K = E_Function
3067         and then Ekind (Gen_Unit) /= E_Generic_Function
3068       then
3069          if Ekind (Gen_Unit) = E_Generic_Procedure then
3070             Error_Msg_N
3071               ("cannot instantiate generic procedure as function", Gen_Id);
3072          else
3073             Error_Msg_N
3074               ("expect name of generic function in instantiation", Gen_Id);
3075          end if;
3076
3077       else
3078          --  If renaming, indicate that this is instantiation of renamed unit
3079
3080          if Present (Renamed_Object (Gen_Unit))
3081            and then (Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Procedure
3082                        or else
3083                      Ekind (Renamed_Object (Gen_Unit)) = E_Generic_Function)
3084          then
3085             Gen_Unit := Renamed_Object (Gen_Unit);
3086             Set_Entity (Gen_Id, Gen_Unit);
3087          end if;
3088
3089          if Contains_Instance_Of (Gen_Unit, Current_Scope, Gen_Id) then
3090             Error_Msg_Node_2 := Current_Scope;
3091             Error_Msg_NE
3092               ("circular Instantiation: & instantiated in &!", N, Gen_Unit);
3093             Circularity_Detected := True;
3094             return;
3095          end if;
3096
3097          if In_Extended_Main_Source_Unit (N) then
3098             Set_Is_Instantiated (Gen_Unit);
3099             Generate_Reference  (Gen_Unit, N);
3100          end if;
3101
3102          Gen_Decl := Unit_Declaration_Node (Gen_Unit);
3103          Spec     := Specification (Gen_Decl);
3104
3105          --  The subprogram itself cannot contain a nested instance, so
3106          --  the current parent is left empty.
3107
3108          Save_Env (Gen_Unit, Empty);
3109
3110          --  Initialize renamings map, for error checking.
3111
3112          Generic_Renamings.Set_Last (0);
3113          Generic_Renamings_HTable.Reset;
3114
3115          Create_Instantiation_Source (N, Gen_Unit, S_Adjustment);
3116
3117          --  Copy original generic tree, to produce text for instantiation.
3118
3119          Act_Tree :=
3120            Copy_Generic_Node
3121              (Original_Node (Gen_Decl), Empty, Instantiating => True);
3122
3123          Act_Spec := Specification (Act_Tree);
3124          Renaming_List :=
3125            Analyze_Associations
3126              (N,
3127               Generic_Formal_Declarations (Act_Tree),
3128               Generic_Formal_Declarations (Gen_Decl));
3129
3130          --  Build the subprogram declaration, which does not appear
3131          --  in the generic template, and give it a sloc consistent
3132          --  with that of the template.
3133
3134          Set_Defining_Unit_Name (Act_Spec, Anon_Id);
3135          Set_Generic_Parent (Act_Spec, Gen_Unit);
3136          Act_Decl :=
3137            Make_Subprogram_Declaration (Sloc (Act_Spec),
3138              Specification => Act_Spec);
3139
3140          Set_Categorization_From_Pragmas (Act_Decl);
3141
3142          if Parent_Installed then
3143             Hide_Current_Scope;
3144          end if;
3145
3146          Append (Act_Decl, Renaming_List);
3147          Analyze_Instance_And_Renamings;
3148
3149          --  If the generic is marked Import (Intrinsic), then so is the
3150          --  instance. This indicates that there is no body to instantiate.
3151          --  If generic is marked inline, so it the instance, and the
3152          --  anonymous subprogram it renames. If inlined, or else if inlining
3153          --  is enabled for the compilation, we generate the instance body
3154          --  even if it is not within the main unit.
3155
3156          --  Any other  pragmas might also be inherited ???
3157
3158          if Is_Intrinsic_Subprogram (Gen_Unit) then
3159             Set_Is_Intrinsic_Subprogram (Anon_Id);
3160             Set_Is_Intrinsic_Subprogram (Act_Decl_Id);
3161
3162             if Chars (Gen_Unit) = Name_Unchecked_Conversion then
3163                Validate_Unchecked_Conversion (N, Act_Decl_Id);
3164             end if;
3165          end if;
3166
3167          Generate_Definition (Act_Decl_Id);
3168
3169          Set_Is_Inlined (Act_Decl_Id, Is_Inlined (Gen_Unit));
3170          Set_Is_Inlined (Anon_Id,     Is_Inlined (Gen_Unit));
3171
3172          Check_Elab_Instantiation (N);
3173          Check_Hidden_Child_Unit (N, Gen_Unit, Act_Decl_Id);
3174
3175          --  Subject to change, pending on if other pragmas are inherited ???
3176
3177          Validate_Categorization_Dependency (N, Act_Decl_Id);
3178
3179          if not Is_Intrinsic_Subprogram (Act_Decl_Id) then
3180
3181             if not Generic_Separately_Compiled (Gen_Unit) then
3182                Inherit_Context (Gen_Decl, N);
3183             end if;
3184
3185             Restore_Private_Views (Pack_Id, False);
3186
3187             --  If the context requires a full instantiation, mark node for
3188             --  subsequent construction of the body.
3189
3190             if (Is_In_Main_Unit (N)
3191                   or else Is_Inlined (Act_Decl_Id))
3192               and then (Operating_Mode = Generate_Code
3193                           or else (Operating_Mode = Check_Semantics
3194                                     and then Tree_Output))
3195               and then (Expander_Active or else Tree_Output)
3196               and then not ABE_Is_Certain (N)
3197               and then not Is_Eliminated (Act_Decl_Id)
3198             then
3199                Pending_Instantiations.Increment_Last;
3200                Pending_Instantiations.Table (Pending_Instantiations.Last) :=
3201                  (N, Act_Decl, Expander_Active, Current_Sem_Unit);
3202                Check_Forward_Instantiation (N, Gen_Decl);
3203
3204                --  The wrapper package is always delayed, because it does
3205                --  not constitute a freeze point, but to insure that the
3206                --  freeze node is placed properly, it is created directly
3207                --  when instantiating the body (otherwise the freeze node
3208                --  might appear to early for nested instantiations).
3209
3210             elsif Nkind (Parent (N)) = N_Compilation_Unit then
3211
3212                --  For ASIS purposes, indicate that the wrapper package has
3213                --  replaced the instantiation node.
3214
3215                Rewrite (N, Unit (Parent (N)));
3216                Set_Unit (Parent (N), N);
3217             end if;
3218
3219          elsif Nkind (Parent (N)) = N_Compilation_Unit then
3220
3221                --  Replace instance node for library-level instantiations
3222                --  of intrinsic subprograms, for ASIS use.
3223
3224                Rewrite (N, Unit (Parent (N)));
3225                Set_Unit (Parent (N), N);
3226          end if;
3227
3228          if Parent_Installed then
3229             Remove_Parent;
3230          end if;
3231
3232          Restore_Env;
3233          Generic_Renamings.Set_Last (0);
3234          Generic_Renamings_HTable.Reset;
3235       end if;
3236
3237    exception
3238       when Instantiation_Error =>
3239          if Parent_Installed then
3240             Remove_Parent;
3241          end if;
3242    end Analyze_Subprogram_Instantiation;
3243
3244    -------------------------
3245    -- Get_Associated_Node --
3246    -------------------------
3247
3248    function Get_Associated_Node (N : Node_Id) return Node_Id is
3249       Assoc : Node_Id := Associated_Node (N);
3250
3251    begin
3252       if Nkind (Assoc) /= Nkind (N) then
3253          return Assoc;
3254
3255       elsif Nkind (Assoc) = N_Aggregate
3256         or else Nkind (Assoc) = N_Extension_Aggregate
3257       then
3258          return Assoc;
3259       else
3260          --  If the node is part of an inner generic, it may itself have been
3261          --  remapped into a further generic copy. Associated_Node is otherwise
3262          --  used for the entity of the node, and will be of a different node
3263          --  kind, or else N has been rewritten as a literal or function call.
3264
3265          while Present (Associated_Node (Assoc))
3266            and then Nkind (Associated_Node (Assoc)) = Nkind (Assoc)
3267          loop
3268             Assoc := Associated_Node (Assoc);
3269          end loop;
3270
3271          --  Follow and additional link in case the final node was rewritten.
3272          --  This can only happen with nested generic units.
3273
3274          if (Nkind (Assoc) = N_Identifier or else Nkind (Assoc) in N_Op)
3275            and then Present (Associated_Node (Assoc))
3276            and then (Nkind (Associated_Node (Assoc)) = N_Function_Call
3277                        or else
3278                      Nkind (Associated_Node (Assoc)) = N_Explicit_Dereference
3279                        or else
3280                      Nkind (Associated_Node (Assoc)) = N_Integer_Literal
3281                        or else
3282                      Nkind (Associated_Node (Assoc)) = N_Real_Literal
3283                        or else
3284                      Nkind (Associated_Node (Assoc)) = N_String_Literal)
3285          then
3286             Assoc := Associated_Node (Assoc);
3287          end if;
3288
3289          return Assoc;
3290       end if;
3291    end Get_Associated_Node;
3292
3293    -------------------------------------------
3294    -- Build_Instance_Compilation_Unit_Nodes --
3295    -------------------------------------------
3296
3297    procedure Build_Instance_Compilation_Unit_Nodes
3298      (N        : Node_Id;
3299       Act_Body : Node_Id;
3300       Act_Decl : Node_Id)
3301    is
3302       Decl_Cunit : Node_Id;
3303       Body_Cunit : Node_Id;
3304       Citem      : Node_Id;
3305       New_Main   : constant Entity_Id := Defining_Entity (Act_Decl);
3306       Old_Main   : constant Entity_Id := Cunit_Entity (Main_Unit);
3307
3308    begin
3309       --  A new compilation unit node is built for the instance declaration
3310
3311       Decl_Cunit :=
3312         Make_Compilation_Unit (Sloc (N),
3313           Context_Items  => Empty_List,
3314           Unit           => Act_Decl,
3315           Aux_Decls_Node =>
3316             Make_Compilation_Unit_Aux (Sloc (N)));
3317
3318       Set_Parent_Spec   (Act_Decl, Parent_Spec (N));
3319       Set_Body_Required (Decl_Cunit, True);
3320
3321       --  We use the original instantiation compilation unit as the resulting
3322       --  compilation unit of the instance, since this is the main unit.
3323
3324       Rewrite (N, Act_Body);
3325       Body_Cunit := Parent (N);
3326
3327       --  The two compilation unit nodes are linked by the Library_Unit field
3328
3329       Set_Library_Unit  (Decl_Cunit, Body_Cunit);
3330       Set_Library_Unit  (Body_Cunit, Decl_Cunit);
3331
3332       --  If the instance is not the main unit, its context, categorization,
3333       --  and elaboration entity are not relevant to the compilation.
3334
3335       if Parent (N) /= Cunit (Main_Unit) then
3336          return;
3337       end if;
3338
3339       --  The context clause items on the instantiation, which are now
3340       --  attached to the body compilation unit (since the body overwrote
3341       --  the original instantiation node), semantically belong on the spec,
3342       --  so copy them there. It's harmless to leave them on the body as well.
3343       --  In fact one could argue that they belong in both places.
3344
3345       Citem := First (Context_Items (Body_Cunit));
3346       while Present (Citem) loop
3347          Append (New_Copy (Citem), Context_Items (Decl_Cunit));
3348          Next (Citem);
3349       end loop;
3350
3351       --  Propagate categorization flags on packages, so that they appear
3352       --  in ali file for the spec of the unit.
3353
3354       if Ekind (New_Main) = E_Package then
3355          Set_Is_Pure           (Old_Main, Is_Pure (New_Main));
3356          Set_Is_Preelaborated  (Old_Main, Is_Preelaborated (New_Main));
3357          Set_Is_Remote_Types   (Old_Main, Is_Remote_Types (New_Main));
3358          Set_Is_Shared_Passive (Old_Main, Is_Shared_Passive (New_Main));
3359          Set_Is_Remote_Call_Interface
3360            (Old_Main, Is_Remote_Call_Interface (New_Main));
3361       end if;
3362
3363       --  Make entry in Units table, so that binder can generate call to
3364       --  elaboration procedure for body, if any.
3365
3366       Make_Instance_Unit (Body_Cunit);
3367       Main_Unit_Entity := New_Main;
3368       Set_Cunit_Entity (Main_Unit, Main_Unit_Entity);
3369
3370       --  Build elaboration entity, since the instance may certainly
3371       --  generate elaboration code requiring a flag for protection.
3372
3373       Build_Elaboration_Entity (Decl_Cunit, New_Main);
3374    end Build_Instance_Compilation_Unit_Nodes;
3375
3376    -----------------------------------
3377    -- Check_Formal_Package_Instance --
3378    -----------------------------------
3379
3380    --  If the formal has specific parameters, they must match those of the
3381    --  actual. Both of them are instances, and the renaming declarations
3382    --  for their formal parameters appear in the same order in both. The
3383    --  analyzed formal has been analyzed in the context of the current
3384    --  instance.
3385
3386    procedure Check_Formal_Package_Instance
3387      (Formal_Pack : Entity_Id;
3388       Actual_Pack : Entity_Id)
3389    is
3390       E1 : Entity_Id := First_Entity (Actual_Pack);
3391       E2 : Entity_Id := First_Entity (Formal_Pack);
3392
3393       Expr1 : Node_Id;
3394       Expr2 : Node_Id;
3395
3396       procedure Check_Mismatch (B : Boolean);
3397       --  Common error routine for mismatch between the parameters of
3398       --  the actual instance and those of the formal package.
3399
3400       procedure Check_Mismatch (B : Boolean) is
3401       begin
3402          if B then
3403             Error_Msg_NE
3404               ("actual for & in actual instance does not match formal",
3405                Parent (Actual_Pack), E1);
3406          end if;
3407       end Check_Mismatch;
3408
3409    --  Start of processing for Check_Formal_Package_Instance
3410
3411    begin
3412       while Present (E1)
3413         and then Present (E2)
3414       loop
3415          exit when Ekind (E1) = E_Package
3416            and then Renamed_Entity (E1) = Renamed_Entity (Actual_Pack);
3417
3418          if Is_Type (E1) then
3419
3420             --  Subtypes must statically match. E1 and E2 are the
3421             --  local entities that are subtypes of the actuals.
3422             --  Itypes generated for other parameters need not be checked,
3423             --  the check will be performed on the parameters themselves.
3424
3425             if not Is_Itype (E1)
3426               and then not Is_Itype (E2)
3427             then
3428                Check_Mismatch
3429                  (not Is_Type (E2)
3430                    or else Etype (E1) /= Etype (E2)
3431                    or else not Subtypes_Statically_Match (E1, E2));
3432             end if;
3433
3434          elsif Ekind (E1) = E_Constant then
3435
3436             --  IN parameters must denote the same static value, or
3437             --  the same constant, or the literal null.
3438
3439             Expr1 := Expression (Parent (E1));
3440
3441             if Ekind (E2) /= E_Constant then
3442                Check_Mismatch (True);
3443                goto Next_E;
3444             else
3445                Expr2 := Expression (Parent (E2));
3446             end if;
3447
3448             if Is_Static_Expression (Expr1) then
3449
3450                if not Is_Static_Expression (Expr2) then
3451                   Check_Mismatch (True);
3452
3453                elsif Is_Integer_Type (Etype (E1)) then
3454
3455                   declare
3456                      V1 : Uint := Expr_Value (Expr1);
3457                      V2 : Uint := Expr_Value (Expr2);
3458                   begin
3459                      Check_Mismatch (V1 /= V2);
3460                   end;
3461
3462                elsif Is_Real_Type (Etype (E1)) then
3463
3464                   declare
3465                      V1 : Ureal := Expr_Value_R (Expr1);
3466                      V2 : Ureal := Expr_Value_R (Expr2);
3467                   begin
3468                      Check_Mismatch (V1 /= V2);
3469                   end;
3470
3471                elsif Is_String_Type (Etype (E1))
3472                  and then Nkind (Expr1) = N_String_Literal
3473                then
3474
3475                   if Nkind (Expr2) /= N_String_Literal then
3476                      Check_Mismatch (True);
3477                   else
3478                      Check_Mismatch
3479                        (not String_Equal (Strval (Expr1), Strval (Expr2)));
3480                   end if;
3481                end if;
3482
3483             elsif Is_Entity_Name (Expr1) then
3484                if Is_Entity_Name (Expr2) then
3485                   if Entity (Expr1) = Entity (Expr2) then
3486                      null;
3487
3488                   elsif Ekind (Entity (Expr2)) = E_Constant
3489                      and then Is_Entity_Name (Constant_Value (Entity (Expr2)))
3490                      and then
3491                       Entity (Constant_Value (Entity (Expr2))) = Entity (Expr1)
3492                   then
3493                      null;
3494                   else
3495                      Check_Mismatch (True);
3496                   end if;
3497                else
3498                   Check_Mismatch (True);
3499                end if;
3500
3501             elsif Nkind (Expr1) = N_Null then
3502                Check_Mismatch (Nkind (Expr1) /= N_Null);
3503
3504             else
3505                Check_Mismatch (True);
3506             end if;
3507
3508          elsif Ekind (E1) = E_Variable
3509            or else Ekind (E1) = E_Package
3510          then
3511             Check_Mismatch
3512               (Ekind (E1) /= Ekind (E2)
3513                 or else Renamed_Object (E1) /= Renamed_Object (E2));
3514
3515          elsif Is_Overloadable (E1) then
3516
3517             --  Verify that the names of the  entities match.
3518             --  What if actual is an attribute ???
3519
3520             Check_Mismatch
3521               (Ekind (E2) /= Ekind (E1) or else (Alias (E1)) /= Alias (E2));
3522
3523          else
3524             raise Program_Error;
3525          end if;
3526
3527          <<Next_E>>
3528             Next_Entity (E1);
3529             Next_Entity (E2);
3530       end loop;
3531    end Check_Formal_Package_Instance;
3532
3533    ---------------------------
3534    -- Check_Formal_Packages --
3535    ---------------------------
3536
3537    procedure Check_Formal_Packages (P_Id : Entity_Id) is
3538       E        : Entity_Id;
3539       Formal_P : Entity_Id;
3540
3541    begin
3542       --  Iterate through the declarations in the instance, looking for
3543       --  package renaming declarations that denote instances of formal
3544       --  packages. Stop when we find the renaming of the current package
3545       --  itself. The declaration for a formal package without a box is
3546       --  followed by an internal entity that repeats the instantiation.
3547
3548       E := First_Entity (P_Id);
3549       while Present (E) loop
3550          if Ekind (E) = E_Package then
3551             if Renamed_Object (E) = P_Id then
3552                exit;
3553
3554             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
3555                null;
3556
3557             elsif not Box_Present (Parent (Associated_Formal_Package (E))) then
3558                Formal_P := Next_Entity (E);
3559                Check_Formal_Package_Instance (Formal_P, E);
3560             end if;
3561          end if;
3562
3563          Next_Entity (E);
3564       end loop;
3565    end Check_Formal_Packages;
3566
3567    ---------------------------------
3568    -- Check_Forward_Instantiation --
3569    ---------------------------------
3570
3571    procedure Check_Forward_Instantiation (N : Node_Id; Decl : Node_Id) is
3572       S        : Entity_Id;
3573       Gen_Comp : Entity_Id := Cunit_Entity (Get_Source_Unit (Decl));
3574
3575    begin
3576       --  The instantiation appears before the generic body if we are in the
3577       --  scope of the unit containing the generic, either in its spec or in
3578       --  the package body. and before the generic body.
3579
3580       if Ekind (Gen_Comp) = E_Package_Body then
3581          Gen_Comp := Spec_Entity (Gen_Comp);
3582       end if;
3583
3584       if In_Open_Scopes (Gen_Comp)
3585         and then No (Corresponding_Body (Decl))
3586       then
3587          S := Current_Scope;
3588
3589          while Present (S)
3590            and then not Is_Compilation_Unit (S)
3591            and then not Is_Child_Unit (S)
3592          loop
3593             if Ekind (S) = E_Package then
3594                Set_Has_Forward_Instantiation (S);
3595             end if;
3596
3597             S := Scope (S);
3598          end loop;
3599       end if;
3600    end Check_Forward_Instantiation;
3601
3602    ---------------------------
3603    -- Check_Generic_Actuals --
3604    ---------------------------
3605
3606    --  The visibility of the actuals may be different between the
3607    --  point of generic instantiation and the instantiation of the body.
3608
3609    procedure Check_Generic_Actuals
3610      (Instance      : Entity_Id;
3611       Is_Formal_Box : Boolean)
3612    is
3613       E      : Entity_Id;
3614       Astype : Entity_Id;
3615
3616    begin
3617       E := First_Entity (Instance);
3618       while Present (E) loop
3619          if Is_Type (E)
3620            and then Nkind (Parent (E)) = N_Subtype_Declaration
3621            and then Scope (Etype (E)) /= Instance
3622            and then Is_Entity_Name (Subtype_Indication (Parent (E)))
3623          then
3624             Check_Private_View (Subtype_Indication (Parent (E)));
3625             Set_Is_Generic_Actual_Type (E, True);
3626             Set_Is_Hidden (E, False);
3627
3628             --  We constructed the generic actual type as a subtype of
3629             --  the supplied type. This means that it normally would not
3630             --  inherit subtype specific attributes of the actual, which
3631             --  is wrong for the generic case.
3632
3633             Astype := Ancestor_Subtype (E);
3634
3635             if No (Astype) then
3636
3637                --  can happen when E is an itype that is the full view of
3638                --  a private type completed, e.g. with a constrained array.
3639
3640                Astype := Base_Type (E);
3641             end if;
3642
3643             Set_Size_Info      (E,                (Astype));
3644             Set_RM_Size        (E, RM_Size        (Astype));
3645             Set_First_Rep_Item (E, First_Rep_Item (Astype));
3646
3647             if Is_Discrete_Or_Fixed_Point_Type (E) then
3648                Set_RM_Size (E, RM_Size (Astype));
3649
3650             --  In  nested instances, the base type of an access actual
3651             --  may itself be private, and need to be exchanged.
3652
3653             elsif Is_Access_Type (E)
3654               and then Is_Private_Type (Etype (E))
3655             then
3656                Check_Private_View
3657                  (New_Occurrence_Of (Etype (E), Sloc (Instance)));
3658             end if;
3659
3660          elsif Ekind (E) = E_Package then
3661
3662             --  If this is the renaming for the current instance, we're done.
3663             --  Otherwise it is a formal package. If the corresponding formal
3664             --  was declared with a box, the (instantiations of the) generic
3665             --  formal part are also visible. Otherwise, ignore the entity
3666             --  created to validate the actuals.
3667
3668             if Renamed_Object (E) = Instance then
3669                exit;
3670
3671             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
3672                null;
3673
3674             --  The visibility of a formal of an enclosing generic is already
3675             --  correct.
3676
3677             elsif Denotes_Formal_Package (E) then
3678                null;
3679
3680             elsif Present (Associated_Formal_Package (E))
3681               and then Box_Present (Parent (Associated_Formal_Package (E)))
3682             then
3683                Check_Generic_Actuals (Renamed_Object (E), True);
3684                Set_Is_Hidden (E, False);
3685             end if;
3686
3687          else
3688             Set_Is_Hidden (E, not Is_Formal_Box);
3689          end if;
3690
3691          Next_Entity (E);
3692       end loop;
3693
3694    end Check_Generic_Actuals;
3695
3696    ------------------------------
3697    -- Check_Generic_Child_Unit --
3698    ------------------------------
3699
3700    procedure Check_Generic_Child_Unit
3701      (Gen_Id           : Node_Id;
3702       Parent_Installed : in out Boolean)
3703    is
3704       Loc      : constant Source_Ptr := Sloc (Gen_Id);
3705       Gen_Par  : Entity_Id := Empty;
3706       Inst_Par : Entity_Id;
3707       E        : Entity_Id;
3708       S        : Node_Id;
3709
3710       function Find_Generic_Child
3711         (Scop : Entity_Id;
3712          Id   : Node_Id)
3713          return Entity_Id;
3714       --  Search generic parent for possible child unit.
3715
3716       function In_Enclosing_Instance return Boolean;
3717       --  Within an instance of the parent, the child unit may be denoted
3718       --  by a simple name. Examine enclosing scopes to locate a possible
3719       --  parent instantiation.
3720
3721       function Find_Generic_Child
3722         (Scop : Entity_Id;
3723          Id   : Node_Id)
3724          return Entity_Id
3725       is
3726          E : Entity_Id;
3727
3728       begin
3729          --  If entity of name is already set, instance has already been
3730          --  resolved, e.g. in an enclosing instantiation.
3731
3732          if Present (Entity (Id)) then
3733             if Scope (Entity (Id)) = Scop then
3734                return Entity (Id);
3735             else
3736                return Empty;
3737             end if;
3738
3739          else
3740             E := First_Entity (Scop);
3741             while Present (E) loop
3742                if Chars (E) = Chars (Id)
3743                  and then Is_Child_Unit (E)
3744                then
3745                   if Is_Child_Unit (E)
3746                     and then not Is_Visible_Child_Unit (E)
3747                   then
3748                      Error_Msg_NE
3749                        ("generic child unit& is not visible", Gen_Id, E);
3750                   end if;
3751
3752                   Set_Entity (Id, E);
3753                   return E;
3754                end if;
3755
3756                Next_Entity (E);
3757             end loop;
3758
3759             return Empty;
3760          end if;
3761       end Find_Generic_Child;
3762
3763       function In_Enclosing_Instance return Boolean is
3764          Enclosing_Instance : Node_Id;
3765
3766       begin
3767          Enclosing_Instance := Current_Scope;
3768
3769          while Present (Enclosing_Instance) loop
3770             exit when Ekind (Enclosing_Instance) = E_Package
3771               and then Nkind (Parent (Enclosing_Instance)) =
3772                 N_Package_Specification
3773               and then Present
3774                 (Generic_Parent (Parent (Enclosing_Instance)));
3775
3776             Enclosing_Instance := Scope (Enclosing_Instance);
3777          end loop;
3778
3779          if Present (Enclosing_Instance) then
3780             E := Find_Generic_Child
3781              (Generic_Parent (Parent (Enclosing_Instance)), Gen_Id);
3782          else
3783             return False;
3784          end if;
3785
3786          if Present (E) then
3787             Rewrite (Gen_Id,
3788               Make_Expanded_Name (Loc,
3789                 Chars         => Chars (E),
3790                 Prefix        => New_Occurrence_Of (Enclosing_Instance, Loc),
3791                 Selector_Name => New_Occurrence_Of (E, Loc)));
3792
3793             Set_Entity (Gen_Id, E);
3794             Set_Etype  (Gen_Id, Etype (E));
3795             Parent_Installed := False;      -- Already in scope.
3796             return True;
3797          else
3798             Analyze (Gen_Id);
3799             return False;
3800          end if;
3801       end In_Enclosing_Instance;
3802
3803    --  Start of processing for Check_Generic_Child_Unit
3804
3805    begin
3806       --  If the name of the generic is given by a selected component, it
3807       --  may be the name of a generic child unit, and the prefix is the name
3808       --  of an instance of the parent, in which case the child unit must be
3809       --  visible. If this instance is not in scope, it must be placed there
3810       --  and removed after instantiation, because what is being instantiated
3811       --  is not the original child, but the corresponding child present in
3812       --  the instance of the parent.
3813
3814       --  If the child is instantiated within the parent, it can be given by
3815       --  a simple name. In this case the instance is already in scope, but
3816       --  the child generic must be recovered from the generic parent as well.
3817
3818       if Nkind (Gen_Id) = N_Selected_Component then
3819          S := Selector_Name (Gen_Id);
3820          Analyze (Prefix (Gen_Id));
3821          Inst_Par := Entity (Prefix (Gen_Id));
3822
3823          if Ekind (Inst_Par) = E_Package
3824            and then Present (Renamed_Object (Inst_Par))
3825          then
3826             Inst_Par := Renamed_Object (Inst_Par);
3827          end if;
3828
3829          if Ekind (Inst_Par) = E_Package then
3830             if Nkind (Parent (Inst_Par)) = N_Package_Specification then
3831                Gen_Par := Generic_Parent (Parent (Inst_Par));
3832
3833             elsif Nkind (Parent (Inst_Par)) = N_Defining_Program_Unit_Name
3834               and then
3835                 Nkind (Parent (Parent (Inst_Par))) = N_Package_Specification
3836             then
3837                Gen_Par := Generic_Parent (Parent (Parent (Inst_Par)));
3838             end if;
3839
3840          elsif Ekind (Inst_Par) = E_Generic_Package
3841            and then Nkind (Parent (Gen_Id)) = N_Formal_Package_Declaration
3842          then
3843
3844             --  A formal package may be a real child package, and not the
3845             --  implicit instance within a parent. In this case the child is
3846             --  not visible and has to be retrieved explicitly as well.
3847
3848             Gen_Par := Inst_Par;
3849          end if;
3850
3851          if Present (Gen_Par) then
3852
3853             --  The prefix denotes an instantiation. The entity itself
3854             --  may be a nested generic, or a child unit.
3855
3856             E := Find_Generic_Child (Gen_Par, S);
3857
3858             if Present (E) then
3859                Change_Selected_Component_To_Expanded_Name (Gen_Id);
3860                Set_Entity (Gen_Id, E);
3861                Set_Etype (Gen_Id, Etype (E));
3862                Set_Entity (S, E);
3863                Set_Etype (S, Etype (E));
3864
3865                --  Indicate that this is a reference to the parent.
3866
3867                if In_Extended_Main_Source_Unit (Gen_Id) then
3868                   Set_Is_Instantiated (Inst_Par);
3869                end if;
3870
3871                --  A common mistake is to replicate the naming scheme of
3872                --  a hierarchy by instantiating a generic child directly,
3873                --  rather than the implicit child in a parent instance:
3874                --
3875                --  generic .. package Gpar is ..
3876                --  generic .. package Gpar.Child is ..
3877                --  package Par is new Gpar ();
3878
3879                --  with Gpar.Child;
3880                --  package Par.Child is new Gpar.Child ();
3881                --                           rather than Par.Child
3882                --
3883                --  In this case the instantiation is within Par, which is
3884                --  an instance, but Gpar does not denote Par because we are
3885                --  not IN the instance of Gpar, so this is illegal. The test
3886                --  below recognizes this particular case.
3887
3888                if Is_Child_Unit (E)
3889                  and then not Comes_From_Source (Entity (Prefix (Gen_Id)))
3890                  and then (not In_Instance
3891                              or else Nkind (Parent (Parent (Gen_Id))) =
3892                                                          N_Compilation_Unit)
3893                then
3894                   Error_Msg_N
3895                     ("prefix of generic child unit must be instance of parent",
3896                       Gen_Id);
3897                end if;
3898
3899                if not In_Open_Scopes (Inst_Par)
3900                  and then Nkind (Parent (Gen_Id))
3901                    not in N_Generic_Renaming_Declaration
3902                then
3903                   Install_Parent (Inst_Par);
3904                   Parent_Installed := True;
3905                end if;
3906
3907             else
3908                --  If the generic parent does not contain an entity that
3909                --  corresponds to the selector, the instance doesn't either.
3910                --  Analyzing the node will yield the appropriate error message.
3911                --  If the entity is not a child unit, then it is an inner
3912                --  generic in the parent.
3913
3914                Analyze (Gen_Id);
3915             end if;
3916
3917          else
3918             Analyze (Gen_Id);
3919
3920             if Is_Child_Unit (Entity (Gen_Id))
3921               and then Nkind (Parent (Gen_Id))
3922                 not in N_Generic_Renaming_Declaration
3923               and then not In_Open_Scopes (Inst_Par)
3924             then
3925                Install_Parent (Inst_Par);
3926                Parent_Installed := True;
3927             end if;
3928          end if;
3929
3930       elsif Nkind (Gen_Id) = N_Expanded_Name then
3931
3932          --  Entity already present, analyze prefix, whose meaning may be
3933          --  an instance in the current context. If it is an instance of
3934          --  a relative within another, the proper parent may still have
3935          --  to be installed, if they are not of the same generation.
3936
3937          Analyze (Prefix (Gen_Id));
3938          Inst_Par := Entity (Prefix (Gen_Id));
3939
3940          if In_Enclosing_Instance then
3941             null;
3942
3943          elsif Present (Entity (Gen_Id))
3944            and then Is_Child_Unit (Entity (Gen_Id))
3945            and then not In_Open_Scopes (Inst_Par)
3946          then
3947             Install_Parent (Inst_Par);
3948             Parent_Installed := True;
3949          end if;
3950
3951       elsif In_Enclosing_Instance then
3952          --  The child unit is found in some enclosing scope.
3953          null;
3954
3955       else
3956          Analyze (Gen_Id);
3957
3958          --  If this is the renaming of the implicit child in a parent
3959          --  instance, recover the parent name and install it.
3960
3961          if Is_Entity_Name (Gen_Id) then
3962             E := Entity (Gen_Id);
3963
3964             if Is_Generic_Unit (E)
3965               and then Nkind (Parent (E)) in N_Generic_Renaming_Declaration
3966               and then Is_Child_Unit (Renamed_Object (E))
3967               and then Is_Generic_Unit (Scope (Renamed_Object (E)))
3968               and then Nkind (Name (Parent (E))) = N_Expanded_Name
3969             then
3970                Rewrite (Gen_Id,
3971                  New_Copy_Tree (Name (Parent (E))));
3972                Inst_Par := Entity (Prefix (Gen_Id));
3973
3974                if not In_Open_Scopes (Inst_Par) then
3975                   Install_Parent (Inst_Par);
3976                   Parent_Installed := True;
3977                end if;
3978
3979             --  If it is a child unit of a non-generic parent, it may be
3980             --  use-visible and given by a direct name. Install parent as
3981             --  for other cases.
3982
3983             elsif Is_Generic_Unit (E)
3984               and then Is_Child_Unit (E)
3985               and then
3986                 Nkind (Parent (Gen_Id)) not in N_Generic_Renaming_Declaration
3987               and then not Is_Generic_Unit (Scope (E))
3988             then
3989                if not In_Open_Scopes (Scope (E)) then
3990                   Install_Parent (Scope (E));
3991                   Parent_Installed := True;
3992                end if;
3993             end if;
3994          end if;
3995       end if;
3996    end Check_Generic_Child_Unit;
3997
3998    -----------------------------
3999    -- Check_Hidden_Child_Unit --
4000    -----------------------------
4001
4002    procedure Check_Hidden_Child_Unit
4003      (N           : Node_Id;
4004       Gen_Unit    : Entity_Id;
4005       Act_Decl_Id : Entity_Id)
4006    is
4007       Gen_Id : Node_Id := Name (N);
4008
4009    begin
4010       if Is_Child_Unit (Gen_Unit)
4011         and then Is_Child_Unit (Act_Decl_Id)
4012         and then Nkind (Gen_Id) = N_Expanded_Name
4013         and then Entity (Prefix (Gen_Id)) = Scope (Act_Decl_Id)
4014         and then Chars (Gen_Unit) = Chars (Act_Decl_Id)
4015       then
4016          Error_Msg_Node_2 := Scope (Act_Decl_Id);
4017          Error_Msg_NE
4018            ("generic unit & is implicitly declared in &",
4019              Defining_Unit_Name (N), Gen_Unit);
4020          Error_Msg_N ("\instance must have different name",
4021            Defining_Unit_Name (N));
4022       end if;
4023    end Check_Hidden_Child_Unit;
4024
4025    ------------------------
4026    -- Check_Private_View --
4027    ------------------------
4028
4029    procedure Check_Private_View (N : Node_Id) is
4030       T : constant Entity_Id := Etype (N);
4031       BT : Entity_Id;
4032
4033    begin
4034       --  Exchange views if the type was not private in the generic but is
4035       --  private at the point of instantiation. Do not exchange views if
4036       --  the scope of the type is in scope. This can happen if both generic
4037       --  and instance are sibling units, or if type is defined in a parent.
4038       --  In this case the visibility of the type will be correct for all
4039       --  semantic checks.
4040
4041       if Present (T) then
4042          BT := Base_Type (T);
4043
4044          if Is_Private_Type (T)
4045            and then not Has_Private_View (N)
4046            and then Present (Full_View (T))
4047            and then not In_Open_Scopes (Scope (T))
4048          then
4049             --  In the generic, the full type was visible. Save the
4050             --  private entity, for subsequent exchange.
4051
4052             Switch_View (T);
4053
4054          elsif Has_Private_View (N)
4055            and then not Is_Private_Type (T)
4056            and then not Has_Been_Exchanged (T)
4057            and then Etype (Get_Associated_Node (N)) /= T
4058          then
4059             --  Only the private declaration was visible in the generic. If
4060             --  the type appears in a subtype declaration, the subtype in the
4061             --  instance must have a view compatible with that of its parent,
4062             --  which must be exchanged (see corresponding code in Restore_
4063             --  Private_Views). Otherwise, if the type is defined in a parent
4064             --  unit, leave full visibility within instance, which is safe.
4065
4066             if In_Open_Scopes (Scope (Base_Type (T)))
4067               and then not Is_Private_Type (Base_Type (T))
4068               and then Comes_From_Source (Base_Type (T))
4069             then
4070                null;
4071
4072             elsif Nkind (Parent (N)) = N_Subtype_Declaration
4073               or else not In_Private_Part (Scope (Base_Type (T)))
4074             then
4075                Append_Elmt (T, Exchanged_Views);
4076                Exchange_Declarations (Etype (Get_Associated_Node (N)));
4077             end if;
4078
4079          --  For composite types with inconsistent representation
4080          --  exchange component types accordingly.
4081
4082          elsif Is_Access_Type (T)
4083            and then Is_Private_Type (Designated_Type (T))
4084            and then Present (Full_View (Designated_Type (T)))
4085          then
4086             Switch_View (Designated_Type (T));
4087
4088          elsif Is_Array_Type (T)
4089            and then Is_Private_Type (Component_Type (T))
4090            and then not Has_Private_View (N)
4091            and then Present (Full_View (Component_Type (T)))
4092          then
4093             Switch_View (Component_Type (T));
4094
4095          elsif Is_Private_Type (T)
4096            and then Present (Full_View (T))
4097            and then Is_Array_Type (Full_View (T))
4098            and then Is_Private_Type (Component_Type (Full_View (T)))
4099          then
4100             Switch_View (T);
4101
4102          --  Finally, a non-private subtype may have a private base type,
4103          --  which must be exchanged for consistency. This can happen when
4104          --  instantiating a package body, when the scope stack is empty but
4105          --  in fact the subtype and the base type are declared in an enclosing
4106          --  scope.
4107
4108          elsif not Is_Private_Type (T)
4109            and then not Has_Private_View (N)
4110            and then Is_Private_Type (Base_Type (T))
4111            and then Present (Full_View (BT))
4112            and then not Is_Generic_Type (BT)
4113            and then not In_Open_Scopes (BT)
4114          then
4115             Append_Elmt (Full_View (BT), Exchanged_Views);
4116             Exchange_Declarations (BT);
4117          end if;
4118       end if;
4119    end Check_Private_View;
4120
4121    --------------------------
4122    -- Contains_Instance_Of --
4123    --------------------------
4124
4125    function Contains_Instance_Of
4126      (Inner : Entity_Id;
4127       Outer : Entity_Id;
4128       N     : Node_Id)
4129       return  Boolean
4130    is
4131       Elmt : Elmt_Id;
4132       Scop : Entity_Id;
4133
4134    begin
4135       Scop := Outer;
4136
4137       --  Verify that there are no circular instantiations. We check whether
4138       --  the unit contains an instance of the current scope or some enclosing
4139       --  scope (in case one of the instances appears in a subunit). Longer
4140       --  circularities involving subunits might seem too pathological to
4141       --  consider, but they were not too pathological for the authors of
4142       --  DEC bc30vsq, so we loop over all enclosing scopes, and mark all
4143       --  enclosing generic scopes as containing an instance.
4144
4145       loop
4146          --  Within a generic subprogram body, the scope is not generic, to
4147          --  allow for recursive subprograms. Use the declaration to determine
4148          --  whether this is a generic unit.
4149
4150          if Ekind (Scop) = E_Generic_Package
4151            or else (Is_Subprogram (Scop)
4152                       and then Nkind (Unit_Declaration_Node (Scop)) =
4153                                         N_Generic_Subprogram_Declaration)
4154          then
4155             Elmt := First_Elmt (Inner_Instances (Inner));
4156
4157             while Present (Elmt) loop
4158                if Node (Elmt) = Scop then
4159                   Error_Msg_Node_2 := Inner;
4160                   Error_Msg_NE
4161                     ("circular Instantiation: & instantiated within &!",
4162                        N, Scop);
4163                   return True;
4164
4165                elsif Node (Elmt) = Inner then
4166                   return True;
4167
4168                elsif Contains_Instance_Of (Node (Elmt), Scop, N) then
4169                   Error_Msg_Node_2 := Inner;
4170                   Error_Msg_NE
4171                     ("circular Instantiation: & instantiated within &!",
4172                       N, Node (Elmt));
4173                   return True;
4174                end if;
4175
4176                Next_Elmt (Elmt);
4177             end loop;
4178
4179             --  Indicate that Inner is being instantiated within  Scop.
4180
4181             Append_Elmt (Inner, Inner_Instances (Scop));
4182          end if;
4183
4184          if Scop = Standard_Standard then
4185             exit;
4186          else
4187             Scop := Scope (Scop);
4188          end if;
4189       end loop;
4190
4191       return False;
4192    end Contains_Instance_Of;
4193
4194    -----------------------
4195    -- Copy_Generic_Node --
4196    -----------------------
4197
4198    function Copy_Generic_Node
4199      (N             : Node_Id;
4200       Parent_Id     : Node_Id;
4201       Instantiating : Boolean)
4202       return          Node_Id
4203    is
4204       Ent   : Entity_Id;
4205       New_N : Node_Id;
4206
4207       function Copy_Generic_Descendant (D : Union_Id) return Union_Id;
4208       --  Check the given value of one of the Fields referenced by the
4209       --  current node to determine whether to copy it recursively. The
4210       --  field may hold a Node_Id, a List_Id, or an Elist_Id, or a plain
4211       --  value (Sloc, Uint, Char) in which case it need not be copied.
4212
4213       procedure Copy_Descendants;
4214       --  Common utility for various nodes.
4215
4216       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id;
4217       --  Make copy of element list.
4218
4219       function Copy_Generic_List
4220         (L         : List_Id;
4221          Parent_Id : Node_Id)
4222          return      List_Id;
4223       --  Apply Copy_Node recursively to the members of a node list.
4224
4225       -----------------------
4226       --  Copy_Descendants --
4227       -----------------------
4228
4229       procedure Copy_Descendants is
4230
4231          use Atree.Unchecked_Access;
4232          --  This code section is part of the implementation of an untyped
4233          --  tree traversal, so it needs direct access to node fields.
4234
4235       begin
4236          Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
4237          Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
4238          Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
4239          Set_Field4 (New_N, Copy_Generic_Descendant (Field4 (N)));
4240          Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
4241       end Copy_Descendants;
4242
4243       -----------------------------
4244       -- Copy_Generic_Descendant --
4245       -----------------------------
4246
4247       function Copy_Generic_Descendant (D : Union_Id) return Union_Id is
4248       begin
4249          if D = Union_Id (Empty) then
4250             return D;
4251
4252          elsif D in Node_Range then
4253             return Union_Id
4254               (Copy_Generic_Node (Node_Id (D), New_N, Instantiating));
4255
4256          elsif D in List_Range then
4257             return Union_Id (Copy_Generic_List (List_Id (D), New_N));
4258
4259          elsif D in Elist_Range then
4260             return Union_Id (Copy_Generic_Elist (Elist_Id (D)));
4261
4262          --  Nothing else is copyable (e.g. Uint values), return as is
4263
4264          else
4265             return D;
4266          end if;
4267       end Copy_Generic_Descendant;
4268
4269       ------------------------
4270       -- Copy_Generic_Elist --
4271       ------------------------
4272
4273       function Copy_Generic_Elist (E : Elist_Id) return Elist_Id is
4274          M : Elmt_Id;
4275          L : Elist_Id;
4276
4277       begin
4278          if Present (E) then
4279             L := New_Elmt_List;
4280             M := First_Elmt (E);
4281             while Present (M) loop
4282                Append_Elmt
4283                  (Copy_Generic_Node (Node (M), Empty, Instantiating), L);
4284                Next_Elmt (M);
4285             end loop;
4286
4287             return L;
4288
4289          else
4290             return No_Elist;
4291          end if;
4292       end Copy_Generic_Elist;
4293
4294       -----------------------
4295       -- Copy_Generic_List --
4296       -----------------------
4297
4298       function Copy_Generic_List
4299         (L         : List_Id;
4300          Parent_Id : Node_Id)
4301          return      List_Id
4302       is
4303          N     : Node_Id;
4304          New_L : List_Id;
4305
4306       begin
4307          if Present (L) then
4308             New_L := New_List;
4309             Set_Parent (New_L, Parent_Id);
4310
4311             N := First (L);
4312             while Present (N) loop
4313                Append (Copy_Generic_Node (N, Empty, Instantiating), New_L);
4314                Next (N);
4315             end loop;
4316
4317             return New_L;
4318
4319          else
4320             return No_List;
4321          end if;
4322       end Copy_Generic_List;
4323
4324    --  Start of processing for Copy_Generic_Node
4325
4326    begin
4327       if N = Empty then
4328          return N;
4329       end if;
4330
4331       New_N := New_Copy (N);
4332
4333       if Instantiating then
4334          Adjust_Instantiation_Sloc (New_N, S_Adjustment);
4335       end if;
4336
4337       if not Is_List_Member (N) then
4338          Set_Parent (New_N, Parent_Id);
4339       end if;
4340
4341       --  If defining identifier, then all fields have been copied already
4342
4343       if Nkind (New_N) in N_Entity then
4344          null;
4345
4346       --  Special casing for identifiers and other entity names and operators
4347
4348       elsif    (Nkind (New_N) = N_Identifier
4349         or else Nkind (New_N) = N_Character_Literal
4350         or else Nkind (New_N) = N_Expanded_Name
4351         or else Nkind (New_N) = N_Operator_Symbol
4352         or else Nkind (New_N) in N_Op)
4353       then
4354          if not Instantiating then
4355
4356             --  Link both nodes in order to assign subsequently the
4357             --  entity of the copy to the original node, in case this
4358             --  is a global reference.
4359
4360             Set_Associated_Node (N, New_N);
4361
4362             --  If we are within an instantiation, this is a nested generic
4363             --  that has already been analyzed at the point of definition. We
4364             --  must preserve references that were global to the enclosing
4365             --  parent at that point. Other occurrences, whether global or
4366             --  local to the current generic, must be resolved anew, so we
4367             --  reset the entity in the generic copy. A global reference has
4368             --  a smaller depth than the parent, or else the same depth in
4369             --  case both are distinct compilation units.
4370
4371             --  It is also possible for Current_Instantiated_Parent to be
4372             --  defined, and for this not to be a nested generic, namely
4373             --  if the unit is loaded through Rtsfind. In that case, the
4374             --  entity of New_N is only a link to the associated node, and
4375             --  not a defining occurrence.
4376
4377             --  The entities for parent units in the defining_program_unit
4378             --  of a generic child unit are established when the context of
4379             --  the unit is first analyzed, before the generic copy is made.
4380             --  They are preserved in the copy for use in ASIS queries.
4381
4382             Ent := Entity (New_N);
4383
4384             if No (Current_Instantiated_Parent.Gen_Id) then
4385                if No (Ent)
4386                  or else Nkind (Ent) /= N_Defining_Identifier
4387                  or else Nkind (Parent (N)) /= N_Defining_Program_Unit_Name
4388                then
4389                   Set_Associated_Node (New_N, Empty);
4390                end if;
4391
4392             elsif No (Ent)
4393               or else
4394                 not (Nkind (Ent) = N_Defining_Identifier
4395                        or else
4396                      Nkind (Ent) = N_Defining_Character_Literal
4397                        or else
4398                      Nkind (Ent) = N_Defining_Operator_Symbol)
4399               or else No (Scope (Ent))
4400               or else Scope (Ent) = Current_Instantiated_Parent.Gen_Id
4401               or else (Scope_Depth (Scope (Ent)) >
4402                              Scope_Depth (Current_Instantiated_Parent.Gen_Id)
4403                          and then
4404                        Get_Source_Unit (Ent) =
4405                        Get_Source_Unit (Current_Instantiated_Parent.Gen_Id))
4406             then
4407                Set_Associated_Node (New_N, Empty);
4408             end if;
4409
4410          --  Case of instantiating identifier or some other name or operator
4411
4412          else
4413             --  If the associated node is still defined, the entity in
4414             --  it is global, and must be copied to the instance.
4415
4416             if Present (Get_Associated_Node (N)) then
4417                if Nkind (Get_Associated_Node (N)) = Nkind (N) then
4418                   Set_Entity (New_N, Entity (Get_Associated_Node (N)));
4419                   Check_Private_View (N);
4420
4421                elsif Nkind (Get_Associated_Node (N)) = N_Function_Call then
4422                   Set_Entity (New_N, Entity (Name (Get_Associated_Node (N))));
4423
4424                else
4425                   Set_Entity (New_N, Empty);
4426                end if;
4427             end if;
4428          end if;
4429
4430          --  For expanded name, we must copy the Prefix and Selector_Name
4431
4432          if Nkind (N) = N_Expanded_Name then
4433
4434             Set_Prefix
4435               (New_N, Copy_Generic_Node (Prefix (N), New_N, Instantiating));
4436
4437             Set_Selector_Name (New_N,
4438               Copy_Generic_Node (Selector_Name (N), New_N, Instantiating));
4439
4440          --  For operators, we must copy the right operand
4441
4442          elsif Nkind (N) in N_Op then
4443
4444             Set_Right_Opnd (New_N,
4445               Copy_Generic_Node (Right_Opnd (N), New_N, Instantiating));
4446
4447             --  And for binary operators, the left operand as well
4448
4449             if Nkind (N) in N_Binary_Op then
4450                Set_Left_Opnd (New_N,
4451                  Copy_Generic_Node (Left_Opnd (N), New_N, Instantiating));
4452             end if;
4453          end if;
4454
4455       --  Special casing for stubs
4456
4457       elsif Nkind (N) in N_Body_Stub then
4458
4459          --  In any case, we must copy the specification or defining
4460          --  identifier as appropriate.
4461
4462          if Nkind (N) = N_Subprogram_Body_Stub then
4463             Set_Specification (New_N,
4464               Copy_Generic_Node (Specification (N), New_N, Instantiating));
4465
4466          else
4467             Set_Defining_Identifier (New_N,
4468               Copy_Generic_Node
4469                 (Defining_Identifier (N), New_N, Instantiating));
4470          end if;
4471
4472          --  If we are not instantiating, then this is where we load and
4473          --  analyze subunits, i.e. at the point where the stub occurs. A
4474          --  more permissivle system might defer this analysis to the point
4475          --  of instantiation, but this seems to complicated for now.
4476
4477          if not Instantiating then
4478             declare
4479                Subunit_Name : constant Unit_Name_Type := Get_Unit_Name (N);
4480                Subunit      : Node_Id;
4481                Unum         : Unit_Number_Type;
4482                New_Body     : Node_Id;
4483
4484             begin
4485                Unum :=
4486                  Load_Unit
4487                    (Load_Name  => Subunit_Name,
4488                     Required   => False,
4489                     Subunit    => True,
4490                     Error_Node => N);
4491
4492                --  If the proper body is not found, a warning message will
4493                --  be emitted when analyzing the stub, or later at the the
4494                --  point of instantiation. Here we just leave the stub as is.
4495
4496                if Unum = No_Unit then
4497                   Subunits_Missing := True;
4498                   goto Subunit_Not_Found;
4499                end if;
4500
4501                Subunit := Cunit (Unum);
4502
4503                --  We must create a generic copy of the subunit, in order
4504                --  to perform semantic analysis on it, and we must replace
4505                --  the stub in the original generic unit with the subunit,
4506                --  in order to preserve non-local references within.
4507
4508                --  Only the proper body needs to be copied. Library_Unit and
4509                --  context clause are simply inherited by the generic copy.
4510                --  Note that the copy (which may be recursive if there are
4511                --  nested subunits) must be done first, before attaching it
4512                --  to the enclosing generic.
4513
4514                New_Body :=
4515                  Copy_Generic_Node
4516                    (Proper_Body (Unit (Subunit)),
4517                     Empty, Instantiating => False);
4518
4519                --  Now place the original proper body in the original
4520                --  generic unit. This is a body, not a compilation unit.
4521
4522                Rewrite (N, Proper_Body (Unit (Subunit)));
4523                Set_Is_Compilation_Unit (Defining_Entity (N), False);
4524                Set_Was_Originally_Stub (N);
4525
4526                --  Finally replace the body of the subunit with its copy,
4527                --  and make this new subunit into the library unit of the
4528                --  generic copy, which does not have stubs any longer.
4529
4530                Set_Proper_Body (Unit (Subunit), New_Body);
4531                Set_Library_Unit (New_N, Subunit);
4532                Inherit_Context (Unit (Subunit), N);
4533
4534             end;
4535
4536          --  If we are instantiating, this must be an error case, since
4537          --  otherwise we would have replaced the stub node by the proper
4538          --  body that corresponds. So just ignore it in the copy (i.e.
4539          --  we have copied it, and that is good enough).
4540
4541          else
4542             null;
4543          end if;
4544
4545          <<Subunit_Not_Found>> null;
4546
4547       --  If the node is a compilation unit, it is the subunit of a stub,
4548       --  which has been loaded already (see code below). In this case,
4549       --  the library unit field of N points to the parent unit (which
4550       --  is a compilation unit) and need not (and cannot!) be copied.
4551
4552       --  When the proper body of the stub is analyzed, thie library_unit
4553       --  link is used to establish the proper context (see sem_ch10).
4554
4555       --  The other fields of a compilation unit are copied as usual
4556
4557       elsif Nkind (N) = N_Compilation_Unit then
4558
4559          --  This code can only be executed when not instantiating, because
4560          --  in the copy made for an instantiation, the compilation unit
4561          --  node has disappeared at the point that a stub is replaced by
4562          --  its proper body.
4563
4564          pragma Assert (not Instantiating);
4565
4566          Set_Context_Items (New_N,
4567            Copy_Generic_List (Context_Items (N), New_N));
4568
4569          Set_Unit (New_N,
4570            Copy_Generic_Node (Unit (N), New_N, False));
4571
4572          Set_First_Inlined_Subprogram (New_N,
4573            Copy_Generic_Node
4574              (First_Inlined_Subprogram (N), New_N, False));
4575
4576          Set_Aux_Decls_Node (New_N,
4577            Copy_Generic_Node (Aux_Decls_Node (N), New_N, False));
4578
4579       --  For an assignment node, the assignment is known to be semantically
4580       --  legal if we are instantiating the template. This avoids incorrect
4581       --  diagnostics in generated code.
4582
4583       elsif Nkind (N) = N_Assignment_Statement then
4584
4585          --  Copy name and expression fields in usual manner
4586
4587          Set_Name (New_N,
4588            Copy_Generic_Node (Name (N), New_N, Instantiating));
4589
4590          Set_Expression (New_N,
4591            Copy_Generic_Node (Expression (N), New_N, Instantiating));
4592
4593          if Instantiating then
4594             Set_Assignment_OK (Name (New_N), True);
4595          end if;
4596
4597       elsif Nkind (N) = N_Aggregate
4598               or else Nkind (N) = N_Extension_Aggregate
4599       then
4600
4601          if not Instantiating then
4602             Set_Associated_Node (N, New_N);
4603
4604          else
4605             if Present (Get_Associated_Node (N))
4606               and then Nkind (Get_Associated_Node (N)) = Nkind (N)
4607             then
4608                --  In the generic the aggregate has some composite type.
4609                --  If at the point of instantiation the type has a private
4610                --  view, install the full view (and that of its ancestors,
4611                --  if any).
4612
4613                declare
4614                   T   : Entity_Id := (Etype (Get_Associated_Node (New_N)));
4615                   Rt  : Entity_Id;
4616
4617                begin
4618                   if Present (T)
4619                     and then Is_Private_Type (T)
4620                   then
4621                      Switch_View (T);
4622                   end if;
4623
4624                   if Present (T)
4625                     and then Is_Tagged_Type (T)
4626                     and then Is_Derived_Type (T)
4627                   then
4628                      Rt := Root_Type (T);
4629
4630                      loop
4631                         T := Etype (T);
4632
4633                         if Is_Private_Type (T) then
4634                            Switch_View (T);
4635                         end if;
4636
4637                         exit when T = Rt;
4638                      end loop;
4639                   end if;
4640                end;
4641             end if;
4642          end if;
4643
4644          --  Do not copy the associated node, which points to
4645          --  the generic copy of the aggregate.
4646
4647          declare
4648             use Atree.Unchecked_Access;
4649             --  This code section is part of the implementation of an untyped
4650             --  tree traversal, so it needs direct access to node fields.
4651
4652          begin
4653             Set_Field1 (New_N, Copy_Generic_Descendant (Field1 (N)));
4654             Set_Field2 (New_N, Copy_Generic_Descendant (Field2 (N)));
4655             Set_Field3 (New_N, Copy_Generic_Descendant (Field3 (N)));
4656             Set_Field5 (New_N, Copy_Generic_Descendant (Field5 (N)));
4657          end;
4658
4659       --  Allocators do not have an identifier denoting the access type,
4660       --  so we must locate it through the expression to check whether
4661       --  the views are consistent.
4662
4663       elsif Nkind (N) = N_Allocator
4664         and then Nkind (Expression (N)) = N_Qualified_Expression
4665         and then Is_Entity_Name (Subtype_Mark (Expression (N)))
4666         and then Instantiating
4667       then
4668          declare
4669             T : Node_Id := Get_Associated_Node (Subtype_Mark (Expression (N)));
4670             Acc_T       : Entity_Id;
4671
4672          begin
4673             if Present (T) then
4674                --  Retrieve the allocator node in the generic copy.
4675
4676                Acc_T := Etype (Parent (Parent (T)));
4677                if Present (Acc_T)
4678                  and then Is_Private_Type (Acc_T)
4679                then
4680                   Switch_View (Acc_T);
4681                end if;
4682             end if;
4683
4684             Copy_Descendants;
4685          end;
4686
4687       --  For a proper body, we must catch the case of a proper body that
4688       --  replaces a stub. This represents the point at which a separate
4689       --  compilation unit, and hence template file, may be referenced, so
4690       --  we must make a new source instantiation entry for the template
4691       --  of the subunit, and ensure that all nodes in the subunit are
4692       --  adjusted using this new source instantiation entry.
4693
4694       elsif Nkind (N) in N_Proper_Body then
4695
4696          declare
4697             Save_Adjustment : constant Sloc_Adjustment := S_Adjustment;
4698
4699          begin
4700             if Instantiating and then Was_Originally_Stub (N) then
4701                Create_Instantiation_Source
4702                  (Instantiation_Node, Defining_Entity (N), S_Adjustment);
4703             end if;
4704
4705             --  Now copy the fields of the proper body, using the new
4706             --  adjustment factor if one was needed as per test above.
4707
4708             Copy_Descendants;
4709
4710             --  Restore the original adjustment factor in case changed
4711
4712             S_Adjustment := Save_Adjustment;
4713          end;
4714
4715       --  Don't copy Ident or Comment pragmas, since the comment belongs
4716       --  to the generic unit, not to the instantiating unit.
4717
4718       elsif Nkind (N) = N_Pragma
4719         and then Instantiating
4720       then
4721          declare
4722             Prag_Id : constant Pragma_Id := Get_Pragma_Id (Chars (N));
4723
4724          begin
4725             if Prag_Id = Pragma_Ident
4726               or else Prag_Id = Pragma_Comment
4727             then
4728                New_N := Make_Null_Statement (Sloc (N));
4729
4730             else
4731                Copy_Descendants;
4732             end if;
4733          end;
4734
4735       --  For the remaining nodes, copy recursively their descendants.
4736
4737       else
4738          Copy_Descendants;
4739
4740          if Instantiating
4741            and then Nkind (N) = N_Subprogram_Body
4742          then
4743             Set_Generic_Parent (Specification (New_N), N);
4744          end if;
4745       end if;
4746
4747       return New_N;
4748    end Copy_Generic_Node;
4749
4750    ----------------------------
4751    -- Denotes_Formal_Package --
4752    ----------------------------
4753
4754    function Denotes_Formal_Package (Pack : Entity_Id) return Boolean is
4755       Par  : constant Entity_Id := Current_Instantiated_Parent.Act_Id;
4756       Scop : Entity_Id := Scope (Pack);
4757       E    : Entity_Id;
4758
4759    begin
4760       if Ekind (Scop) = E_Generic_Package
4761         or else Nkind (Unit_Declaration_Node (Scop))
4762           = N_Generic_Subprogram_Declaration
4763       then
4764          return True;
4765
4766       elsif Nkind (Parent (Pack)) = N_Formal_Package_Declaration then
4767          return True;
4768
4769       elsif No (Par) then
4770          return False;
4771
4772       else
4773          --  Check whether this package is associated with a formal
4774          --  package of the enclosing instantiation. Iterate over the
4775          --  list of renamings.
4776
4777          E := First_Entity (Par);
4778          while Present (E) loop
4779
4780             if Ekind (E) /= E_Package
4781               or else Nkind (Parent (E)) /= N_Package_Renaming_Declaration
4782             then
4783                null;
4784             elsif Renamed_Object (E) = Par then
4785                return False;
4786
4787             elsif Renamed_Object (E) = Pack then
4788                return True;
4789             end if;
4790
4791             Next_Entity (E);
4792          end loop;
4793
4794          return False;
4795       end if;
4796    end Denotes_Formal_Package;
4797
4798    -----------------
4799    -- End_Generic --
4800    -----------------
4801
4802    procedure End_Generic is
4803    begin
4804       --  ??? More things could be factored out in this
4805       --  routine. Should probably be done at a later stage.
4806
4807       Inside_A_Generic := Generic_Flags.Table (Generic_Flags.Last);
4808       Generic_Flags.Decrement_Last;
4809
4810       Expander_Mode_Restore;
4811    end End_Generic;
4812
4813    ----------------------
4814    -- Find_Actual_Type --
4815    ----------------------
4816
4817    function Find_Actual_Type
4818      (Typ       : Entity_Id;
4819       Gen_Scope : Entity_Id)
4820       return      Entity_Id
4821    is
4822       T : Entity_Id;
4823
4824    begin
4825       if not Is_Child_Unit (Gen_Scope) then
4826          return Get_Instance_Of (Typ);
4827
4828       elsif not Is_Generic_Type (Typ)
4829         or else Scope (Typ) = Gen_Scope
4830       then
4831          return Get_Instance_Of (Typ);
4832
4833       else
4834          T := Current_Entity (Typ);
4835          while Present (T) loop
4836             if In_Open_Scopes (Scope (T)) then
4837                return T;
4838             end if;
4839
4840             T := Homonym (T);
4841          end loop;
4842
4843          return Typ;
4844       end if;
4845    end Find_Actual_Type;
4846
4847    ----------------------------
4848    -- Freeze_Subprogram_Body --
4849    ----------------------------
4850
4851    procedure Freeze_Subprogram_Body
4852      (Inst_Node : Node_Id;
4853       Gen_Body  : Node_Id;
4854       Pack_Id   : Entity_Id)
4855   is
4856       F_Node   : Node_Id;
4857       Gen_Unit : constant Entity_Id := Entity (Name (Inst_Node));
4858       Par      : constant Entity_Id := Scope (Gen_Unit);
4859       Enc_G    : Entity_Id;
4860       Enc_I    : Node_Id;
4861       E_G_Id   : Entity_Id;
4862
4863       function Earlier (N1, N2 : Node_Id) return Boolean;
4864       --  Yields True if N1 and N2 appear in the same compilation unit,
4865       --  ignoring subunits, and if N1 is to the left of N2 in a left-to-right
4866       --  traversal of the tree for the unit.
4867
4868       function Enclosing_Body (N : Node_Id) return Node_Id;
4869       --  Find innermost package body that encloses the given node, and which
4870       --  is not a compilation unit. Freeze nodes for the instance, or for its
4871       --  enclosing body, may be inserted after the enclosing_body of the
4872       --  generic unit.
4873
4874       function Package_Freeze_Node (B : Node_Id) return Node_Id;
4875       --  Find entity for given package body, and locate or create a freeze
4876       --  node for it.
4877
4878       function True_Parent (N : Node_Id) return Node_Id;
4879       --  For a subunit, return parent of corresponding stub.
4880
4881       -------------
4882       -- Earlier --
4883       -------------
4884
4885       function Earlier (N1, N2 : Node_Id) return Boolean is
4886          D1 : Integer := 0;
4887          D2 : Integer := 0;
4888          P1 : Node_Id := N1;
4889          P2 : Node_Id := N2;
4890
4891          procedure Find_Depth (P : in out Node_Id; D : in out Integer);
4892          --  Find distance from given node to enclosing compilation unit.
4893
4894          procedure Find_Depth (P : in out Node_Id; D : in out Integer) is
4895          begin
4896             while Present (P)
4897               and then Nkind (P) /= N_Compilation_Unit
4898             loop
4899                P := True_Parent (P);
4900                D := D + 1;
4901             end loop;
4902          end Find_Depth;
4903
4904       begin
4905          Find_Depth (P1, D1);
4906          Find_Depth (P2, D2);
4907
4908          if P1 /= P2 then
4909             return False;
4910          else
4911             P1 := N1;
4912             P2 := N2;
4913          end if;
4914
4915          while D1 > D2 loop
4916             P1 := True_Parent (P1);
4917             D1 := D1 - 1;
4918          end loop;
4919
4920          while D2 > D1 loop
4921             P2 := True_Parent (P2);
4922             D2 := D2 - 1;
4923          end loop;
4924
4925          --  At this point P1 and P2 are at the same distance from the root.
4926          --  We examine their parents until we find a common declarative
4927          --  list, at which point we can establish their relative placement
4928          --  by comparing their ultimate slocs. If we reach the root,
4929          --  N1 and N2 do not descend from the same declarative list (e.g.
4930          --  one is nested in the declarative part and the other is in a block
4931          --  in the statement part) and the earlier one is already frozen.
4932
4933          while not Is_List_Member (P1)
4934            or else not Is_List_Member (P2)
4935            or else List_Containing (P1) /= List_Containing (P2)
4936          loop
4937             P1 := True_Parent (P1);
4938             P2 := True_Parent (P2);
4939
4940             if Nkind (Parent (P1)) = N_Subunit then
4941                P1 := Corresponding_Stub (Parent (P1));
4942             end if;
4943
4944             if Nkind (Parent (P2)) = N_Subunit then
4945                P2 := Corresponding_Stub (Parent (P2));
4946             end if;
4947
4948             if P1 = P2 then
4949                return False;
4950             end if;
4951          end loop;
4952
4953          return
4954            Top_Level_Location (Sloc (P1)) < Top_Level_Location (Sloc (P2));
4955       end Earlier;
4956
4957       --------------------
4958       -- Enclosing_Body --
4959       --------------------
4960
4961       function Enclosing_Body (N : Node_Id) return Node_Id is
4962          P : Node_Id := Parent (N);
4963
4964       begin
4965          while Present (P)
4966            and then Nkind (Parent (P)) /= N_Compilation_Unit
4967          loop
4968             if Nkind (P) = N_Package_Body then
4969
4970                if Nkind (Parent (P)) = N_Subunit then
4971                   return Corresponding_Stub (Parent (P));
4972                else
4973                   return P;
4974                end if;
4975             end if;
4976
4977             P := True_Parent (P);
4978          end loop;
4979
4980          return Empty;
4981       end Enclosing_Body;
4982
4983       -------------------------
4984       -- Package_Freeze_Node --
4985       -------------------------
4986
4987       function Package_Freeze_Node (B : Node_Id) return Node_Id is
4988          Id : Entity_Id;
4989
4990       begin
4991          if Nkind (B) = N_Package_Body then
4992             Id := Corresponding_Spec (B);
4993
4994          else pragma Assert (Nkind (B) = N_Package_Body_Stub);
4995             Id := Corresponding_Spec (Proper_Body (Unit (Library_Unit (B))));
4996          end if;
4997
4998          Ensure_Freeze_Node (Id);
4999          return Freeze_Node (Id);
5000       end Package_Freeze_Node;
5001
5002       -----------------
5003       -- True_Parent --
5004       -----------------
5005
5006       function True_Parent (N : Node_Id) return Node_Id is
5007       begin
5008          if Nkind (Parent (N)) = N_Subunit then
5009             return Parent (Corresponding_Stub (Parent (N)));
5010          else
5011             return Parent (N);
5012          end if;
5013       end True_Parent;
5014
5015    --  Start of processing of Freeze_Subprogram_Body
5016
5017    begin
5018       --  If the instance and the generic body appear within the same
5019       --  unit, and the instance precedes the generic, the freeze node for
5020       --  the instance must appear after that of the generic. If the generic
5021       --  is nested within another instance I2, then current instance must
5022       --  be frozen after I2. In both cases, the freeze nodes are those of
5023       --  enclosing packages. Otherwise, the freeze node is placed at the end
5024       --  of the current declarative part.
5025
5026       Enc_G  := Enclosing_Body (Gen_Body);
5027       Enc_I  := Enclosing_Body (Inst_Node);
5028       Ensure_Freeze_Node (Pack_Id);
5029       F_Node := Freeze_Node (Pack_Id);
5030
5031       if Is_Generic_Instance (Par)
5032         and then Present (Freeze_Node (Par))
5033         and then
5034           In_Same_Declarative_Part (Freeze_Node (Par), Inst_Node)
5035       then
5036          if ABE_Is_Certain (Get_Package_Instantiation_Node (Par)) then
5037             --  The parent was a premature instantiation. Insert freeze
5038             --  node at the end the current declarative part.
5039
5040             Insert_After_Last_Decl (Inst_Node, F_Node);
5041
5042          else
5043             Insert_After (Freeze_Node (Par), F_Node);
5044          end if;
5045
5046       --  The body enclosing the instance should be frozen after the body
5047       --  that includes the generic, because the body of the instance may
5048       --  make references to entities therein. If the two are not in the
5049       --  same declarative part, or if the one enclosing the instance is
5050       --  frozen already, freeze the instance at the end of the current
5051       --  declarative part.
5052
5053       elsif Is_Generic_Instance (Par)
5054         and then Present (Freeze_Node (Par))
5055         and then Present (Enc_I)
5056       then
5057          if In_Same_Declarative_Part (Freeze_Node (Par), Enc_I)
5058            or else
5059              (Nkind (Enc_I) = N_Package_Body
5060                and then
5061              In_Same_Declarative_Part (Freeze_Node (Par), Parent (Enc_I)))
5062          then
5063
5064             --  The enclosing package may contain several instances. Rather
5065             --  than computing the earliest point at which to insert its
5066             --  freeze node, we place it at the end of the declarative part
5067             --  of the parent of the generic.
5068
5069             Insert_After_Last_Decl
5070               (Freeze_Node (Par), Package_Freeze_Node (Enc_I));
5071          end if;
5072
5073          Insert_After_Last_Decl (Inst_Node, F_Node);
5074
5075       elsif Present (Enc_G)
5076         and then Present (Enc_I)
5077         and then Enc_G /= Enc_I
5078         and then Earlier (Inst_Node, Gen_Body)
5079       then
5080          if Nkind (Enc_G) = N_Package_Body then
5081             E_G_Id := Corresponding_Spec (Enc_G);
5082          else pragma Assert (Nkind (Enc_G) = N_Package_Body_Stub);
5083             E_G_Id :=
5084               Corresponding_Spec (Proper_Body (Unit (Library_Unit (Enc_G))));
5085          end if;
5086
5087          --  Freeze package that encloses instance, and place node after
5088          --  package that encloses generic. If enclosing package is already
5089          --  frozen we have to assume it is at the proper place. This may
5090          --  be a potential ABE that requires dynamic checking.
5091
5092          Insert_After_Last_Decl (Enc_G, Package_Freeze_Node (Enc_I));
5093
5094          --  Freeze enclosing subunit before instance
5095
5096          Ensure_Freeze_Node (E_G_Id);
5097
5098          if not Is_List_Member (Freeze_Node (E_G_Id)) then
5099             Insert_After (Enc_G, Freeze_Node (E_G_Id));
5100          end if;
5101
5102          Insert_After_Last_Decl (Inst_Node, F_Node);
5103
5104       else
5105
5106          --  If none of the above, insert freeze node at the end of the
5107          --  current declarative part.
5108
5109          Insert_After_Last_Decl (Inst_Node, F_Node);
5110       end if;
5111    end Freeze_Subprogram_Body;
5112
5113    ----------------
5114    -- Get_Gen_Id --
5115    ----------------
5116
5117    function Get_Gen_Id (E : Assoc_Ptr) return Entity_Id is
5118    begin
5119       return Generic_Renamings.Table (E).Gen_Id;
5120    end Get_Gen_Id;
5121
5122    ---------------------
5123    -- Get_Instance_Of --
5124    ---------------------
5125
5126    function Get_Instance_Of (A : Entity_Id) return Entity_Id is
5127       Res : Assoc_Ptr := Generic_Renamings_HTable.Get (A);
5128    begin
5129       if Res /= Assoc_Null then
5130          return Generic_Renamings.Table (Res).Act_Id;
5131       else
5132          --  On exit, entity is not instantiated: not a generic parameter,
5133          --  or else parameter of an inner generic unit.
5134
5135          return A;
5136       end if;
5137    end Get_Instance_Of;
5138
5139    ------------------------------------
5140    -- Get_Package_Instantiation_Node --
5141    ------------------------------------
5142
5143    function Get_Package_Instantiation_Node (A : Entity_Id) return Node_Id is
5144       Decl : Node_Id := Unit_Declaration_Node (A);
5145       Inst : Node_Id;
5146
5147    begin
5148       --  If the instantiation is a compilation unit that does not need a
5149       --  body then the instantiation node has been rewritten as a package
5150       --  declaration for the instance, and we return the original node.
5151       --  If it is a compilation unit and the instance node has not been
5152       --  rewritten, then it is still the unit of the compilation.
5153       --  Otherwise the instantiation node appears after the declaration.
5154       --  If the entity is a formal package, the declaration may have been
5155       --  rewritten as a generic declaration (in the case of a formal with a
5156       --  box) or left as a formal package declaration if it has actuals, and
5157       --  is found with a forward search.
5158
5159       if Nkind (Parent (Decl)) = N_Compilation_Unit then
5160          if Nkind (Original_Node (Decl)) = N_Package_Instantiation then
5161             return Original_Node (Decl);
5162          else
5163             return Unit (Parent (Decl));
5164          end if;
5165
5166       elsif Nkind (Decl) = N_Generic_Package_Declaration
5167         and then Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration
5168       then
5169          return Original_Node (Decl);
5170
5171       else
5172          Inst := Next (Decl);
5173          while Nkind (Inst) /= N_Package_Instantiation
5174            and then Nkind (Inst) /= N_Formal_Package_Declaration
5175          loop
5176             Next (Inst);
5177          end loop;
5178
5179          return Inst;
5180       end if;
5181    end Get_Package_Instantiation_Node;
5182
5183    ------------------------
5184    -- Has_Been_Exchanged --
5185    ------------------------
5186
5187    function Has_Been_Exchanged (E : Entity_Id) return Boolean is
5188       Next : Elmt_Id := First_Elmt (Exchanged_Views);
5189
5190    begin
5191       while Present (Next) loop
5192          if Full_View (Node (Next)) = E then
5193             return True;
5194          end if;
5195
5196          Next_Elmt (Next);
5197       end loop;
5198
5199       return False;
5200    end Has_Been_Exchanged;
5201
5202    ----------
5203    -- Hash --
5204    ----------
5205
5206    function Hash (F : Entity_Id) return HTable_Range is
5207    begin
5208       return HTable_Range (F mod HTable_Size);
5209    end Hash;
5210
5211    ------------------------
5212    -- Hide_Current_Scope --
5213    ------------------------
5214
5215    procedure Hide_Current_Scope is
5216       C : constant Entity_Id := Current_Scope;
5217       E : Entity_Id;
5218
5219    begin
5220       Set_Is_Hidden_Open_Scope (C);
5221       E := First_Entity (C);
5222
5223       while Present (E) loop
5224          if Is_Immediately_Visible (E) then
5225             Set_Is_Immediately_Visible (E, False);
5226             Append_Elmt (E, Hidden_Entities);
5227          end if;
5228
5229          Next_Entity (E);
5230       end loop;
5231
5232       --  Make the scope name invisible as well. This is necessary, but
5233       --  might conflict with calls to Rtsfind later on, in case the scope
5234       --  is a predefined one. There is no clean solution to this problem, so
5235       --  for now we depend on the user not redefining Standard itself in one
5236       --  of the parent units.
5237
5238       if Is_Immediately_Visible (C)
5239         and then C /= Standard_Standard
5240       then
5241          Set_Is_Immediately_Visible (C, False);
5242          Append_Elmt (C, Hidden_Entities);
5243       end if;
5244
5245    end Hide_Current_Scope;
5246
5247    ------------------------------
5248    -- In_Same_Declarative_Part --
5249    ------------------------------
5250
5251    function In_Same_Declarative_Part
5252      (F_Node : Node_Id;
5253       Inst   : Node_Id)
5254       return   Boolean
5255    is
5256       Decls : Node_Id := Parent (F_Node);
5257       Nod   : Node_Id := Parent (Inst);
5258
5259    begin
5260       while Present (Nod) loop
5261          if Nod = Decls then
5262             return True;
5263
5264          elsif Nkind (Nod) = N_Subprogram_Body
5265            or else Nkind (Nod) = N_Package_Body
5266            or else Nkind (Nod) = N_Task_Body
5267            or else Nkind (Nod) = N_Protected_Body
5268            or else Nkind (Nod) = N_Block_Statement
5269          then
5270             return False;
5271
5272          elsif Nkind (Nod) = N_Subunit then
5273             Nod :=  Corresponding_Stub (Nod);
5274
5275          elsif Nkind (Nod) = N_Compilation_Unit then
5276             return False;
5277          else
5278             Nod := Parent (Nod);
5279          end if;
5280       end loop;
5281
5282       return False;
5283    end In_Same_Declarative_Part;
5284
5285    ---------------------
5286    -- Inherit_Context --
5287    ---------------------
5288
5289    procedure Inherit_Context (Gen_Decl : Node_Id; Inst : Node_Id) is
5290       Current_Context : List_Id;
5291       Current_Unit    : Node_Id;
5292       Item            : Node_Id;
5293       New_I           : Node_Id;
5294
5295    begin
5296       if Nkind (Parent (Gen_Decl)) = N_Compilation_Unit then
5297
5298          --  The inherited context is attached to the enclosing compilation
5299          --  unit. This is either the main unit, or the declaration for the
5300          --  main unit (in case the instantiation appears within the package
5301          --  declaration and the main unit is its body).
5302
5303          Current_Unit := Parent (Inst);
5304          while Present (Current_Unit)
5305            and then Nkind (Current_Unit) /= N_Compilation_Unit
5306          loop
5307             Current_Unit := Parent (Current_Unit);
5308          end loop;
5309
5310          Current_Context := Context_Items (Current_Unit);
5311
5312          Item := First (Context_Items (Parent (Gen_Decl)));
5313          while Present (Item) loop
5314             if Nkind (Item) = N_With_Clause then
5315                New_I := New_Copy (Item);
5316                Set_Implicit_With (New_I, True);
5317                Append (New_I, Current_Context);
5318             end if;
5319
5320             Next (Item);
5321          end loop;
5322       end if;
5323    end Inherit_Context;
5324
5325    ----------------------------
5326    -- Insert_After_Last_Decl --
5327    ----------------------------
5328
5329    procedure Insert_After_Last_Decl (N : Node_Id; F_Node : Node_Id) is
5330       L : List_Id := List_Containing (N);
5331       P : Node_Id := Parent (L);
5332
5333    begin
5334       if not Is_List_Member (F_Node) then
5335          if Nkind (P) = N_Package_Specification
5336            and then L = Visible_Declarations (P)
5337            and then Present (Private_Declarations (P))
5338            and then not Is_Empty_List (Private_Declarations (P))
5339          then
5340             L := Private_Declarations (P);
5341          end if;
5342
5343          Insert_After (Last (L), F_Node);
5344       end if;
5345    end Insert_After_Last_Decl;
5346
5347    ------------------
5348    -- Install_Body --
5349    ------------------
5350
5351    procedure Install_Body
5352      (Act_Body : Node_Id;
5353       N        : Node_Id;
5354       Gen_Body : Node_Id;
5355       Gen_Decl : Node_Id)
5356    is
5357       Act_Id    : Entity_Id := Corresponding_Spec (Act_Body);
5358       Act_Unit  : constant Node_Id :=
5359                     Unit (Cunit (Get_Source_Unit (N)));
5360       F_Node    : Node_Id;
5361       Gen_Id    : Entity_Id := Corresponding_Spec (Gen_Body);
5362       Gen_Unit  : constant Node_Id :=
5363                     Unit (Cunit (Get_Source_Unit (Gen_Decl)));
5364       Orig_Body : Node_Id := Gen_Body;
5365       Par       : constant Entity_Id := Scope (Gen_Id);
5366       Body_Unit : Node_Id;
5367
5368       Must_Delay : Boolean;
5369
5370       function Enclosing_Subp (Id : Entity_Id) return Entity_Id;
5371       --  Find subprogram (if any) that encloses instance and/or generic body.
5372
5373       function True_Sloc (N : Node_Id) return Source_Ptr;
5374       --  If the instance is nested inside a generic unit, the Sloc of the
5375       --  instance indicates the place of the original definition, not the
5376       --  point of the current enclosing instance. Pending a better usage of
5377       --  Slocs to indicate instantiation places, we determine the place of
5378       --  origin of a node by finding the maximum sloc of any ancestor node.
5379       --  Why is this not equivalent fo Top_Level_Location ???
5380
5381       function Enclosing_Subp (Id : Entity_Id) return Entity_Id is
5382          Scop : Entity_Id := Scope (Id);
5383
5384       begin
5385          while Scop /= Standard_Standard
5386            and then not Is_Overloadable (Scop)
5387          loop
5388             Scop := Scope (Scop);
5389          end loop;
5390
5391          return Scop;
5392       end Enclosing_Subp;
5393
5394       function True_Sloc (N : Node_Id) return Source_Ptr is
5395          Res : Source_Ptr;
5396          N1  : Node_Id;
5397
5398       begin
5399          Res := Sloc (N);
5400          N1 := N;
5401          while Present (N1) and then N1 /= Act_Unit loop
5402             if Sloc (N1) > Res then
5403                Res := Sloc (N1);
5404             end if;
5405
5406             N1 := Parent (N1);
5407          end loop;
5408
5409          return Res;
5410       end True_Sloc;
5411
5412    --  Start of processing for Install_Body
5413
5414    begin
5415       --  If the body is a subunit, the freeze point is the corresponding
5416       --  stub in the current compilation, not the subunit itself.
5417
5418       if Nkind (Parent (Gen_Body)) = N_Subunit then
5419          Orig_Body :=  Corresponding_Stub (Parent (Gen_Body));
5420       else
5421          Orig_Body := Gen_Body;
5422       end if;
5423
5424       Body_Unit := Unit (Cunit (Get_Source_Unit (Orig_Body)));
5425
5426       --  If the instantiation and the generic definition appear in the
5427       --  same package declaration, this is an early instantiation.
5428       --  If they appear in the same declarative part, it is an early
5429       --  instantiation only if the generic body appears textually later,
5430       --  and the generic body is also in the main unit.
5431
5432       --  If instance is nested within a subprogram, and the generic body is
5433       --  not, the instance is delayed because the enclosing body is. If
5434       --  instance and body are within the same scope, or the same sub-
5435       --  program body, indicate explicitly that the instance is delayed.
5436
5437       Must_Delay :=
5438         (Gen_Unit = Act_Unit
5439           and then ((Nkind (Gen_Unit) = N_Package_Declaration)
5440                       or else Nkind (Gen_Unit) = N_Generic_Package_Declaration
5441                       or else (Gen_Unit = Body_Unit
5442                                 and then True_Sloc (N) < Sloc (Orig_Body)))
5443           and then Is_In_Main_Unit (Gen_Unit)
5444           and then (Scope (Act_Id) = Scope (Gen_Id)
5445                       or else
5446                     Enclosing_Subp (Act_Id) = Enclosing_Subp (Gen_Id)));
5447
5448       --  If this is an early instantiation, the freeze node is placed after
5449       --  the generic body. Otherwise, if the generic appears in an instance,
5450       --  we cannot freeze the current instance until the outer one is frozen.
5451       --  This is only relevant if the current instance is nested within some
5452       --  inner scope not itself within the outer instance. If this scope is
5453       --  a package body in the same declarative part as the outer instance,
5454       --  then that body needs to be frozen after the outer instance. Finally,
5455       --  if no delay is needed, we place the freeze node at the end of the
5456       --  current declarative part.
5457
5458       if Expander_Active then
5459          Ensure_Freeze_Node (Act_Id);
5460          F_Node := Freeze_Node (Act_Id);
5461
5462          if Must_Delay then
5463             Insert_After (Orig_Body, F_Node);
5464
5465          elsif Is_Generic_Instance (Par)
5466            and then Present (Freeze_Node (Par))
5467            and then Scope (Act_Id) /= Par
5468          then
5469             --  Freeze instance of inner generic after instance of enclosing
5470             --  generic.
5471
5472             if In_Same_Declarative_Part (Freeze_Node (Par), N) then
5473                Insert_After (Freeze_Node (Par), F_Node);
5474
5475             --  Freeze package enclosing instance of inner generic after
5476             --  instance of enclosing generic.
5477
5478             elsif Nkind (Parent (N)) = N_Package_Body
5479               and then In_Same_Declarative_Part (Freeze_Node (Par), Parent (N))
5480             then
5481
5482                declare
5483                   Enclosing : Entity_Id := Corresponding_Spec (Parent (N));
5484
5485                begin
5486                   Insert_After_Last_Decl (N, F_Node);
5487                   Ensure_Freeze_Node (Enclosing);
5488
5489                   if not Is_List_Member (Freeze_Node (Enclosing)) then
5490                      Insert_After (Freeze_Node (Par), Freeze_Node (Enclosing));
5491                   end if;
5492                end;
5493
5494             else
5495                Insert_After_Last_Decl (N, F_Node);
5496             end if;
5497
5498          else
5499             Insert_After_Last_Decl (N, F_Node);
5500          end if;
5501       end if;
5502
5503       Set_Is_Frozen (Act_Id);
5504       Insert_Before (N, Act_Body);
5505       Mark_Rewrite_Insertion (Act_Body);
5506    end Install_Body;
5507
5508    --------------------
5509    -- Install_Parent --
5510    --------------------
5511
5512    procedure Install_Parent (P : Entity_Id; In_Body : Boolean := False) is
5513       S : Entity_Id := Current_Scope;
5514       Inst_Par  : Entity_Id;
5515       First_Par : Entity_Id;
5516       Inst_Node : Node_Id;
5517       Gen_Par   : Entity_Id;
5518       First_Gen : Entity_Id;
5519       Ancestors : Elist_Id := New_Elmt_List;
5520       Elmt      : Elmt_Id;
5521
5522       procedure Install_Formal_Packages (Par : Entity_Id);
5523       --  If any of the formals of the parent are formal packages with box,
5524       --  their formal parts are visible in the parent and thus in the child
5525       --  unit as well. Analogous to what is done in Check_Generic_Actuals
5526       --  for the unit itself.
5527
5528       procedure Install_Noninstance_Specs (Par : Entity_Id);
5529       --  Install the scopes of noninstance parent units ending with Par.
5530
5531       procedure Install_Spec (Par : Entity_Id);
5532       --  The child unit is within the declarative part of the parent, so
5533       --  the declarations within the parent are immediately visible.
5534
5535       -----------------------------
5536       -- Install_Formal_Packages --
5537       -----------------------------
5538
5539       procedure Install_Formal_Packages (Par : Entity_Id) is
5540          E : Entity_Id;
5541
5542       begin
5543          E := First_Entity (Par);
5544
5545          while Present (E) loop
5546
5547             if Ekind (E) = E_Package
5548               and then Nkind (Parent (E)) = N_Package_Renaming_Declaration
5549             then
5550                --  If this is the renaming for the parent instance, done.
5551
5552                if Renamed_Object (E) = Par then
5553                   exit;
5554
5555                --  The visibility of a formal of an enclosing generic is
5556                --  already correct.
5557
5558                elsif Denotes_Formal_Package (E) then
5559                   null;
5560
5561                elsif Present (Associated_Formal_Package (E))
5562                  and then Box_Present (Parent (Associated_Formal_Package (E)))
5563                then
5564                   Check_Generic_Actuals (Renamed_Object (E), True);
5565                   Set_Is_Hidden (E, False);
5566                end if;
5567             end if;
5568
5569             Next_Entity (E);
5570          end loop;
5571       end Install_Formal_Packages;
5572
5573       -------------------------------
5574       -- Install_Noninstance_Specs --
5575       -------------------------------
5576
5577       procedure Install_Noninstance_Specs (Par : Entity_Id) is
5578       begin
5579          if Present (Par)
5580            and then Par /= Standard_Standard
5581            and then not In_Open_Scopes (Par)
5582          then
5583             Install_Noninstance_Specs (Scope (Par));
5584             Install_Spec (Par);
5585          end if;
5586       end Install_Noninstance_Specs;
5587
5588       ------------------
5589       -- Install_Spec --
5590       ------------------
5591
5592       procedure Install_Spec (Par : Entity_Id) is
5593          Spec : constant Node_Id :=
5594                   Specification (Unit_Declaration_Node (Par));
5595
5596       begin
5597          New_Scope (Par);
5598          Set_Is_Immediately_Visible   (Par);
5599          Install_Visible_Declarations (Par);
5600          Install_Private_Declarations (Par);
5601          Set_Use (Visible_Declarations (Spec));
5602          Set_Use (Private_Declarations (Spec));
5603       end Install_Spec;
5604
5605    --  Start of processing for Install_Parent
5606
5607    begin
5608       --  We need to install the parent instance to compile the instantiation
5609       --  of the child, but the child instance must appear in the current
5610       --  scope. Given that we cannot place the parent above the current
5611       --  scope in the scope stack, we duplicate the current scope and unstack
5612       --  both after the instantiation is complete.
5613
5614       --  If the parent is itself the instantiation of a child unit, we must
5615       --  also stack the instantiation of its parent, and so on. Each such
5616       --  ancestor is the prefix of the name in a prior instantiation.
5617
5618       --  If this is a nested instance, the parent unit itself resolves to
5619       --  a renaming of the parent instance, whose declaration we need.
5620
5621       --  Finally, the parent may be a generic (not an instance) when the
5622       --  child unit appears as a formal package.
5623
5624       Inst_Par := P;
5625
5626       if Present (Renamed_Entity (Inst_Par)) then
5627          Inst_Par := Renamed_Entity (Inst_Par);
5628       end if;
5629
5630       First_Par := Inst_Par;
5631
5632       Gen_Par :=
5633         Generic_Parent (Specification (Unit_Declaration_Node (Inst_Par)));
5634
5635       First_Gen := Gen_Par;
5636
5637       while Present (Gen_Par)
5638         and then Is_Child_Unit (Gen_Par)
5639       loop
5640          --  Load grandparent instance as well.
5641
5642          Inst_Node := Get_Package_Instantiation_Node (Inst_Par);
5643
5644          if Nkind (Name (Inst_Node)) = N_Expanded_Name then
5645             Inst_Par := Entity (Prefix (Name (Inst_Node)));
5646
5647             if Present (Renamed_Entity (Inst_Par)) then
5648                Inst_Par := Renamed_Entity (Inst_Par);
5649             end if;
5650
5651             Gen_Par :=
5652               Generic_Parent
5653                 (Specification (Unit_Declaration_Node (Inst_Par)));
5654
5655             if Present (Gen_Par) then
5656                Prepend_Elmt (Inst_Par, Ancestors);
5657
5658             else
5659                --  Parent is not the name of an instantiation.
5660
5661                Install_Noninstance_Specs (Inst_Par);
5662
5663                exit;
5664             end if;
5665
5666          else
5667             --  Previous error.
5668
5669             exit;
5670          end if;
5671       end loop;
5672
5673       if Present (First_Gen) then
5674          Append_Elmt (First_Par, Ancestors);
5675
5676       else
5677          Install_Noninstance_Specs (First_Par);
5678       end if;
5679
5680       if not Is_Empty_Elmt_List (Ancestors) then
5681          Elmt := First_Elmt (Ancestors);
5682
5683          while Present (Elmt) loop
5684             Install_Spec (Node (Elmt));
5685             Install_Formal_Packages (Node (Elmt));
5686
5687             Next_Elmt (Elmt);
5688          end loop;
5689       end if;
5690
5691       if not In_Body then
5692          New_Scope (S);
5693       end if;
5694    end Install_Parent;
5695
5696    --------------------------------
5697    -- Instantiate_Formal_Package --
5698    --------------------------------
5699
5700    function Instantiate_Formal_Package
5701      (Formal          : Node_Id;
5702       Actual          : Node_Id;
5703       Analyzed_Formal : Node_Id)
5704       return            List_Id
5705    is
5706       Loc         : constant Source_Ptr := Sloc (Actual);
5707       Actual_Pack : Entity_Id;
5708       Formal_Pack : Entity_Id;
5709       Gen_Parent  : Entity_Id;
5710       Decls       : List_Id;
5711       Nod         : Node_Id;
5712       Parent_Spec : Node_Id;
5713
5714       function Formal_Entity
5715         (F       : Node_Id;
5716          Act_Ent : Entity_Id)
5717          return    Entity_Id;
5718       --  Returns the entity associated with the given formal F. In the
5719       --  case where F is a formal package, this function will iterate
5720       --  through all of F's formals and enter map associations from the
5721       --  actuals occurring in the formal package's corresponding actual
5722       --  package (obtained via Act_Ent) to the formal package's formal
5723       --  parameters. This function is called recursively for arbitrary
5724       --  levels of formal packages.
5725
5726       procedure Map_Entities (Form : Entity_Id; Act : Entity_Id);
5727       --  Within the generic part, entities in the formal package are
5728       --  visible. To validate subsequent type declarations, indicate
5729       --  the correspondence betwen the entities in the analyzed formal,
5730       --  and the entities in  the actual package. There are three packages
5731       --  involved in the instantiation of a formal package: the parent
5732       --  generic P1 which appears in the generic declaration, the fake
5733       --  instantiation P2 which appears in the analyzed generic, and whose
5734       --  visible entities may be used in subsequent formals, and the actual
5735       --  P3 in the instance. To validate subsequent formals, me indicate
5736       --  that the entities in P2 are mapped into those of P3. The mapping of
5737       --  entities has to be done recursively for nested packages.
5738
5739       -------------------
5740       -- Formal_Entity --
5741       -------------------
5742
5743       function Formal_Entity
5744         (F       : Node_Id;
5745          Act_Ent : Entity_Id)
5746          return    Entity_Id
5747       is
5748          Orig_Node : Node_Id := F;
5749
5750       begin
5751          case Nkind (F) is
5752             when N_Formal_Object_Declaration =>
5753                return Defining_Identifier (F);
5754
5755             when N_Formal_Type_Declaration =>
5756                return Defining_Identifier (F);
5757
5758             when N_Formal_Subprogram_Declaration =>
5759                return Defining_Unit_Name (Specification (F));
5760
5761             when N_Formal_Package_Declaration |
5762                  N_Generic_Package_Declaration =>
5763
5764                if Nkind (F) = N_Generic_Package_Declaration then
5765                   Orig_Node := Original_Node (F);
5766                end if;
5767
5768                declare
5769                   Actual_Ent  : Entity_Id := First_Entity (Act_Ent);
5770                   Formal_Node : Node_Id;
5771                   Formal_Ent  : Entity_Id;
5772
5773                   Gen_Decl : Node_Id :=
5774                                Unit_Declaration_Node
5775                                  (Entity (Name (Orig_Node)));
5776                   Formals  : List_Id :=
5777                                Generic_Formal_Declarations (Gen_Decl);
5778
5779                begin
5780                   if Present (Formals) then
5781                      Formal_Node := First_Non_Pragma (Formals);
5782                   else
5783                      Formal_Node := Empty;
5784                   end if;
5785
5786                   --  As for the loop further below, this loop is making
5787                   --  a probably invalid assumption about the correspondence
5788                   --  between formals and actuals and eventually needs to
5789                   --  corrected to account for cases where the formals are
5790                   --  not synchronized and in one-to-one correspondence
5791                   --  with actuals. ???
5792
5793                   --  What is certain is that for a legal program the
5794                   --  presence of actual entities guarantees the existing
5795                   --  of formal ones.
5796
5797                   while Present (Actual_Ent)
5798                     and then Present (Formal_Node)
5799                     and then Actual_Ent /= First_Private_Entity (Act_Ent)
5800                   loop
5801                      --  ???  Are the following calls also needed here:
5802                      --
5803                      --  Set_Is_Hidden (Actual_Ent, False);
5804                      --  Set_Is_Potentially_Use_Visible
5805                      --    (Actual_Ent, In_Use (Act_Ent));
5806
5807                      Formal_Ent := Formal_Entity (Formal_Node, Actual_Ent);
5808                      if Present (Formal_Ent) then
5809                         Set_Instance_Of (Formal_Ent, Actual_Ent);
5810                      end if;
5811                      Next_Non_Pragma (Formal_Node);
5812
5813                      Next_Entity (Actual_Ent);
5814                   end loop;
5815                end;
5816
5817                return Defining_Identifier (Orig_Node);
5818
5819             when N_Use_Package_Clause =>
5820                return Empty;
5821
5822             when N_Use_Type_Clause =>
5823                return Empty;
5824
5825             --  We return Empty for all other encountered forms of
5826             --  declarations because there are some cases of nonformal
5827             --  sorts of declaration that can show up (e.g., when array
5828             --  formals are present). Since it's not clear what kinds
5829             --  can appear among the formals, we won't raise failure here.
5830
5831             when others =>
5832                return Empty;
5833
5834          end case;
5835       end Formal_Entity;
5836
5837       ------------------
5838       -- Map_Entities --
5839       ------------------
5840
5841       procedure Map_Entities (Form : Entity_Id; Act : Entity_Id) is
5842          E1 : Entity_Id;
5843          E2 : Entity_Id;
5844
5845       begin
5846          Set_Instance_Of (Form, Act);
5847
5848          E1 := First_Entity (Form);
5849          E2 := First_Entity (Act);
5850          while Present (E1)
5851            and then E1 /= First_Private_Entity (Form)
5852          loop
5853             if not Is_Internal (E1)
5854               and then not Is_Class_Wide_Type (E1)
5855             then
5856
5857                while Present (E2)
5858                  and then Chars (E2) /= Chars (E1)
5859                loop
5860                   Next_Entity (E2);
5861                end loop;
5862
5863                if No (E2) then
5864                   exit;
5865                else
5866                   Set_Instance_Of (E1, E2);
5867
5868                   if Is_Type (E1)
5869                     and then Is_Tagged_Type (E2)
5870                   then
5871                      Set_Instance_Of
5872                        (Class_Wide_Type (E1), Class_Wide_Type (E2));
5873                   end if;
5874
5875                   if Ekind (E1) = E_Package
5876                     and then No (Renamed_Object (E1))
5877                   then
5878                      Map_Entities (E1, E2);
5879                   end if;
5880                end if;
5881             end if;
5882
5883             Next_Entity (E1);
5884          end loop;
5885       end Map_Entities;
5886
5887    --  Start of processing for Instantiate_Formal_Package
5888
5889    begin
5890       Analyze (Actual);
5891
5892       if not Is_Entity_Name (Actual)
5893         or else  Ekind (Entity (Actual)) /= E_Package
5894       then
5895          Error_Msg_N
5896            ("expect package instance to instantiate formal", Actual);
5897          Abandon_Instantiation (Actual);
5898          raise Program_Error;
5899
5900       else
5901          Actual_Pack := Entity (Actual);
5902          Set_Is_Instantiated (Actual_Pack);
5903
5904          --  The actual may be a renamed package, or an outer generic
5905          --  formal package whose instantiation is converted into a renaming.
5906
5907          if Present (Renamed_Object (Actual_Pack)) then
5908             Actual_Pack := Renamed_Object (Actual_Pack);
5909          end if;
5910
5911          if Nkind (Analyzed_Formal) = N_Formal_Package_Declaration then
5912             Gen_Parent  := Get_Instance_Of (Entity (Name (Analyzed_Formal)));
5913             Formal_Pack := Defining_Identifier (Analyzed_Formal);
5914          else
5915             Gen_Parent :=
5916               Generic_Parent (Specification (Analyzed_Formal));
5917             Formal_Pack :=
5918               Defining_Unit_Name (Specification (Analyzed_Formal));
5919          end if;
5920
5921          if Nkind (Parent (Actual_Pack)) = N_Defining_Program_Unit_Name then
5922             Parent_Spec := Specification (Unit_Declaration_Node (Actual_Pack));
5923          else
5924             Parent_Spec := Parent (Actual_Pack);
5925          end if;
5926
5927          if Gen_Parent = Any_Id then
5928             Error_Msg_N
5929               ("previous error in declaration of formal package", Actual);
5930             Abandon_Instantiation (Actual);
5931
5932          elsif
5933            Generic_Parent (Parent_Spec) /= Get_Instance_Of (Gen_Parent)
5934          then
5935             Error_Msg_NE
5936               ("actual parameter must be instance of&", Actual, Gen_Parent);
5937             Abandon_Instantiation (Actual);
5938          end if;
5939
5940          Set_Instance_Of (Defining_Identifier (Formal), Actual_Pack);
5941          Map_Entities (Formal_Pack, Actual_Pack);
5942
5943          Nod :=
5944            Make_Package_Renaming_Declaration (Loc,
5945              Defining_Unit_Name => New_Copy (Defining_Identifier (Formal)),
5946              Name               => New_Reference_To (Actual_Pack, Loc));
5947
5948          Set_Associated_Formal_Package (Defining_Unit_Name (Nod),
5949            Defining_Identifier (Formal));
5950          Decls := New_List (Nod);
5951
5952          --  If the formal F has a box, then the generic declarations are
5953          --  visible in the generic G. In an instance of G, the corresponding
5954          --  entities in the actual for F (which are the actuals for the
5955          --  instantiation of the generic that F denotes) must also be made
5956          --  visible for analysis of the current instance. On exit from the
5957          --  current instance, those entities are made private again. If the
5958          --  actual is currently in use, these entities are also use-visible.
5959
5960          --  The loop through the actual entities also steps through the
5961          --  formal entities and enters associations from formals to
5962          --  actuals into the renaming map. This is necessary to properly
5963          --  handle checking of actual parameter associations for later
5964          --  formals that depend on actuals declared in the formal package.
5965          --
5966          --  This processing needs to be reviewed at some point because
5967          --  it is probably not entirely correct as written. For example
5968          --  there may not be a strict one-to-one correspondence between
5969          --  actuals and formals and this loop is currently assuming that
5970          --  there is. ???
5971
5972          if Box_Present (Formal) then
5973             declare
5974                Actual_Ent  : Entity_Id := First_Entity (Actual_Pack);
5975                Formal_Node : Node_Id := Empty;
5976                Formal_Ent  : Entity_Id;
5977                Gen_Decl    : Node_Id := Unit_Declaration_Node (Gen_Parent);
5978                Formals     : List_Id := Generic_Formal_Declarations (Gen_Decl);
5979
5980             begin
5981                if Present (Formals) then
5982                   Formal_Node := First_Non_Pragma (Formals);
5983                end if;
5984
5985                while Present (Actual_Ent)
5986                  and then Actual_Ent /= First_Private_Entity (Actual_Pack)
5987                loop
5988                   Set_Is_Hidden (Actual_Ent, False);
5989                   Set_Is_Potentially_Use_Visible
5990                     (Actual_Ent, In_Use (Actual_Pack));
5991
5992                   if Present (Formal_Node) then
5993                      Formal_Ent := Formal_Entity (Formal_Node, Actual_Ent);
5994
5995                      if Present (Formal_Ent) then
5996                         Set_Instance_Of (Formal_Ent, Actual_Ent);
5997                      end if;
5998
5999                      Next_Non_Pragma (Formal_Node);
6000                   end if;
6001
6002                   Next_Entity (Actual_Ent);
6003                end loop;
6004             end;
6005
6006          --  If the formal is not declared with a box, reanalyze it as
6007          --  an instantiation, to verify the matching rules of 12.7. The
6008          --  actual checks are performed after the generic associations
6009          --  been analyzed.
6010
6011          else
6012             declare
6013                I_Pack : constant Entity_Id :=
6014                           Make_Defining_Identifier (Sloc (Actual),
6015                             Chars => New_Internal_Name  ('P'));
6016
6017             begin
6018                Set_Is_Internal (I_Pack);
6019
6020                Append_To (Decls,
6021                  Make_Package_Instantiation (Sloc (Actual),
6022                    Defining_Unit_Name => I_Pack,
6023                    Name => New_Occurrence_Of (Gen_Parent, Sloc (Actual)),
6024                    Generic_Associations =>
6025                      Generic_Associations (Formal)));
6026             end;
6027          end if;
6028
6029          return Decls;
6030       end if;
6031
6032    end Instantiate_Formal_Package;
6033
6034    -----------------------------------
6035    -- Instantiate_Formal_Subprogram --
6036    -----------------------------------
6037
6038    function Instantiate_Formal_Subprogram
6039      (Formal          : Node_Id;
6040       Actual          : Node_Id;
6041       Analyzed_Formal : Node_Id)
6042       return Node_Id
6043    is
6044       Loc        : Source_Ptr := Sloc (Instantiation_Node);
6045       Formal_Sub : constant Entity_Id :=
6046                      Defining_Unit_Name (Specification (Formal));
6047       Analyzed_S : constant Entity_Id :=
6048                      Defining_Unit_Name (Specification (Analyzed_Formal));
6049       Decl_Node  : Node_Id;
6050       Nam        : Node_Id;
6051       New_Spec   : Node_Id;
6052
6053       function From_Parent_Scope (Subp : Entity_Id) return Boolean;
6054       --  If the generic is a child unit, the parent has been installed
6055       --  on the scope stack, but a default subprogram cannot resolve to
6056       --  something on the parent because that parent is not really part
6057       --  of the visible context (it is there to resolve explicit local
6058       --  entities). If the default has resolved in this way, we remove
6059       --  the entity from immediate visibility and analyze the node again
6060       --  to emit an error message or find another visible candidate.
6061
6062       procedure Valid_Actual_Subprogram (Act : Node_Id);
6063       --  Perform legality check and raise exception on failure.
6064
6065       -----------------------
6066       -- From_Parent_Scope --
6067       -----------------------
6068
6069       function From_Parent_Scope (Subp : Entity_Id) return Boolean is
6070          Gen_Scope : Node_Id := Scope (Analyzed_S);
6071
6072       begin
6073          while Present (Gen_Scope)
6074            and then  Is_Child_Unit (Gen_Scope)
6075          loop
6076             if Scope (Subp) = Scope (Gen_Scope) then
6077                return True;
6078             end if;
6079
6080             Gen_Scope := Scope (Gen_Scope);
6081          end loop;
6082
6083          return False;
6084       end From_Parent_Scope;
6085
6086       -----------------------------
6087       -- Valid_Actual_Subprogram --
6088       -----------------------------
6089
6090       procedure Valid_Actual_Subprogram (Act : Node_Id) is
6091       begin
6092          if not Is_Entity_Name (Act)
6093            and then Nkind (Act) /= N_Operator_Symbol
6094            and then Nkind (Act) /= N_Attribute_Reference
6095            and then Nkind (Act) /= N_Selected_Component
6096            and then Nkind (Act) /= N_Indexed_Component
6097            and then Nkind (Act) /= N_Character_Literal
6098            and then Nkind (Act) /= N_Explicit_Dereference
6099          then
6100             if Etype (Act) /= Any_Type then
6101                Error_Msg_NE
6102                  ("Expect subprogram name to instantiate &",
6103                   Instantiation_Node, Formal_Sub);
6104             end if;
6105
6106             --  In any case, instantiation cannot continue.
6107
6108             Abandon_Instantiation (Instantiation_Node);
6109          end if;
6110       end Valid_Actual_Subprogram;
6111
6112    --  Start of processing for Instantiate_Formal_Subprogram
6113
6114    begin
6115       New_Spec := New_Copy_Tree (Specification (Formal));
6116
6117       --  Create new entity for the actual (New_Copy_Tree does not).
6118
6119       Set_Defining_Unit_Name
6120         (New_Spec, Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
6121
6122       --  Find entity of actual. If the actual is an attribute reference, it
6123       --  cannot be resolved here (its formal is missing) but is handled
6124       --  instead in Attribute_Renaming. If the actual is overloaded, it is
6125       --  fully resolved subsequently, when the renaming declaration for the
6126       --  formal is analyzed. If it is an explicit dereference, resolve the
6127       --  prefix but not the actual itself, to prevent interpretation as a
6128       --  call.
6129
6130       if Present (Actual) then
6131          Loc := Sloc (Actual);
6132          Set_Sloc (New_Spec, Loc);
6133
6134          if Nkind (Actual) = N_Operator_Symbol then
6135             Find_Direct_Name (Actual);
6136
6137          elsif Nkind (Actual) = N_Explicit_Dereference then
6138             Analyze (Prefix (Actual));
6139
6140          elsif Nkind (Actual) /= N_Attribute_Reference then
6141             Analyze (Actual);
6142          end if;
6143
6144          Valid_Actual_Subprogram (Actual);
6145          Nam := Actual;
6146
6147       elsif Present (Default_Name (Formal)) then
6148
6149          if Nkind (Default_Name (Formal)) /= N_Attribute_Reference
6150            and then Nkind (Default_Name (Formal)) /= N_Selected_Component
6151            and then Nkind (Default_Name (Formal)) /= N_Indexed_Component
6152            and then Nkind (Default_Name (Formal)) /= N_Character_Literal
6153            and then Present (Entity (Default_Name (Formal)))
6154          then
6155             Nam := New_Occurrence_Of (Entity (Default_Name (Formal)), Loc);
6156          else
6157             Nam := New_Copy (Default_Name (Formal));
6158             Set_Sloc (Nam, Loc);
6159          end if;
6160
6161       elsif Box_Present (Formal) then
6162
6163          --  Actual is resolved at the point of instantiation. Create
6164          --  an identifier or operator with the same name as the formal.
6165
6166          if Nkind (Formal_Sub) = N_Defining_Operator_Symbol then
6167             Nam := Make_Operator_Symbol (Loc,
6168               Chars =>  Chars (Formal_Sub),
6169               Strval => No_String);
6170          else
6171             Nam := Make_Identifier (Loc, Chars (Formal_Sub));
6172          end if;
6173
6174       else
6175          Error_Msg_NE
6176            ("missing actual for instantiation of &",
6177                                  Instantiation_Node, Formal_Sub);
6178          Abandon_Instantiation (Instantiation_Node);
6179       end if;
6180
6181       Decl_Node :=
6182         Make_Subprogram_Renaming_Declaration (Loc,
6183           Specification => New_Spec,
6184           Name => Nam);
6185
6186       --  Gather possible interpretations for the actual before analyzing the
6187       --  instance. If overloaded, it will be resolved when analyzing the
6188       --  renaming declaration.
6189
6190       if Box_Present (Formal)
6191         and then No (Actual)
6192       then
6193          Analyze (Nam);
6194
6195          if Is_Child_Unit (Scope (Analyzed_S))
6196            and then Present (Entity (Nam))
6197          then
6198             if not Is_Overloaded (Nam) then
6199
6200                if From_Parent_Scope (Entity (Nam)) then
6201                   Set_Is_Immediately_Visible (Entity (Nam), False);
6202                   Set_Entity (Nam, Empty);
6203                   Set_Etype (Nam, Empty);
6204
6205                   Analyze (Nam);
6206
6207                   Set_Is_Immediately_Visible (Entity (Nam));
6208                end if;
6209
6210             else
6211                declare
6212                   I  : Interp_Index;
6213                   It : Interp;
6214
6215                begin
6216                   Get_First_Interp (Nam, I, It);
6217
6218                   while Present (It.Nam) loop
6219                      if From_Parent_Scope (It.Nam) then
6220                         Remove_Interp (I);
6221                      end if;
6222
6223                      Get_Next_Interp (I, It);
6224                   end loop;
6225                end;
6226             end if;
6227          end if;
6228       end if;
6229
6230       --  The generic instantiation freezes the actual. This can only be
6231       --  done once the actual is resolved, in the analysis of the renaming
6232       --  declaration. To indicate that must be done, we set the corresponding
6233       --  spec of the node to point to the formal subprogram declaration.
6234
6235       Set_Corresponding_Spec (Decl_Node, Analyzed_Formal);
6236
6237       --  We cannot analyze the renaming declaration, and thus find the
6238       --  actual, until the all the actuals are assembled in the instance.
6239       --  For subsequent checks of other actuals, indicate the node that
6240       --  will hold the instance of this formal.
6241
6242       Set_Instance_Of (Analyzed_S, Nam);
6243
6244       if Nkind (Actual) = N_Selected_Component
6245         and then Is_Task_Type (Etype (Prefix (Actual)))
6246         and then not Is_Frozen (Etype (Prefix (Actual)))
6247       then
6248          --  The renaming declaration will create a body, which must appear
6249          --  outside of the instantiation, We move the renaming declaration
6250          --  out of the instance, and create an additional renaming inside,
6251          --  to prevent freezing anomalies.
6252
6253          declare
6254             Anon_Id : constant Entity_Id :=
6255                         Make_Defining_Identifier
6256                           (Loc, New_Internal_Name ('E'));
6257          begin
6258             Set_Defining_Unit_Name (New_Spec, Anon_Id);
6259             Insert_Before (Instantiation_Node, Decl_Node);
6260             Analyze (Decl_Node);
6261
6262             --  Now create renaming within the instance.
6263
6264             Decl_Node :=
6265               Make_Subprogram_Renaming_Declaration (Loc,
6266                 Specification => New_Copy_Tree (New_Spec),
6267                 Name => New_Occurrence_Of (Anon_Id, Loc));
6268
6269             Set_Defining_Unit_Name (Specification (Decl_Node),
6270               Make_Defining_Identifier (Loc, Chars (Formal_Sub)));
6271          end;
6272       end if;
6273
6274       return Decl_Node;
6275    end Instantiate_Formal_Subprogram;
6276
6277    ------------------------
6278    -- Instantiate_Object --
6279    ------------------------
6280
6281    function Instantiate_Object
6282      (Formal          : Node_Id;
6283       Actual          : Node_Id;
6284       Analyzed_Formal : Node_Id)
6285       return            List_Id
6286    is
6287       Formal_Id : constant Entity_Id  := Defining_Identifier (Formal);
6288       Type_Id   : constant Node_Id    := Subtype_Mark (Formal);
6289       Loc       : constant Source_Ptr := Sloc (Actual);
6290       Act_Assoc : constant Node_Id    := Parent (Actual);
6291       Orig_Ftyp : constant Entity_Id  :=
6292                     Etype (Defining_Identifier (Analyzed_Formal));
6293       Ftyp      : Entity_Id;
6294       Decl_Node : Node_Id;
6295       Subt_Decl : Node_Id := Empty;
6296       List      : List_Id := New_List;
6297
6298    begin
6299       if Get_Instance_Of (Formal_Id) /= Formal_Id then
6300          Error_Msg_N ("duplicate instantiation of generic parameter", Actual);
6301       end if;
6302
6303       Set_Parent (List, Parent (Actual));
6304
6305       --  OUT present
6306
6307       if Out_Present (Formal) then
6308
6309          --  An IN OUT generic actual must be a name. The instantiation is
6310          --  a renaming declaration. The actual is the name being renamed.
6311          --  We use the actual directly, rather than a copy, because it is not
6312          --  used further in the list of actuals, and because a copy or a use
6313          --  of relocate_node is incorrect if the instance is nested within
6314          --  a generic. In order to simplify ASIS searches, the Generic_Parent
6315          --  field links the declaration to the generic association.
6316
6317          if No (Actual) then
6318             Error_Msg_NE
6319               ("missing actual for instantiation of &",
6320                Instantiation_Node, Formal_Id);
6321             Abandon_Instantiation (Instantiation_Node);
6322          end if;
6323
6324          Decl_Node :=
6325            Make_Object_Renaming_Declaration (Loc,
6326              Defining_Identifier => New_Copy (Formal_Id),
6327              Subtype_Mark        => New_Copy_Tree (Type_Id),
6328              Name                => Actual);
6329
6330          Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
6331
6332          --  The analysis of the actual may produce insert_action nodes, so
6333          --  the declaration must have a context in which to attach them.
6334
6335          Append (Decl_Node, List);
6336          Analyze (Actual);
6337
6338          --  This check is performed here because Analyze_Object_Renaming
6339          --  will not check it when Comes_From_Source is False. Note
6340          --  though that the check for the actual being the name of an
6341          --  object will be performed in Analyze_Object_Renaming.
6342
6343          if Is_Object_Reference (Actual)
6344            and then Is_Dependent_Component_Of_Mutable_Object (Actual)
6345          then
6346             Error_Msg_N
6347               ("illegal discriminant-dependent component for in out parameter",
6348                Actual);
6349          end if;
6350
6351          --  The actual has to be resolved in order to check that it is
6352          --  a variable (due to cases such as F(1), where F returns
6353          --  access to an array, and for overloaded prefixes).
6354
6355          Ftyp :=
6356            Get_Instance_Of (Etype (Defining_Identifier (Analyzed_Formal)));
6357
6358          if Is_Private_Type (Ftyp)
6359            and then not Is_Private_Type (Etype (Actual))
6360            and then (Base_Type (Full_View (Ftyp)) = Base_Type (Etype (Actual))
6361                       or else Base_Type (Etype (Actual)) = Ftyp)
6362          then
6363             --  If the actual has the type of the full view of the formal,
6364             --  or else a non-private subtype of the formal, then
6365             --  the visibility of the formal type has changed. Add to the
6366             --  actuals a subtype declaration that will force the exchange
6367             --  of views in the body of the instance as well.
6368
6369             Subt_Decl :=
6370               Make_Subtype_Declaration (Loc,
6371                  Defining_Identifier =>
6372                    Make_Defining_Identifier (Loc, New_Internal_Name ('P')),
6373                  Subtype_Indication  => New_Occurrence_Of (Ftyp, Loc));
6374
6375             Prepend (Subt_Decl, List);
6376
6377             Append_Elmt (Full_View (Ftyp), Exchanged_Views);
6378             Exchange_Declarations (Ftyp);
6379          end if;
6380
6381          Resolve (Actual, Ftyp);
6382
6383          if not Is_Variable (Actual) or else Paren_Count (Actual) > 0 then
6384             Error_Msg_NE
6385               ("actual for& must be a variable", Actual, Formal_Id);
6386
6387          elsif Base_Type (Ftyp) /= Base_Type (Etype (Actual)) then
6388             Error_Msg_NE (
6389               "type of actual does not match type of&", Actual, Formal_Id);
6390
6391          end if;
6392
6393          Note_Possible_Modification (Actual);
6394
6395          --  Check for instantiation of atomic/volatile actual for
6396          --  non-atomic/volatile formal (RM C.6 (12)).
6397
6398          if Is_Atomic_Object (Actual)
6399            and then not Is_Atomic (Orig_Ftyp)
6400          then
6401             Error_Msg_N
6402               ("cannot instantiate non-atomic formal object " &
6403                "with atomic actual", Actual);
6404
6405          elsif Is_Volatile_Object (Actual)
6406            and then not Is_Volatile (Orig_Ftyp)
6407          then
6408             Error_Msg_N
6409               ("cannot instantiate non-volatile formal object " &
6410                "with volatile actual", Actual);
6411          end if;
6412
6413       --  OUT not present
6414
6415       else
6416          --  The instantiation of a generic formal in-parameter
6417          --  is a constant declaration. The actual is the expression for
6418          --  that declaration.
6419
6420          if Present (Actual) then
6421
6422             Decl_Node := Make_Object_Declaration (Loc,
6423               Defining_Identifier => New_Copy (Formal_Id),
6424               Constant_Present => True,
6425               Object_Definition => New_Copy_Tree (Type_Id),
6426               Expression => Actual);
6427
6428             Set_Corresponding_Generic_Association (Decl_Node, Act_Assoc);
6429
6430             --  A generic formal object of a tagged type is defined
6431             --  to be aliased so the new constant must also be treated
6432             --  as aliased.
6433
6434             if Is_Tagged_Type
6435                  (Etype (Defining_Identifier (Analyzed_Formal)))
6436             then
6437                Set_Aliased_Present (Decl_Node);
6438             end if;
6439
6440             Append (Decl_Node, List);
6441             Analyze (Actual);
6442
6443             declare
6444                Typ : Entity_Id
6445                       := Get_Instance_Of
6446                            (Etype (Defining_Identifier (Analyzed_Formal)));
6447             begin
6448                Freeze_Before (Instantiation_Node, Typ);
6449
6450                --  If the actual is an aggregate, perform name resolution
6451                --  on its components (the analysis of an aggregate does not
6452                --  do it) to capture local names that may be hidden if the
6453                --  generic is a child unit.
6454
6455                if Nkind (Actual) = N_Aggregate then
6456                      Pre_Analyze_And_Resolve (Actual, Typ);
6457                end if;
6458             end;
6459
6460          elsif Present (Expression (Formal)) then
6461
6462             --  Use default to construct declaration.
6463
6464             Decl_Node :=
6465               Make_Object_Declaration (Sloc (Formal),
6466                 Defining_Identifier => New_Copy (Formal_Id),
6467                 Constant_Present    => True,
6468                 Object_Definition   => New_Copy (Type_Id),
6469                 Expression          => New_Copy_Tree (Expression (Formal)));
6470
6471             Append (Decl_Node, List);
6472             Set_Analyzed (Expression (Decl_Node), False);
6473
6474          else
6475             Error_Msg_NE
6476               ("missing actual for instantiation of &",
6477                Instantiation_Node, Formal_Id);
6478             Abandon_Instantiation (Instantiation_Node);
6479          end if;
6480
6481       end if;
6482
6483       return List;
6484    end Instantiate_Object;
6485
6486    ------------------------------
6487    -- Instantiate_Package_Body --
6488    ------------------------------
6489
6490    procedure Instantiate_Package_Body
6491      (Body_Info : Pending_Body_Info)
6492    is
6493       Act_Decl    : constant Node_Id    := Body_Info.Act_Decl;
6494       Inst_Node   : constant Node_Id    := Body_Info.Inst_Node;
6495       Loc         : constant Source_Ptr := Sloc (Inst_Node);
6496
6497       Gen_Id      : constant Node_Id    := Name (Inst_Node);
6498       Gen_Unit    : constant Entity_Id  := Entity (Name (Inst_Node));
6499       Gen_Decl    : constant Node_Id    := Unit_Declaration_Node (Gen_Unit);
6500       Act_Spec    : constant Node_Id    := Specification (Act_Decl);
6501       Act_Decl_Id : constant Entity_Id  := Defining_Entity (Act_Spec);
6502
6503       Act_Body_Name : Node_Id;
6504       Gen_Body      : Node_Id;
6505       Gen_Body_Id   : Node_Id;
6506       Act_Body      : Node_Id;
6507       Act_Body_Id   : Entity_Id;
6508
6509       Parent_Installed : Boolean := False;
6510       Save_Style_Check : Boolean := Style_Check;
6511
6512    begin
6513       Gen_Body_Id := Corresponding_Body (Gen_Decl);
6514
6515       --  The instance body may already have been processed, as the parent
6516       --  of another instance that is inlined. (Load_Parent_Of_Generic).
6517
6518       if Present (Corresponding_Body (Instance_Spec (Inst_Node))) then
6519          return;
6520       end if;
6521
6522       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
6523
6524       if No (Gen_Body_Id) then
6525          Load_Parent_Of_Generic (Inst_Node, Specification (Gen_Decl));
6526          Gen_Body_Id := Corresponding_Body (Gen_Decl);
6527       end if;
6528
6529       --  Establish global variable for sloc adjustment and for error
6530       --  recovery.
6531
6532       Instantiation_Node := Inst_Node;
6533
6534       if Present (Gen_Body_Id) then
6535          Save_Env (Gen_Unit, Act_Decl_Id);
6536          Style_Check := False;
6537          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
6538
6539          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
6540
6541          Create_Instantiation_Source
6542           (Inst_Node, Gen_Body_Id, S_Adjustment);
6543
6544          Act_Body :=
6545            Copy_Generic_Node
6546              (Original_Node (Gen_Body), Empty, Instantiating => True);
6547
6548          --  Build new name (possibly qualified) for body declaration.
6549
6550          Act_Body_Id := New_Copy (Act_Decl_Id);
6551
6552          --  Some attributes of the spec entity are not inherited by the
6553          --  body entity.
6554
6555          Set_Handler_Records (Act_Body_Id, No_List);
6556
6557          if Nkind (Defining_Unit_Name (Act_Spec)) =
6558                                            N_Defining_Program_Unit_Name
6559          then
6560             Act_Body_Name :=
6561               Make_Defining_Program_Unit_Name (Loc,
6562                 Name => New_Copy_Tree (Name (Defining_Unit_Name (Act_Spec))),
6563                 Defining_Identifier => Act_Body_Id);
6564          else
6565             Act_Body_Name :=  Act_Body_Id;
6566          end if;
6567
6568          Set_Defining_Unit_Name (Act_Body, Act_Body_Name);
6569
6570          Set_Corresponding_Spec (Act_Body, Act_Decl_Id);
6571          Check_Generic_Actuals (Act_Decl_Id, False);
6572
6573          --  If it is a child unit, make the parent instance (which is an
6574          --  instance of the parent of the generic) visible. The parent
6575          --  instance is the prefix of the name of the generic unit.
6576
6577          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
6578            and then Nkind (Gen_Id) = N_Expanded_Name
6579          then
6580             Install_Parent (Entity (Prefix (Gen_Id)), In_Body => True);
6581             Parent_Installed := True;
6582
6583          elsif Is_Child_Unit (Gen_Unit) then
6584             Install_Parent (Scope (Gen_Unit), In_Body => True);
6585             Parent_Installed := True;
6586          end if;
6587
6588          --  If the instantiation is a library unit, and this is the main
6589          --  unit, then build the resulting compilation unit nodes for the
6590          --  instance. If this is a compilation unit but it is not the main
6591          --  unit, then it is the body of a unit in the context, that is being
6592          --  compiled because it is encloses some inlined unit or another
6593          --  generic unit being instantiated. In that case, this body is not
6594          --  part of the current compilation, and is not attached to the tree,
6595          --  but its parent must be set for analysis.
6596
6597          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
6598
6599             --  Replace instance node with body of instance, and create
6600             --  new node for corresponding instance declaration.
6601
6602             Build_Instance_Compilation_Unit_Nodes
6603               (Inst_Node, Act_Body, Act_Decl);
6604             Analyze (Inst_Node);
6605
6606             if Parent (Inst_Node) = Cunit (Main_Unit) then
6607
6608                --  If the instance is a child unit itself, then set the
6609                --  scope of the expanded body to be the parent of the
6610                --  instantiation (ensuring that the fully qualified name
6611                --  will be generated for the elaboration subprogram).
6612
6613                if Nkind (Defining_Unit_Name (Act_Spec)) =
6614                                               N_Defining_Program_Unit_Name
6615                then
6616                   Set_Scope
6617                     (Defining_Entity (Inst_Node), Scope (Act_Decl_Id));
6618                end if;
6619             end if;
6620
6621          --  Case where instantiation is not a library unit
6622
6623          else
6624             --  If this is an early instantiation, i.e. appears textually
6625             --  before the corresponding body and must be elaborated first,
6626             --  indicate that the body instance is to be delayed.
6627
6628             Install_Body (Act_Body, Inst_Node, Gen_Body, Gen_Decl);
6629
6630             --  Now analyze the body. We turn off all checks if this is
6631             --  an internal unit, since there is no reason to have checks
6632             --  on for any predefined run-time library code. All such
6633             --  code is designed to be compiled with checks off.
6634
6635             --  Note that we do NOT apply this criterion to children of
6636             --  GNAT (or on VMS, children of DEC). The latter units must
6637             --  suppress checks explicitly if this is needed.
6638
6639             if Is_Predefined_File_Name
6640                  (Unit_File_Name (Get_Source_Unit (Gen_Decl)))
6641             then
6642                Analyze (Act_Body, Suppress => All_Checks);
6643             else
6644                Analyze (Act_Body);
6645             end if;
6646          end if;
6647
6648          if not Generic_Separately_Compiled (Gen_Unit) then
6649             Inherit_Context (Gen_Body, Inst_Node);
6650          end if;
6651
6652          Restore_Private_Views (Act_Decl_Id);
6653          Restore_Env;
6654          Style_Check := Save_Style_Check;
6655
6656       --  If we have no body, and the unit requires a body, then complain.
6657       --  This complaint is suppressed if we have detected other errors
6658       --  (since a common reason for missing the body is that it had errors).
6659
6660       elsif Unit_Requires_Body (Gen_Unit) then
6661          if Errors_Detected = 0 then
6662             Error_Msg_NE
6663               ("cannot find body of generic package &", Inst_Node, Gen_Unit);
6664
6665          --  Don't attempt to perform any cleanup actions if some other
6666          --  error was aready detected, since this can cause blowups.
6667
6668          else
6669             return;
6670          end if;
6671
6672       --  Case of package that does not need a body
6673
6674       else
6675          --  If the instantiation of the declaration is a library unit,
6676          --  rewrite the original package instantiation as a package
6677          --  declaration in the compilation unit node.
6678
6679          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
6680             Set_Parent_Spec (Act_Decl, Parent_Spec (Inst_Node));
6681             Rewrite (Inst_Node, Act_Decl);
6682
6683          --  If the instantiation is not a library unit, then append the
6684          --  declaration to the list of implicitly generated entities.
6685          --  unless it is already a list member which means that it was
6686          --  already processed
6687
6688          elsif not Is_List_Member (Act_Decl) then
6689             Mark_Rewrite_Insertion (Act_Decl);
6690             Insert_Before (Inst_Node, Act_Decl);
6691          end if;
6692       end if;
6693
6694       Expander_Mode_Restore;
6695
6696       --  Remove the parent instances if they have been placed on the
6697       --  scope stack to compile the body.
6698
6699       if Parent_Installed then
6700          Remove_Parent (In_Body => True);
6701       end if;
6702    end Instantiate_Package_Body;
6703
6704    ---------------------------------
6705    -- Instantiate_Subprogram_Body --
6706    ---------------------------------
6707
6708    procedure Instantiate_Subprogram_Body
6709      (Body_Info : Pending_Body_Info)
6710    is
6711       Act_Decl      : constant Node_Id    := Body_Info.Act_Decl;
6712       Inst_Node     : constant Node_Id    := Body_Info.Inst_Node;
6713       Loc           : constant Source_Ptr := Sloc (Inst_Node);
6714
6715       Decls         : List_Id;
6716       Gen_Id        : constant Node_Id   := Name (Inst_Node);
6717       Gen_Unit      : constant Entity_Id := Entity (Name (Inst_Node));
6718       Gen_Decl      : constant Node_Id   := Unit_Declaration_Node (Gen_Unit);
6719       Anon_Id       : constant Entity_Id :=
6720                         Defining_Unit_Name (Specification (Act_Decl));
6721       Gen_Body      : Node_Id;
6722       Gen_Body_Id   : Node_Id;
6723       Act_Body      : Node_Id;
6724       Act_Body_Id   : Entity_Id;
6725       Pack_Id       : Entity_Id := Defining_Unit_Name (Parent (Act_Decl));
6726       Pack_Body     : Node_Id;
6727       Prev_Formal   : Entity_Id;
6728       Unit_Renaming : Node_Id;
6729
6730       Parent_Installed : Boolean := False;
6731       Save_Style_Check : Boolean := Style_Check;
6732
6733    begin
6734       Gen_Body_Id := Corresponding_Body (Gen_Decl);
6735
6736       Expander_Mode_Save_And_Set (Body_Info.Expander_Status);
6737
6738       if No (Gen_Body_Id) then
6739          Load_Parent_Of_Generic (Inst_Node, Specification (Gen_Decl));
6740          Gen_Body_Id := Corresponding_Body (Gen_Decl);
6741       end if;
6742
6743       Instantiation_Node := Inst_Node;
6744
6745       if Present (Gen_Body_Id) then
6746          Gen_Body := Unit_Declaration_Node (Gen_Body_Id);
6747
6748          if Nkind (Gen_Body) = N_Subprogram_Body_Stub then
6749
6750             --  Either body is not present, or context is non-expanding, as
6751             --  when compiling a subunit. Mark the instance as completed.
6752
6753             Set_Has_Completion (Anon_Id);
6754             return;
6755          end if;
6756
6757          Save_Env (Gen_Unit, Anon_Id);
6758          Style_Check := False;
6759          Current_Sem_Unit := Body_Info.Current_Sem_Unit;
6760          Create_Instantiation_Source (Inst_Node, Gen_Body_Id, S_Adjustment);
6761
6762          Act_Body :=
6763            Copy_Generic_Node
6764              (Original_Node (Gen_Body), Empty, Instantiating => True);
6765          Act_Body_Id := Defining_Entity (Act_Body);
6766          Set_Chars (Act_Body_Id, Chars (Anon_Id));
6767          Set_Sloc (Act_Body_Id, Sloc (Defining_Entity (Inst_Node)));
6768          Set_Corresponding_Spec (Act_Body, Anon_Id);
6769          Set_Has_Completion (Anon_Id);
6770          Check_Generic_Actuals (Pack_Id, False);
6771
6772          --  If it is a child unit, make the parent instance (which is an
6773          --  instance of the parent of the generic) visible. The parent
6774          --  instance is the prefix of the name of the generic unit.
6775
6776          if Ekind (Scope (Gen_Unit)) = E_Generic_Package
6777            and then Nkind (Gen_Id) = N_Expanded_Name
6778          then
6779             Install_Parent (Entity (Prefix (Gen_Id)), In_Body => True);
6780             Parent_Installed := True;
6781
6782          elsif Is_Child_Unit (Gen_Unit) then
6783             Install_Parent (Scope (Gen_Unit), In_Body => True);
6784             Parent_Installed := True;
6785          end if;
6786
6787          --  Inside its body, a reference to the generic unit is a reference
6788          --  to the instance. The corresponding renaming is the first
6789          --  declaration in the body.
6790
6791          Unit_Renaming :=
6792            Make_Subprogram_Renaming_Declaration (Loc,
6793              Specification =>
6794                Copy_Generic_Node (
6795                  Specification (Original_Node (Gen_Body)),
6796                  Empty,
6797                  Instantiating => True),
6798              Name => New_Occurrence_Of (Anon_Id, Loc));
6799
6800          --  If there is a formal subprogram with the same name as the
6801          --  unit itself, do not add this renaming declaration. This is
6802          --  a temporary fix for one ACVC test. ???
6803
6804          Prev_Formal := First_Entity (Pack_Id);
6805          while Present (Prev_Formal) loop
6806             if Chars (Prev_Formal) = Chars (Gen_Unit)
6807               and then Is_Overloadable (Prev_Formal)
6808             then
6809                exit;
6810             end if;
6811
6812             Next_Entity (Prev_Formal);
6813          end loop;
6814
6815          if Present (Prev_Formal) then
6816             Decls :=  New_List (Act_Body);
6817          else
6818             Decls :=  New_List (Unit_Renaming, Act_Body);
6819          end if;
6820
6821          --  The subprogram body is placed in the body of a dummy package
6822          --  body, whose spec contains the subprogram declaration as well
6823          --  as the renaming declarations for the generic parameters.
6824
6825          Pack_Body := Make_Package_Body (Loc,
6826            Defining_Unit_Name => New_Copy (Pack_Id),
6827            Declarations       => Decls);
6828
6829          Set_Corresponding_Spec (Pack_Body, Pack_Id);
6830
6831          --  If the instantiation is a library unit, then build resulting
6832          --  compilation unit nodes for the instance. The declaration of
6833          --  the enclosing package is the grandparent of the subprogram
6834          --  declaration. First replace the instantiation node as the unit
6835          --  of the corresponding compilation.
6836
6837          if Nkind (Parent (Inst_Node)) = N_Compilation_Unit then
6838
6839             if Parent (Inst_Node) = Cunit (Main_Unit) then
6840                Set_Unit (Parent (Inst_Node), Inst_Node);
6841                Build_Instance_Compilation_Unit_Nodes
6842                  (Inst_Node, Pack_Body, Parent (Parent (Act_Decl)));
6843                Analyze (Inst_Node);
6844             else
6845                Set_Parent (Pack_Body, Parent (Inst_Node));
6846                Analyze (Pack_Body);
6847             end if;
6848
6849          else
6850             Insert_Before (Inst_Node, Pack_Body);
6851             Mark_Rewrite_Insertion (Pack_Body);
6852             Analyze (Pack_Body);
6853
6854             if Expander_Active then
6855                Freeze_Subprogram_Body (Inst_Node, Gen_Body, Pack_Id);
6856             end if;
6857          end if;
6858
6859          if not Generic_Separately_Compiled (Gen_Unit) then
6860             Inherit_Context (Gen_Body, Inst_Node);
6861          end if;
6862
6863          Restore_Private_Views (Pack_Id, False);
6864
6865          if Parent_Installed then
6866             Remove_Parent (In_Body => True);
6867          end if;
6868
6869          Restore_Env;
6870          Style_Check := Save_Style_Check;
6871
6872       --  Body not found. Error was emitted already. If there were no
6873       --  previous errors, this may be an instance whose scope is a premature
6874       --  instance. In that case we must insure that the (legal) program does
6875       --  raise program error if executed. We generate a subprogram body for
6876       --  this purpose. See DEC ac30vso.
6877
6878       elsif Errors_Detected = 0
6879         and then Nkind (Parent (Inst_Node)) /= N_Compilation_Unit
6880       then
6881          if Ekind (Anon_Id) = E_Procedure then
6882             Act_Body :=
6883               Make_Subprogram_Body (Loc,
6884                  Specification              =>
6885                    Make_Procedure_Specification (Loc,
6886                      Defining_Unit_Name         => New_Copy (Anon_Id),
6887                        Parameter_Specifications =>
6888                        New_Copy_List
6889                          (Parameter_Specifications (Parent (Anon_Id)))),
6890
6891                  Declarations               => Empty_List,
6892                  Handled_Statement_Sequence =>
6893                    Make_Handled_Sequence_Of_Statements (Loc,
6894                      Statements =>
6895                        New_List (Make_Raise_Program_Error (Loc))));
6896          else
6897             Act_Body :=
6898               Make_Subprogram_Body (Loc,
6899                 Specification =>
6900                   Make_Function_Specification (Loc,
6901                      Defining_Unit_Name         => New_Copy (Anon_Id),
6902                        Parameter_Specifications =>
6903                        New_Copy_List
6904                          (Parameter_Specifications (Parent (Anon_Id))),
6905                      Subtype_Mark =>
6906                        New_Occurrence_Of (Etype (Anon_Id), Loc)),
6907
6908                   Declarations               => Empty_List,
6909                   Handled_Statement_Sequence =>
6910                     Make_Handled_Sequence_Of_Statements (Loc,
6911                       Statements => New_List (
6912                         Make_Return_Statement (Loc,
6913                           Expression => Make_Raise_Program_Error (Loc)))));
6914          end if;
6915
6916          Pack_Body := Make_Package_Body (Loc,
6917            Defining_Unit_Name => New_Copy (Pack_Id),
6918            Declarations       => New_List (Act_Body));
6919
6920          Insert_After (Inst_Node, Pack_Body);
6921          Set_Corresponding_Spec (Pack_Body, Pack_Id);
6922          Analyze (Pack_Body);
6923       end if;
6924
6925       Expander_Mode_Restore;
6926    end Instantiate_Subprogram_Body;
6927
6928    ----------------------
6929    -- Instantiate_Type --
6930    ----------------------
6931
6932    function Instantiate_Type
6933      (Formal          : Node_Id;
6934       Actual          : Node_Id;
6935       Analyzed_Formal : Node_Id)
6936       return            Node_Id
6937    is
6938       Loc       : constant Source_Ptr := Sloc (Actual);
6939       Gen_T     : constant Entity_Id  := Defining_Identifier (Formal);
6940       A_Gen_T   : constant Entity_Id  := Defining_Identifier (Analyzed_Formal);
6941       Ancestor  : Entity_Id;
6942       Def       : constant Node_Id    := Formal_Type_Definition (Formal);
6943       Act_T     : Entity_Id;
6944       Decl_Node : Node_Id;
6945
6946       procedure Validate_Array_Type_Instance;
6947       procedure Validate_Access_Subprogram_Instance;
6948       procedure Validate_Access_Type_Instance;
6949       procedure Validate_Derived_Type_Instance;
6950       procedure Validate_Private_Type_Instance;
6951       --  These procedures perform validation tests for the named case
6952
6953       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean;
6954       --  Check that base types are the same and that the subtypes match
6955       --  statically. Used in several of the above.
6956
6957       --------------------
6958       -- Subtypes_Match --
6959       --------------------
6960
6961       function Subtypes_Match (Gen_T, Act_T : Entity_Id) return Boolean is
6962          T : constant Entity_Id := Get_Instance_Of (Gen_T);
6963
6964       begin
6965          return (Base_Type (T) = Base_Type (Act_T)
6966 --  why is the and then commented out here???
6967 --                  and then Is_Constrained (T) = Is_Constrained (Act_T)
6968                   and then Subtypes_Statically_Match (T, Act_T))
6969
6970            or else (Is_Class_Wide_Type (Gen_T)
6971                      and then Is_Class_Wide_Type (Act_T)
6972                      and then
6973                        Subtypes_Match (
6974                          Get_Instance_Of (Root_Type (Gen_T)),
6975                          Root_Type (Act_T)));
6976       end Subtypes_Match;
6977
6978       -----------------------------------------
6979       -- Validate_Access_Subprogram_Instance --
6980       -----------------------------------------
6981
6982       procedure Validate_Access_Subprogram_Instance is
6983       begin
6984          if not Is_Access_Type (Act_T)
6985            or else Ekind (Designated_Type (Act_T)) /= E_Subprogram_Type
6986          then
6987             Error_Msg_NE
6988               ("expect access type in instantiation of &", Actual, Gen_T);
6989             Abandon_Instantiation (Actual);
6990          end if;
6991
6992          Check_Mode_Conformant
6993            (Designated_Type (Act_T),
6994             Designated_Type (A_Gen_T),
6995             Actual,
6996             Get_Inst => True);
6997
6998          if Ekind (Base_Type (Act_T)) = E_Access_Protected_Subprogram_Type then
6999             if Ekind (A_Gen_T) = E_Access_Subprogram_Type then
7000                Error_Msg_NE
7001                  ("protected access type not allowed for formal &",
7002                   Actual, Gen_T);
7003             end if;
7004
7005          elsif Ekind (A_Gen_T) = E_Access_Protected_Subprogram_Type then
7006             Error_Msg_NE
7007               ("expect protected access type for formal &",
7008                Actual, Gen_T);
7009          end if;
7010       end Validate_Access_Subprogram_Instance;
7011
7012       -----------------------------------
7013       -- Validate_Access_Type_Instance --
7014       -----------------------------------
7015
7016       procedure Validate_Access_Type_Instance is
7017          Desig_Type : Entity_Id :=
7018            Find_Actual_Type (Designated_Type (A_Gen_T), Scope (A_Gen_T));
7019
7020       begin
7021          if not Is_Access_Type (Act_T) then
7022             Error_Msg_NE
7023               ("expect access type in instantiation of &", Actual, Gen_T);
7024             Abandon_Instantiation (Actual);
7025          end if;
7026
7027          if Is_Access_Constant (A_Gen_T) then
7028             if not Is_Access_Constant (Act_T) then
7029                Error_Msg_N
7030                  ("actual type must be access-to-constant type", Actual);
7031                Abandon_Instantiation (Actual);
7032             end if;
7033          else
7034             if Is_Access_Constant (Act_T) then
7035                Error_Msg_N
7036                  ("actual type must be access-to-variable type", Actual);
7037                Abandon_Instantiation (Actual);
7038
7039             elsif Ekind (A_Gen_T) = E_General_Access_Type
7040               and then Ekind (Base_Type (Act_T)) /= E_General_Access_Type
7041             then
7042                Error_Msg_N ("actual must be general access type!", Actual);
7043                Error_Msg_NE ("add ALL to }!", Actual, Act_T);
7044                Abandon_Instantiation (Actual);
7045             end if;
7046          end if;
7047
7048          --  The designated subtypes, that is to say the subtypes introduced
7049          --  by an access type declaration (and not by a subtype declaration)
7050          --  must match.
7051
7052          if not Subtypes_Match
7053            (Desig_Type, Designated_Type (Base_Type (Act_T)))
7054          then
7055             Error_Msg_NE
7056               ("designated type of actual does not match that of formal &",
7057                  Actual, Gen_T);
7058             Abandon_Instantiation (Actual);
7059
7060          elsif Is_Access_Type (Designated_Type (Act_T))
7061            and then Is_Constrained (Designated_Type (Designated_Type (Act_T)))
7062                       /=
7063                   Is_Constrained (Designated_Type (Desig_Type))
7064          then
7065             Error_Msg_NE
7066               ("designated type of actual does not match that of formal &",
7067                  Actual, Gen_T);
7068             Abandon_Instantiation (Actual);
7069          end if;
7070       end Validate_Access_Type_Instance;
7071
7072       ----------------------------------
7073       -- Validate_Array_Type_Instance --
7074       ----------------------------------
7075
7076       procedure Validate_Array_Type_Instance is
7077          I1 : Node_Id;
7078          I2 : Node_Id;
7079          T2 : Entity_Id;
7080
7081          function Formal_Dimensions return Int;
7082          --  Count number of dimensions in array type formal
7083
7084          function Formal_Dimensions return Int is
7085             Num   : Int := 0;
7086             Index : Node_Id;
7087
7088          begin
7089             if Nkind (Def) = N_Constrained_Array_Definition then
7090                Index := First (Discrete_Subtype_Definitions (Def));
7091             else
7092                Index := First (Subtype_Marks (Def));
7093             end if;
7094
7095             while Present (Index) loop
7096                Num := Num + 1;
7097                Next_Index (Index);
7098             end loop;
7099
7100             return Num;
7101          end Formal_Dimensions;
7102
7103       --  Start of processing for Validate_Array_Type_Instance
7104
7105       begin
7106          if not Is_Array_Type (Act_T) then
7107             Error_Msg_NE
7108               ("expect array type in instantiation of &", Actual, Gen_T);
7109             Abandon_Instantiation (Actual);
7110
7111          elsif Nkind (Def) = N_Constrained_Array_Definition then
7112             if not (Is_Constrained (Act_T)) then
7113                Error_Msg_NE
7114                  ("expect constrained array in instantiation of &",
7115                   Actual, Gen_T);
7116                Abandon_Instantiation (Actual);
7117             end if;
7118
7119          else
7120             if Is_Constrained (Act_T) then
7121                Error_Msg_NE
7122                  ("expect unconstrained array in instantiation of &",
7123                   Actual, Gen_T);
7124                Abandon_Instantiation (Actual);
7125             end if;
7126          end if;
7127
7128          if Formal_Dimensions /= Number_Dimensions (Act_T) then
7129             Error_Msg_NE
7130               ("dimensions of actual do not match formal &", Actual, Gen_T);
7131             Abandon_Instantiation (Actual);
7132          end if;
7133
7134          I1 := First_Index (A_Gen_T);
7135          I2 := First_Index (Act_T);
7136          for J in 1 .. Formal_Dimensions loop
7137
7138             --  If the indices of the actual were given by a subtype_mark,
7139             --  the index was transformed into a range attribute. Retrieve
7140             --  the original type mark for checking.
7141
7142             if Is_Entity_Name (Original_Node (I2)) then
7143                T2 := Entity (Original_Node (I2));
7144             else
7145                T2 := Etype (I2);
7146             end if;
7147
7148             if not Subtypes_Match
7149               (Find_Actual_Type (Etype (I1), Scope (A_Gen_T)), T2)
7150             then
7151                Error_Msg_NE
7152                  ("index types of actual do not match those of formal &",
7153                   Actual, Gen_T);
7154                Abandon_Instantiation (Actual);
7155             end if;
7156
7157             Next_Index (I1);
7158             Next_Index (I2);
7159          end loop;
7160
7161          if not Subtypes_Match (
7162             Find_Actual_Type (Component_Type (A_Gen_T), Scope (A_Gen_T)),
7163             Component_Type (Act_T))
7164          then
7165             Error_Msg_NE
7166               ("component subtype of actual does not match that of formal &",
7167                Actual, Gen_T);
7168             Abandon_Instantiation (Actual);
7169          end if;
7170
7171          if Has_Aliased_Components (A_Gen_T)
7172            and then not Has_Aliased_Components (Act_T)
7173          then
7174             Error_Msg_NE
7175               ("actual must have aliased components to match formal type &",
7176                Actual, Gen_T);
7177          end if;
7178
7179       end Validate_Array_Type_Instance;
7180
7181       ------------------------------------
7182       -- Validate_Derived_Type_Instance --
7183       ------------------------------------
7184
7185       procedure Validate_Derived_Type_Instance is
7186          Actual_Discr   : Entity_Id;
7187          Ancestor_Discr : Entity_Id;
7188
7189       begin
7190          --  If the parent type in the generic declaration is itself
7191          --  a previous formal type, then it is local to the generic
7192          --  and absent from the analyzed generic definition. In  that
7193          --  case the ancestor is the instance of the formal (which must
7194          --  have been instantiated previously). Otherwise, the analyzed
7195          --  generic carries the parent type. If the parent type is defined
7196          --  in a previous formal package, then the scope of that formal
7197          --  package is that of the generic type itself, and it has already
7198          --  been mapped into the corresponding type in the actual package.
7199
7200          --  Common case: parent type defined outside of the generic.
7201
7202          if Is_Entity_Name (Subtype_Mark (Def))
7203            and then Present (Entity (Subtype_Mark (Def)))
7204          then
7205             Ancestor := Get_Instance_Of (Entity (Subtype_Mark (Def)));
7206
7207          --  Check whether parent is defined in a previous formal package.
7208
7209          elsif
7210            Scope (Scope (Base_Type (Etype (A_Gen_T)))) = Scope (A_Gen_T)
7211          then
7212             Ancestor :=
7213               Get_Instance_Of (Base_Type (Etype (A_Gen_T)));
7214
7215          --  The type may be a local derivation, or a type extension of
7216          --  a previous formal, or of a formal of a parent package.
7217
7218          elsif Is_Derived_Type (Get_Instance_Of (A_Gen_T))
7219           or else
7220             Ekind (Get_Instance_Of (A_Gen_T)) = E_Record_Type_With_Private
7221          then
7222             Ancestor :=
7223               Get_Instance_Of (Base_Type (Get_Instance_Of (A_Gen_T)));
7224
7225          else
7226             Ancestor := Get_Instance_Of (Etype (Base_Type (A_Gen_T)));
7227          end if;
7228
7229          if not Is_Ancestor (Base_Type (Ancestor), Act_T) then
7230             Error_Msg_NE
7231               ("expect type derived from & in instantiation",
7232                Actual, First_Subtype (Ancestor));
7233             Abandon_Instantiation (Actual);
7234          end if;
7235
7236          --  Perform atomic/volatile checks (RM C.6(12))
7237
7238          if Is_Atomic (Act_T) and then not Is_Atomic (Ancestor) then
7239             Error_Msg_N
7240               ("cannot have atomic actual type for non-atomic formal type",
7241                Actual);
7242
7243          elsif Is_Volatile (Act_T)
7244            and then not Is_Volatile (Ancestor)
7245            and then Is_By_Reference_Type (Ancestor)
7246          then
7247             Error_Msg_N
7248               ("cannot have volatile actual type for non-volatile formal type",
7249                Actual);
7250          end if;
7251
7252          --  It should not be necessary to check for unknown discriminants
7253          --  on Formal, but for some reason Has_Unknown_Discriminants is
7254          --  false for A_Gen_T, so Is_Indefinite_Subtype incorrectly
7255          --  returns False. This needs fixing. ???
7256
7257          if not Is_Indefinite_Subtype (A_Gen_T)
7258            and then not Unknown_Discriminants_Present (Formal)
7259            and then Is_Indefinite_Subtype (Act_T)
7260          then
7261             Error_Msg_N
7262               ("actual subtype must be constrained", Actual);
7263             Abandon_Instantiation (Actual);
7264          end if;
7265
7266          if not Unknown_Discriminants_Present (Formal) then
7267             if Is_Constrained (Ancestor) then
7268                if not Is_Constrained (Act_T) then
7269                   Error_Msg_N
7270                     ("actual subtype must be constrained", Actual);
7271                   Abandon_Instantiation (Actual);
7272                end if;
7273
7274             --  Ancestor is unconstrained
7275
7276             elsif Is_Constrained (Act_T) then
7277                if Ekind (Ancestor) = E_Access_Type
7278                  or else Is_Composite_Type (Ancestor)
7279                then
7280                   Error_Msg_N
7281                     ("actual subtype must be unconstrained", Actual);
7282                   Abandon_Instantiation (Actual);
7283                end if;
7284
7285             --  A class-wide type is only allowed if the formal has
7286             --  unknown discriminants.
7287
7288             elsif Is_Class_Wide_Type (Act_T)
7289               and then not Has_Unknown_Discriminants (Ancestor)
7290             then
7291                Error_Msg_NE
7292                  ("actual for & cannot be a class-wide type", Actual, Gen_T);
7293                Abandon_Instantiation (Actual);
7294
7295             --  Otherwise, the formal and actual shall have the same
7296             --  number of discriminants and each discriminant of the
7297             --  actual must correspond to a discriminant of the formal.
7298
7299             elsif Has_Discriminants (Act_T)
7300               and then Has_Discriminants (Ancestor)
7301             then
7302                Actual_Discr   := First_Discriminant (Act_T);
7303                Ancestor_Discr := First_Discriminant (Ancestor);
7304                while Present (Actual_Discr)
7305                  and then Present (Ancestor_Discr)
7306                loop
7307                   if Base_Type (Act_T) /= Base_Type (Ancestor) and then
7308                     not Present (Corresponding_Discriminant (Actual_Discr))
7309                   then
7310                      Error_Msg_NE
7311                        ("discriminant & does not correspond " &
7312                         "to ancestor discriminant", Actual, Actual_Discr);
7313                      Abandon_Instantiation (Actual);
7314                   end if;
7315
7316                   Next_Discriminant (Actual_Discr);
7317                   Next_Discriminant (Ancestor_Discr);
7318                end loop;
7319
7320                if Present (Actual_Discr) or else Present (Ancestor_Discr) then
7321                   Error_Msg_NE
7322                     ("actual for & must have same number of discriminants",
7323                      Actual, Gen_T);
7324                   Abandon_Instantiation (Actual);
7325                end if;
7326
7327             --  This case should be caught by the earlier check for
7328             --  for constrainedness, but the check here is added for
7329             --  completeness.
7330
7331             elsif Has_Discriminants (Act_T) then
7332                Error_Msg_NE
7333                  ("actual for & must not have discriminants", Actual, Gen_T);
7334                Abandon_Instantiation (Actual);
7335
7336             elsif Has_Discriminants (Ancestor) then
7337                Error_Msg_NE
7338                  ("actual for & must have known discriminants", Actual, Gen_T);
7339                Abandon_Instantiation (Actual);
7340             end if;
7341
7342             if not Subtypes_Statically_Compatible (Act_T, Ancestor) then
7343                Error_Msg_N
7344                  ("constraint on actual is incompatible with formal", Actual);
7345                Abandon_Instantiation (Actual);
7346             end if;
7347          end if;
7348
7349       end Validate_Derived_Type_Instance;
7350
7351       ------------------------------------
7352       -- Validate_Private_Type_Instance --
7353       ------------------------------------
7354
7355       procedure Validate_Private_Type_Instance is
7356          Formal_Discr : Entity_Id;
7357          Actual_Discr : Entity_Id;
7358          Formal_Subt  : Entity_Id;
7359
7360       begin
7361          if (Is_Limited_Type (Act_T)
7362               or else Is_Limited_Composite (Act_T))
7363            and then not Is_Limited_Type (A_Gen_T)
7364          then
7365             Error_Msg_NE
7366               ("actual for non-limited  & cannot be a limited type", Actual,
7367                Gen_T);
7368             Abandon_Instantiation (Actual);
7369
7370          elsif Is_Indefinite_Subtype (Act_T)
7371             and then not Is_Indefinite_Subtype (A_Gen_T)
7372             and then Ada_95
7373          then
7374             Error_Msg_NE
7375               ("actual for & must be a definite subtype", Actual, Gen_T);
7376
7377          elsif not Is_Tagged_Type (Act_T)
7378            and then Is_Tagged_Type (A_Gen_T)
7379          then
7380             Error_Msg_NE
7381               ("actual for & must be a tagged type", Actual, Gen_T);
7382
7383          elsif Has_Discriminants (A_Gen_T) then
7384             if not Has_Discriminants (Act_T) then
7385                Error_Msg_NE
7386                  ("actual for & must have discriminants", Actual, Gen_T);
7387                Abandon_Instantiation (Actual);
7388
7389             elsif Is_Constrained (Act_T) then
7390                Error_Msg_NE
7391                  ("actual for & must be unconstrained", Actual, Gen_T);
7392                Abandon_Instantiation (Actual);
7393
7394             else
7395                Formal_Discr := First_Discriminant (A_Gen_T);
7396                Actual_Discr := First_Discriminant (Act_T);
7397                while Formal_Discr /= Empty loop
7398                   if Actual_Discr = Empty then
7399                      Error_Msg_NE
7400                        ("discriminants on actual do not match formal",
7401                         Actual, Gen_T);
7402                      Abandon_Instantiation (Actual);
7403                   end if;
7404
7405                   Formal_Subt := Get_Instance_Of (Etype (Formal_Discr));
7406
7407                   --  access discriminants match if designated types do.
7408
7409                   if Ekind (Base_Type (Formal_Subt)) = E_Anonymous_Access_Type
7410                     and then (Ekind (Base_Type (Etype (Actual_Discr))))
7411                       = E_Anonymous_Access_Type
7412                     and then Get_Instance_Of (
7413                       Designated_Type (Base_Type (Formal_Subt)))
7414                       = Designated_Type (Base_Type (Etype (Actual_Discr)))
7415                   then
7416                      null;
7417
7418                   elsif Base_Type (Formal_Subt) /=
7419                                        Base_Type (Etype (Actual_Discr))
7420                   then
7421                      Error_Msg_NE
7422                        ("types of actual discriminants must match formal",
7423                         Actual, Gen_T);
7424                      Abandon_Instantiation (Actual);
7425
7426                   elsif not Subtypes_Statically_Match
7427                               (Formal_Subt, Etype (Actual_Discr))
7428                     and then Ada_95
7429                   then
7430                      Error_Msg_NE
7431                        ("subtypes of actual discriminants must match formal",
7432                         Actual, Gen_T);
7433                      Abandon_Instantiation (Actual);
7434                   end if;
7435
7436                   Next_Discriminant (Formal_Discr);
7437                   Next_Discriminant (Actual_Discr);
7438                end loop;
7439
7440                if Actual_Discr /= Empty then
7441                   Error_Msg_NE
7442                     ("discriminants on actual do not match formal",
7443                      Actual, Gen_T);
7444                   Abandon_Instantiation (Actual);
7445                end if;
7446             end if;
7447
7448          end if;
7449
7450          Ancestor := Gen_T;
7451       end Validate_Private_Type_Instance;
7452
7453    --  Start of processing for Instantiate_Type
7454
7455    begin
7456       if Get_Instance_Of (A_Gen_T) /= A_Gen_T then
7457          Error_Msg_N ("duplicate instantiation of generic type", Actual);
7458          return Error;
7459
7460       elsif not Is_Entity_Name (Actual)
7461         or else not Is_Type (Entity (Actual))
7462       then
7463          Error_Msg_NE
7464            ("expect valid subtype mark to instantiate &", Actual, Gen_T);
7465          Abandon_Instantiation (Actual);
7466
7467       else
7468          Act_T := Entity (Actual);
7469
7470          if Ekind (Act_T) = E_Incomplete_Type then
7471             if No (Underlying_Type (Act_T)) then
7472                Error_Msg_N ("premature use of incomplete type", Actual);
7473                Abandon_Instantiation (Actual);
7474             else
7475                Act_T := Full_View (Act_T);
7476                Set_Entity (Actual, Act_T);
7477
7478                if Has_Private_Component (Act_T) then
7479                   Error_Msg_N
7480                     ("premature use of type with private component", Actual);
7481                end if;
7482             end if;
7483
7484          elsif Is_Private_Type (Act_T)
7485            and then Is_Private_Type (Base_Type (Act_T))
7486            and then not Is_Generic_Type (Act_T)
7487            and then not Is_Derived_Type (Act_T)
7488            and then No (Full_View (Root_Type (Act_T)))
7489          then
7490             Error_Msg_N ("premature use of private type", Actual);
7491
7492          elsif Has_Private_Component (Act_T) then
7493             Error_Msg_N
7494               ("premature use of type with private component", Actual);
7495          end if;
7496
7497          Set_Instance_Of (A_Gen_T, Act_T);
7498
7499          --  If the type is generic, the class-wide type may also be used
7500
7501          if Is_Tagged_Type (A_Gen_T)
7502            and then Is_Tagged_Type (Act_T)
7503            and then not Is_Class_Wide_Type (A_Gen_T)
7504          then
7505             Set_Instance_Of (Class_Wide_Type (A_Gen_T),
7506               Class_Wide_Type (Act_T));
7507          end if;
7508
7509          if not Is_Abstract (A_Gen_T)
7510            and then Is_Abstract (Act_T)
7511          then
7512             Error_Msg_N
7513               ("actual of non-abstract formal cannot be abstract", Actual);
7514          end if;
7515
7516          if Is_Scalar_Type (Gen_T) then
7517             Set_Instance_Of (Etype (A_Gen_T), Etype (Act_T));
7518          end if;
7519       end if;
7520
7521       case Nkind (Def) is
7522          when N_Formal_Private_Type_Definition =>
7523             Validate_Private_Type_Instance;
7524
7525          when N_Formal_Derived_Type_Definition =>
7526             Validate_Derived_Type_Instance;
7527
7528          when N_Formal_Discrete_Type_Definition =>
7529             if not Is_Discrete_Type (Act_T) then
7530                Error_Msg_NE
7531                  ("expect discrete type in instantiation of&", Actual, Gen_T);
7532                Abandon_Instantiation (Actual);
7533             end if;
7534
7535          when N_Formal_Signed_Integer_Type_Definition =>
7536             if not Is_Signed_Integer_Type (Act_T) then
7537                Error_Msg_NE
7538                  ("expect signed integer type in instantiation of&",
7539                   Actual, Gen_T);
7540                Abandon_Instantiation (Actual);
7541             end if;
7542
7543          when N_Formal_Modular_Type_Definition =>
7544             if not Is_Modular_Integer_Type (Act_T) then
7545                Error_Msg_NE
7546                  ("expect modular type in instantiation of &", Actual, Gen_T);
7547                Abandon_Instantiation (Actual);
7548             end if;
7549
7550          when N_Formal_Floating_Point_Definition =>
7551             if not Is_Floating_Point_Type (Act_T) then
7552                Error_Msg_NE
7553                  ("expect float type in instantiation of &", Actual, Gen_T);
7554                Abandon_Instantiation (Actual);
7555             end if;
7556
7557          when N_Formal_Ordinary_Fixed_Point_Definition =>
7558             if not Is_Ordinary_Fixed_Point_Type (Act_T) then
7559                Error_Msg_NE
7560                  ("expect ordinary fixed point type in instantiation of &",
7561                   Actual, Gen_T);
7562                Abandon_Instantiation (Actual);
7563             end if;
7564
7565          when N_Formal_Decimal_Fixed_Point_Definition =>
7566             if not Is_Decimal_Fixed_Point_Type (Act_T) then
7567                Error_Msg_NE
7568                  ("expect decimal type in instantiation of &",
7569                   Actual, Gen_T);
7570                Abandon_Instantiation (Actual);
7571             end if;
7572
7573          when N_Array_Type_Definition =>
7574             Validate_Array_Type_Instance;
7575
7576          when N_Access_To_Object_Definition =>
7577             Validate_Access_Type_Instance;
7578
7579          when N_Access_Function_Definition |
7580               N_Access_Procedure_Definition =>
7581             Validate_Access_Subprogram_Instance;
7582
7583          when others =>
7584             raise Program_Error;
7585
7586       end case;
7587
7588       Decl_Node :=
7589         Make_Subtype_Declaration (Loc,
7590           Defining_Identifier => New_Copy (Gen_T),
7591           Subtype_Indication  => New_Reference_To (Act_T, Loc));
7592
7593       if Is_Private_Type (Act_T) then
7594          Set_Has_Private_View (Subtype_Indication (Decl_Node));
7595       end if;
7596
7597       --  Flag actual derived types so their elaboration produces the
7598       --  appropriate renamings for the primitive operations of the ancestor.
7599       --  Flag actual for formal private types as well, to determine whether
7600       --  operations in the private part may override inherited operations.
7601
7602       if Nkind (Def) = N_Formal_Derived_Type_Definition
7603         or else Nkind (Def) = N_Formal_Private_Type_Definition
7604       then
7605          Set_Generic_Parent_Type (Decl_Node, Ancestor);
7606       end if;
7607
7608       return Decl_Node;
7609    end Instantiate_Type;
7610
7611    ---------------------
7612    -- Is_In_Main_Unit --
7613    ---------------------
7614
7615    function Is_In_Main_Unit (N : Node_Id) return Boolean is
7616       Unum : constant Unit_Number_Type := Get_Source_Unit (N);
7617
7618       Current_Unit : Node_Id;
7619
7620    begin
7621       if Unum = Main_Unit then
7622          return True;
7623
7624       --  If the current unit is a subunit then it is either the main unit
7625       --  or is being compiled as part of the main unit.
7626
7627       elsif Nkind (N) = N_Compilation_Unit then
7628          return Nkind (Unit (N)) = N_Subunit;
7629       end if;
7630
7631       Current_Unit := Parent (N);
7632       while Present (Current_Unit)
7633         and then Nkind (Current_Unit) /= N_Compilation_Unit
7634       loop
7635          Current_Unit := Parent (Current_Unit);
7636       end loop;
7637
7638       --  The instantiation node is in the main unit, or else the current
7639       --  node (perhaps as the result of nested instantiations) is in the
7640       --  main unit, or in the declaration of the main unit, which in this
7641       --  last case must be a body.
7642
7643       return Unum = Main_Unit
7644         or else Current_Unit = Cunit (Main_Unit)
7645         or else Current_Unit = Library_Unit (Cunit (Main_Unit))
7646         or else (Present (Library_Unit (Current_Unit))
7647                   and then Is_In_Main_Unit (Library_Unit (Current_Unit)));
7648    end Is_In_Main_Unit;
7649
7650    ----------------------------
7651    -- Load_Parent_Of_Generic --
7652    ----------------------------
7653
7654    procedure Load_Parent_Of_Generic (N : Node_Id; Spec : Node_Id) is
7655       Comp_Unit        : constant Node_Id := Cunit (Get_Source_Unit (Spec));
7656       True_Parent      : Node_Id;
7657       Inst_Node        : Node_Id;
7658       OK               : Boolean;
7659       Save_Style_Check : Boolean := Style_Check;
7660
7661    begin
7662       if not In_Same_Source_Unit (N, Spec)
7663         or else Nkind (Unit (Comp_Unit)) = N_Package_Declaration
7664         or else (Nkind (Unit (Comp_Unit)) = N_Package_Body
7665                    and then not Is_In_Main_Unit (Spec))
7666       then
7667          --  Find body of parent of spec, and analyze it. A special case
7668          --  arises when the parent is an instantiation, that is to say when
7669          --  we are currently instantiating a nested generic. In that case,
7670          --  there is no separate file for the body of the enclosing instance.
7671          --  Instead, the enclosing body must be instantiated as if it were
7672          --  a pending instantiation, in order to produce the body for the
7673          --  nested generic we require now. Note that in that case the
7674          --  generic may be defined in a package body, the instance defined
7675          --  in the same package body, and the original enclosing body may not
7676          --  be in the main unit.
7677
7678          True_Parent := Parent (Spec);
7679          Inst_Node   := Empty;
7680
7681          while Present (True_Parent)
7682            and then Nkind (True_Parent) /= N_Compilation_Unit
7683          loop
7684             if Nkind (True_Parent) = N_Package_Declaration
7685               and then
7686                 Nkind (Original_Node (True_Parent)) = N_Package_Instantiation
7687             then
7688                --  Parent is a compilation unit that is an instantiation.
7689                --  Instantiation node has been replaced with package decl.
7690
7691                Inst_Node := Original_Node (True_Parent);
7692                exit;
7693
7694             elsif Nkind (True_Parent) = N_Package_Declaration
7695               and then Present (Generic_Parent (Specification (True_Parent)))
7696             then
7697                --  Parent is an instantiation within another specification.
7698                --  Declaration for instance has been inserted before original
7699                --  instantiation node. A direct link would be preferable?
7700
7701                Inst_Node := Next (True_Parent);
7702
7703                while Present (Inst_Node)
7704                  and then Nkind (Inst_Node) /= N_Package_Instantiation
7705                loop
7706                   Next (Inst_Node);
7707                end loop;
7708
7709                --  If the instance appears within a generic, and the generic
7710                --  unit is defined within a formal package of the enclosing
7711                --  generic, there is no generic body available, and none
7712                --  needed. A more precise test should be used ???
7713
7714                if No (Inst_Node) then
7715                   return;
7716                end if;
7717
7718                exit;
7719             else
7720                True_Parent := Parent (True_Parent);
7721             end if;
7722          end loop;
7723
7724          if Present (Inst_Node) then
7725
7726             if Nkind (Parent (True_Parent)) = N_Compilation_Unit then
7727
7728                --  Instantiation node and declaration of instantiated package
7729                --  were exchanged when only the declaration was needed.
7730                --  Restore instantiation node before proceeding with body.
7731
7732                Set_Unit (Parent (True_Parent), Inst_Node);
7733             end if;
7734
7735             --  Now complete instantiation of enclosing body, if it appears
7736             --  in some other unit. If it appears in the current unit, the
7737             --  body will have been instantiated already.
7738
7739             if No (Corresponding_Body (Instance_Spec (Inst_Node))) then
7740                Instantiate_Package_Body
7741                  (Pending_Body_Info'(
7742                     Inst_Node, True_Parent, Expander_Active,
7743                       Get_Code_Unit (Sloc (Inst_Node))));
7744             end if;
7745
7746          else
7747             Opt.Style_Check := False;
7748             Load_Needed_Body (Comp_Unit, OK);
7749             Opt.Style_Check := Save_Style_Check;
7750
7751             if not OK
7752               and then Unit_Requires_Body (Defining_Entity (Spec))
7753             then
7754                declare
7755                   Bname : constant Unit_Name_Type :=
7756                             Get_Body_Name (Get_Unit_Name (Unit (Comp_Unit)));
7757
7758                begin
7759                   Error_Msg_Unit_1 := Bname;
7760                   Error_Msg_N ("this instantiation requires$!", N);
7761                   Error_Msg_Name_1 :=
7762                     Get_File_Name (Bname, Subunit => False);
7763                   Error_Msg_N ("\but file{ was not found!", N);
7764                   raise Unrecoverable_Error;
7765                end;
7766             end if;
7767          end if;
7768       end if;
7769
7770       --  If loading the parent of the generic caused an instantiation
7771       --  circularity, we abandon compilation at this point, because
7772       --  otherwise in some cases we get into trouble with infinite
7773       --  recursions after this point.
7774
7775       if Circularity_Detected then
7776          raise Unrecoverable_Error;
7777       end if;
7778
7779    end Load_Parent_Of_Generic;
7780
7781    -----------------------
7782    -- Move_Freeze_Nodes --
7783    -----------------------
7784
7785    procedure Move_Freeze_Nodes
7786      (Out_Of : Entity_Id;
7787       After  : Node_Id;
7788       L      : List_Id)
7789    is
7790       Decl      : Node_Id;
7791       Next_Decl : Node_Id;
7792       Next_Node : Node_Id := After;
7793       Spec      : Node_Id;
7794
7795       function Is_Outer_Type (T : Entity_Id) return Boolean;
7796       --  Check whether entity is declared in a scope external to that
7797       --  of the generic unit.
7798
7799       -------------------
7800       -- Is_Outer_Type --
7801       -------------------
7802
7803       function Is_Outer_Type (T : Entity_Id) return Boolean is
7804          Scop : Entity_Id := Scope (T);
7805
7806       begin
7807          if Scope_Depth (Scop) < Scope_Depth (Out_Of) then
7808             return True;
7809
7810          else
7811             while Scop /= Standard_Standard loop
7812
7813                if Scop = Out_Of then
7814                   return False;
7815                else
7816                   Scop := Scope (Scop);
7817                end if;
7818             end loop;
7819
7820             return True;
7821          end if;
7822       end Is_Outer_Type;
7823
7824    --  Start of processing for Move_Freeze_Nodes
7825
7826    begin
7827       if No (L) then
7828          return;
7829       end if;
7830
7831       --  First remove the freeze nodes that may appear before all other
7832       --  declarations.
7833
7834       Decl := First (L);
7835       while Present (Decl)
7836         and then Nkind (Decl) = N_Freeze_Entity
7837         and then Is_Outer_Type (Entity (Decl))
7838       loop
7839          Decl := Remove_Head (L);
7840          Insert_After (Next_Node, Decl);
7841          Set_Analyzed (Decl, False);
7842          Next_Node := Decl;
7843          Decl := First (L);
7844       end loop;
7845
7846       --  Next scan the list of declarations and remove each freeze node that
7847       --  appears ahead of the current node.
7848
7849       while Present (Decl) loop
7850          while Present (Next (Decl))
7851            and then Nkind (Next (Decl)) = N_Freeze_Entity
7852            and then Is_Outer_Type (Entity (Next (Decl)))
7853          loop
7854             Next_Decl := Remove_Next (Decl);
7855             Insert_After (Next_Node, Next_Decl);
7856             Set_Analyzed (Next_Decl, False);
7857             Next_Node := Next_Decl;
7858          end loop;
7859
7860          --  If the declaration is a nested package or concurrent type, then
7861          --  recurse. Nested generic packages will have been processed from the
7862          --  inside out.
7863
7864          if Nkind (Decl) = N_Package_Declaration then
7865             Spec := Specification (Decl);
7866
7867          elsif Nkind (Decl) = N_Task_Type_Declaration then
7868             Spec := Task_Definition (Decl);
7869
7870          elsif Nkind (Decl) = N_Protected_Type_Declaration then
7871             Spec := Protected_Definition (Decl);
7872
7873          else
7874             Spec := Empty;
7875          end if;
7876
7877          if Present (Spec) then
7878             Move_Freeze_Nodes (Out_Of, Next_Node,
7879               Visible_Declarations (Spec));
7880             Move_Freeze_Nodes (Out_Of, Next_Node,
7881               Private_Declarations (Spec));
7882          end if;
7883
7884          Next (Decl);
7885       end loop;
7886    end Move_Freeze_Nodes;
7887
7888    ----------------
7889    -- Next_Assoc --
7890    ----------------
7891
7892    function Next_Assoc (E : Assoc_Ptr) return Assoc_Ptr is
7893    begin
7894       return Generic_Renamings.Table (E).Next_In_HTable;
7895    end Next_Assoc;
7896
7897    ------------------------
7898    -- Preanalyze_Actuals --
7899    ------------------------
7900
7901    procedure Pre_Analyze_Actuals (N : Node_Id) is
7902       Assoc : Node_Id;
7903       Act   : Node_Id;
7904       Errs  : Int := Errors_Detected;
7905
7906    begin
7907       Assoc := First (Generic_Associations (N));
7908
7909       while Present (Assoc) loop
7910          Act := Explicit_Generic_Actual_Parameter (Assoc);
7911
7912          --  Within a nested instantiation, a defaulted actual is an
7913          --  empty association, so nothing to analyze. If the actual for
7914          --  a subprogram is an attribute, analyze prefix only, because
7915          --  actual is not a complete attribute reference.
7916          --  String literals may be operators, but at this point we do not
7917          --  know whether the actual is a formal subprogram or a string.
7918
7919          if No (Act) then
7920             null;
7921
7922          elsif Nkind (Act) = N_Attribute_Reference then
7923             Analyze (Prefix (Act));
7924
7925          elsif Nkind (Act) = N_Explicit_Dereference then
7926             Analyze (Prefix (Act));
7927
7928          elsif Nkind (Act) /= N_Operator_Symbol then
7929             Analyze (Act);
7930          end if;
7931
7932          if Errs /= Errors_Detected then
7933             Abandon_Instantiation (Act);
7934          end if;
7935
7936          Next (Assoc);
7937       end loop;
7938    end Pre_Analyze_Actuals;
7939
7940    -------------------
7941    -- Remove_Parent --
7942    -------------------
7943
7944    procedure Remove_Parent (In_Body : Boolean := False) is
7945       S      : Entity_Id := Current_Scope;
7946       E      : Entity_Id;
7947       P      : Entity_Id;
7948       Hidden : Elmt_Id;
7949
7950    begin
7951       --  After child instantiation is complete, remove from scope stack
7952       --  the extra copy of the current scope, and then remove parent
7953       --  instances.
7954
7955       if not In_Body then
7956          Pop_Scope;
7957
7958          while Current_Scope /= S loop
7959             P := Current_Scope;
7960             End_Package_Scope (Current_Scope);
7961
7962             if In_Open_Scopes (P) then
7963                E := First_Entity (P);
7964
7965                while Present (E) loop
7966                   Set_Is_Immediately_Visible (E, True);
7967                   Next_Entity (E);
7968                end loop;
7969
7970             elsif not In_Open_Scopes (Scope (P)) then
7971                Set_Is_Immediately_Visible (P, False);
7972             end if;
7973          end loop;
7974
7975          --  Reset visibility of entities in the enclosing scope.
7976
7977          Set_Is_Hidden_Open_Scope (Current_Scope, False);
7978          Hidden := First_Elmt (Hidden_Entities);
7979
7980          while Present (Hidden) loop
7981             Set_Is_Immediately_Visible (Node (Hidden), True);
7982             Next_Elmt (Hidden);
7983          end loop;
7984
7985       else
7986          --  Each body is analyzed separately, and there is no context
7987          --  that needs preserving from one body instance to the next,
7988          --  so remove all parent scopes that have been installed.
7989
7990          while Present (S) loop
7991             End_Package_Scope (S);
7992             S := Current_Scope;
7993             exit when S = Standard_Standard;
7994          end loop;
7995       end if;
7996
7997    end Remove_Parent;
7998
7999    -----------------
8000    -- Restore_Env --
8001    -----------------
8002
8003    procedure Restore_Env is
8004       Saved : Instance_Env renames Instance_Envs.Table (Instance_Envs.Last);
8005
8006    begin
8007       Ada_83                       := Saved.Ada_83;
8008
8009       if No (Current_Instantiated_Parent.Act_Id) then
8010
8011          --  Restore environment after subprogram inlining
8012
8013          Restore_Private_Views (Empty);
8014       end if;
8015
8016       Current_Instantiated_Parent  := Saved.Instantiated_Parent;
8017       Exchanged_Views              := Saved.Exchanged_Views;
8018       Hidden_Entities              := Saved.Hidden_Entities;
8019       Current_Sem_Unit             := Saved.Current_Sem_Unit;
8020
8021       Instance_Envs.Decrement_Last;
8022    end Restore_Env;
8023
8024    ---------------------------
8025    -- Restore_Private_Views --
8026    ---------------------------
8027
8028    procedure Restore_Private_Views
8029      (Pack_Id    : Entity_Id;
8030       Is_Package : Boolean := True)
8031    is
8032       M        : Elmt_Id;
8033       E        : Entity_Id;
8034       Typ      : Entity_Id;
8035       Dep_Elmt : Elmt_Id;
8036       Dep_Typ  : Node_Id;
8037
8038    begin
8039       M := First_Elmt (Exchanged_Views);
8040       while Present (M) loop
8041          Typ := Node (M);
8042
8043          --  Subtypes of types whose views have been exchanged, and that
8044          --  are defined within the instance, were not on the list of
8045          --  Private_Dependents on entry to the instance, so they have to
8046          --  be exchanged explicitly now, in order to remain consistent with
8047          --  the view of the parent type.
8048
8049          if Ekind (Typ) = E_Private_Type
8050            or else Ekind (Typ) = E_Limited_Private_Type
8051            or else Ekind (Typ) = E_Record_Type_With_Private
8052          then
8053             Dep_Elmt := First_Elmt (Private_Dependents (Typ));
8054
8055             while Present (Dep_Elmt) loop
8056                Dep_Typ := Node (Dep_Elmt);
8057
8058                if Scope (Dep_Typ) = Pack_Id
8059                  and then Present (Full_View (Dep_Typ))
8060                then
8061                   Replace_Elmt (Dep_Elmt, Full_View (Dep_Typ));
8062                   Exchange_Declarations (Dep_Typ);
8063                end if;
8064
8065                Next_Elmt (Dep_Elmt);
8066             end loop;
8067          end if;
8068
8069          Exchange_Declarations (Node (M));
8070          Next_Elmt (M);
8071       end loop;
8072
8073       if No (Pack_Id) then
8074          return;
8075       end if;
8076
8077       --  Make the generic formal parameters private, and make the formal
8078       --  types into subtypes of the actuals again.
8079
8080       E := First_Entity (Pack_Id);
8081
8082       while Present (E) loop
8083          Set_Is_Hidden (E, True);
8084
8085          if Is_Type (E)
8086            and then Nkind (Parent (E)) = N_Subtype_Declaration
8087          then
8088             Set_Is_Generic_Actual_Type (E, False);
8089
8090             --  An unusual case of aliasing: the actual may also be directly
8091             --  visible in the generic, and be private there, while it is
8092             --  fully visible in the context of the instance. The internal
8093             --  subtype is private in the instance, but has full visibility
8094             --  like its parent in the enclosing scope. This enforces the
8095             --  invariant that the privacy status of all private dependents of
8096             --  a type coincide with that of the parent type. This can only
8097             --  happen when a generic child unit is instantiated within a
8098             --  sibling.
8099
8100             if Is_Private_Type (E)
8101               and then not Is_Private_Type (Etype (E))
8102             then
8103                Exchange_Declarations (E);
8104             end if;
8105
8106          elsif Ekind (E) = E_Package then
8107
8108             --  The end of the renaming list is the renaming of the generic
8109             --  package itself. If the instance is a subprogram, all entities
8110             --  in the corresponding package are renamings. If this entity is
8111             --  a formal package, make its own formals private as well. The
8112             --  actual in this case is itself the renaming of an instantiation.
8113             --  If the entity is not a package renaming, it is the entity
8114             --  created to validate formal package actuals: ignore.
8115
8116             --  If the actual is itself a formal package for the enclosing
8117             --  generic, or the actual for such a formal package, it remains
8118             --  visible after the current instance, and therefore nothing
8119             --  needs to be done either, except to keep it accessible.
8120
8121             if Is_Package
8122               and then Renamed_Object (E) = Pack_Id
8123             then
8124                exit;
8125
8126             elsif Nkind (Parent (E)) /= N_Package_Renaming_Declaration then
8127                null;
8128
8129             elsif Denotes_Formal_Package (Renamed_Object (E)) then
8130                Set_Is_Hidden (E, False);
8131
8132             else
8133                declare
8134                   Act_P : Entity_Id := Renamed_Object (E);
8135                   Id    : Entity_Id := First_Entity (Act_P);
8136
8137                begin
8138                   while Present (Id)
8139                     and then Id /= First_Private_Entity (Act_P)
8140                   loop
8141                      Set_Is_Hidden (Id, True);
8142                      Set_Is_Potentially_Use_Visible (Id, In_Use (Act_P));
8143                      exit when Ekind (Id) = E_Package
8144                                  and then Renamed_Object (Id) = Act_P;
8145
8146                      Next_Entity (Id);
8147                   end loop;
8148                end;
8149                null;
8150             end if;
8151          end if;
8152
8153          Next_Entity (E);
8154       end loop;
8155    end Restore_Private_Views;
8156
8157    --------------
8158    -- Save_Env --
8159    --------------
8160
8161    procedure Save_Env
8162      (Gen_Unit : Entity_Id;
8163       Act_Unit : Entity_Id)
8164    is
8165       Saved : Instance_Env;
8166
8167    begin
8168       Saved.Ada_83              := Ada_83;
8169       Saved.Instantiated_Parent := Current_Instantiated_Parent;
8170       Saved.Exchanged_Views     := Exchanged_Views;
8171       Saved.Hidden_Entities     := Hidden_Entities;
8172       Saved.Current_Sem_Unit    := Current_Sem_Unit;
8173       Instance_Envs.Increment_Last;
8174       Instance_Envs.Table (Instance_Envs.Last) := Saved;
8175
8176       --  Regardless of the current mode, predefined units are analyzed in
8177       --  Ada95 mode, and Ada83 checks don't apply.
8178
8179       if Is_Internal_File_Name
8180           (Fname => Unit_File_Name (Get_Source_Unit (Gen_Unit)),
8181            Renamings_Included => True) then
8182          Ada_83 := False;
8183       end if;
8184
8185       Current_Instantiated_Parent := (Gen_Unit, Act_Unit, Assoc_Null);
8186       Exchanged_Views := New_Elmt_List;
8187       Hidden_Entities := New_Elmt_List;
8188    end Save_Env;
8189
8190    ----------------------------
8191    -- Save_Global_References --
8192    ----------------------------
8193
8194    procedure Save_Global_References (N : Node_Id) is
8195       Gen_Scope : Entity_Id;
8196       E         : Entity_Id;
8197       N2        : Node_Id;
8198
8199       function Is_Global (E : Entity_Id) return Boolean;
8200       --  Check whether entity is defined outside of generic unit.
8201       --  Examine the scope of an entity, and the scope of the scope,
8202       --  etc, until we find either Standard, in which case the entity
8203       --  is global, or the generic unit itself, which indicates that
8204       --  the entity is local. If the entity is the generic unit itself,
8205       --  as in the case of a recursive call, or the enclosing generic unit,
8206       --  if different from the current scope, then it is local as well,
8207       --  because it will be replaced at the point of instantiation. On
8208       --  the other hand, if it is a reference to a child unit of a common
8209       --  ancestor, which appears in an instantiation, it is global because
8210       --  it is used to denote a specific compilation unit at the time the
8211       --  instantiations will be analyzed.
8212
8213       procedure Reset_Entity (N : Node_Id);
8214       --  Save semantic information on global entity, so that it is not
8215       --  resolved again at instantiation time.
8216
8217       procedure Save_Entity_Descendants (N : Node_Id);
8218       --  Apply Save_Global_References to the two syntactic descendants of
8219       --  non-terminal nodes that carry an Associated_Node and are processed
8220       --  through Reset_Entity. Once the global entity (if any) has been
8221       --  captured together with its type, only two syntactic descendants
8222       --  need to be traversed to complete the processing of the tree rooted
8223       --  at N. This applies to Selected_Components, Expanded_Names, and to
8224       --  Operator nodes. N can also be a character literal, identifier, or
8225       --  operator symbol node, but the call has no effect in these cases.
8226
8227       procedure Save_Global_Defaults (N1, N2 : Node_Id);
8228       --  Default actuals in nested instances must be handled specially
8229       --  because there is no link to them from the original tree. When an
8230       --  actual subprogram is given by a default, we add an explicit generic
8231       --  association for it in the instantiation node. When we save the
8232       --  global references on the name of the instance, we recover the list
8233       --  of generic associations, and add an explicit one to the original
8234       --  generic tree, through which a global actual can be preserved.
8235       --  Similarly, if a child unit is instantiated within a sibling, in the
8236       --  context of the parent, we must preserve the identifier of the parent
8237       --  so that it can be properly resolved in a subsequent instantiation.
8238
8239       procedure Save_Global_Descendant (D : Union_Id);
8240       --  Apply Save_Global_References recursively to the descendents of
8241       --  current node.
8242
8243       procedure Save_References (N : Node_Id);
8244       --  This is the recursive procedure that does the work, once the
8245       --  enclosing generic scope has been established.
8246
8247       ---------------
8248       -- Is_Global --
8249       ---------------
8250
8251       function Is_Global (E : Entity_Id) return Boolean is
8252          Se  : Entity_Id := Scope (E);
8253
8254          function Is_Instance_Node (Decl : Node_Id) return Boolean;
8255          --  Determine whether the parent node of a reference to a child unit
8256          --  denotes an instantiation or a formal package, in which case the
8257          --  reference to the child unit is global, even if it appears within
8258          --  the current scope (e.g. when the instance appears within the body
8259          --  of an ancestor).
8260
8261          function Is_Instance_Node (Decl : Node_Id) return Boolean is
8262          begin
8263             return (Nkind (Decl) in N_Generic_Instantiation
8264               or else
8265                 Nkind (Original_Node (Decl)) = N_Formal_Package_Declaration);
8266          end Is_Instance_Node;
8267
8268       --  Start of processing for Is_Global
8269
8270       begin
8271          if E = Gen_Scope then
8272             return False;
8273
8274          elsif E = Standard_Standard then
8275             return True;
8276
8277          elsif Is_Child_Unit (E)
8278            and then (Is_Instance_Node (Parent (N2))
8279              or else (Nkind (Parent (N2)) = N_Expanded_Name
8280                        and then N2 = Selector_Name (Parent (N2))
8281                        and then Is_Instance_Node (Parent (Parent (N2)))))
8282          then
8283             return True;
8284
8285          else
8286             while Se /= Gen_Scope loop
8287                if Se = Standard_Standard then
8288                   return True;
8289                else
8290                   Se := Scope (Se);
8291                end if;
8292             end loop;
8293
8294             return False;
8295          end if;
8296       end Is_Global;
8297
8298       ------------------
8299       -- Reset_Entity --
8300       ------------------
8301
8302       procedure Reset_Entity (N : Node_Id) is
8303
8304          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id);
8305          --  The type of N2 is global to the generic unit. Save the
8306          --  type in the generic node.
8307
8308          ---------------------
8309          -- Set_Global_Type --
8310          ---------------------
8311
8312          procedure Set_Global_Type (N : Node_Id; N2 : Node_Id) is
8313             Typ : constant Entity_Id := Etype (N2);
8314
8315          begin
8316             Set_Etype (N, Typ);
8317
8318             if Entity (N) /= N2
8319               and then Has_Private_View (Entity (N))
8320             then
8321                --  If the entity of N is not the associated node, this is
8322                --  a nested generic and it has an associated node as well,
8323                --  whose type is already the full view (see below). Indicate
8324                --  that the original node has a private view.
8325
8326                Set_Has_Private_View (N);
8327             end if;
8328
8329             --  If not a private type, nothing else to do
8330
8331             if not Is_Private_Type (Typ) then
8332                if Is_Array_Type (Typ)
8333                  and then Is_Private_Type (Component_Type (Typ))
8334                then
8335                   Set_Has_Private_View (N);
8336                end if;
8337
8338             --  If it is a derivation of a private type in a context where
8339             --  no full view is needed, nothing to do either.
8340
8341             elsif No (Full_View (Typ)) and then Typ /= Etype (Typ) then
8342                null;
8343
8344             --  Otherwise mark the type for flipping and use the full_view
8345             --  when available.
8346
8347             else
8348                Set_Has_Private_View (N);
8349
8350                if Present (Full_View (Typ)) then
8351                   Set_Etype (N2, Full_View (Typ));
8352                end if;
8353             end if;
8354          end Set_Global_Type;
8355
8356       --  Start of processing for Reset_Entity
8357
8358       begin
8359          N2 := Get_Associated_Node (N);
8360          E := Entity (N2);
8361
8362          if Present (E) then
8363             if Is_Global (E) then
8364                Set_Global_Type (N, N2);
8365
8366             elsif Nkind (N) = N_Op_Concat
8367               and then Is_Generic_Type (Etype (N2))
8368               and then
8369                (Base_Type (Etype (Right_Opnd (N2))) = Etype (N2)
8370                   or else Base_Type (Etype (Left_Opnd (N2))) = Etype (N2))
8371               and then Is_Intrinsic_Subprogram (E)
8372             then
8373                null;
8374
8375             else
8376                --  Entity is local. Mark generic node as unresolved.
8377                --  Note that now it does not have an entity.
8378
8379                Set_Associated_Node (N, Empty);
8380                Set_Etype  (N, Empty);
8381             end if;
8382
8383             if (Nkind (Parent (N)) = N_Package_Instantiation
8384                  or else Nkind (Parent (N)) = N_Function_Instantiation
8385                  or else Nkind (Parent (N)) = N_Procedure_Instantiation)
8386               and then N = Name (Parent (N))
8387             then
8388                Save_Global_Defaults (Parent (N), Parent (N2));
8389             end if;
8390
8391          elsif Nkind (Parent (N)) = N_Selected_Component
8392            and then Nkind (Parent (N2)) = N_Expanded_Name
8393          then
8394
8395             if Is_Global (Entity (Parent (N2))) then
8396                Change_Selected_Component_To_Expanded_Name (Parent (N));
8397                Set_Associated_Node (Parent (N), Parent (N2));
8398                Set_Global_Type (Parent (N), Parent (N2));
8399                Save_Entity_Descendants (N);
8400
8401                --  If this is a reference to the current generic entity,
8402                --  replace it with a simple name. This is to avoid anomalies
8403                --  when the enclosing scope is also a generic unit, in which
8404                --  case the selected component will not resolve to the current
8405                --  unit within an instance of the outer one. Ditto if the
8406                --  entity is an enclosing scope, e.g. a parent unit.
8407
8408             elsif In_Open_Scopes (Entity (Parent (N2)))
8409               and then not Is_Generic_Unit (Entity (Prefix (Parent (N2))))
8410             then
8411                Rewrite (Parent (N),
8412                  Make_Identifier (Sloc (N),
8413                    Chars => Chars (Selector_Name (Parent (N2)))));
8414             end if;
8415
8416             if (Nkind (Parent (Parent (N))) = N_Package_Instantiation
8417                  or else Nkind (Parent (Parent (N)))
8418                    = N_Function_Instantiation
8419                  or else Nkind (Parent (Parent (N)))
8420                    = N_Procedure_Instantiation)
8421               and then Parent (N) = Name (Parent (Parent (N)))
8422             then
8423                Save_Global_Defaults
8424                  (Parent (Parent (N)), Parent (Parent ((N2))));
8425             end if;
8426
8427          --  A selected component may denote a static constant that has
8428          --  been folded. Make the same replacement in original tree.
8429
8430          elsif Nkind (Parent (N)) = N_Selected_Component
8431            and then (Nkind (Parent (N2)) = N_Integer_Literal
8432                       or else Nkind (Parent (N2)) = N_Real_Literal)
8433          then
8434             Rewrite (Parent (N),
8435               New_Copy (Parent (N2)));
8436             Set_Analyzed (Parent (N), False);
8437
8438          --  A selected component may be transformed into a parameterless
8439          --  function call. If the called entity is global, rewrite the
8440          --  node appropriately, i.e. as an extended name for the global
8441          --  entity.
8442
8443          elsif Nkind (Parent (N)) = N_Selected_Component
8444            and then Nkind (Parent (N2)) = N_Function_Call
8445            and then Is_Global (Entity (Name (Parent (N2))))
8446          then
8447             Change_Selected_Component_To_Expanded_Name (Parent (N));
8448             Set_Associated_Node (Parent (N), Name (Parent (N2)));
8449             Set_Global_Type (Parent (N), Name (Parent (N2)));
8450             Save_Entity_Descendants (N);
8451
8452          else
8453             --  Entity is local. Reset in generic unit, so that node
8454             --  is resolved anew at the point of instantiation.
8455
8456             Set_Associated_Node (N, Empty);
8457             Set_Etype (N, Empty);
8458          end if;
8459       end Reset_Entity;
8460
8461       -----------------------------
8462       -- Save_Entity_Descendants --
8463       -----------------------------
8464
8465       procedure Save_Entity_Descendants (N : Node_Id) is
8466       begin
8467          case Nkind (N) is
8468             when N_Binary_Op =>
8469                Save_Global_Descendant (Union_Id (Left_Opnd (N)));
8470                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
8471
8472             when N_Unary_Op =>
8473                Save_Global_Descendant (Union_Id (Right_Opnd (N)));
8474
8475             when N_Expanded_Name | N_Selected_Component =>
8476                Save_Global_Descendant (Union_Id (Prefix (N)));
8477                Save_Global_Descendant (Union_Id (Selector_Name (N)));
8478
8479             when N_Identifier | N_Character_Literal | N_Operator_Symbol =>
8480                null;
8481
8482             when others =>
8483                raise Program_Error;
8484          end case;
8485       end Save_Entity_Descendants;
8486
8487       --------------------------
8488       -- Save_Global_Defaults --
8489       --------------------------
8490
8491       procedure Save_Global_Defaults (N1, N2 : Node_Id) is
8492          Loc    : constant Source_Ptr := Sloc (N1);
8493          Assoc1 : List_Id := Generic_Associations (N1);
8494          Assoc2 : List_Id := Generic_Associations (N2);
8495          Act1   : Node_Id;
8496          Act2   : Node_Id;
8497          Def    : Node_Id;
8498          Gen_Id : Entity_Id := Entity (Name (N2));
8499          Ndec   : Node_Id;
8500          Subp   : Entity_Id;
8501          Actual : Entity_Id;
8502
8503       begin
8504          if Present (Assoc1) then
8505             Act1 := First (Assoc1);
8506          else
8507             Act1 := Empty;
8508             Set_Generic_Associations (N1, New_List);
8509             Assoc1 := Generic_Associations (N1);
8510          end if;
8511
8512          if Present (Assoc2) then
8513             Act2 := First (Assoc2);
8514          else
8515             return;
8516          end if;
8517
8518          while Present (Act1) and then Present (Act2) loop
8519             Next (Act1);
8520             Next (Act2);
8521          end loop;
8522
8523          --  Find the associations added for default suprograms.
8524
8525          if Present (Act2) then
8526             while Nkind (Act2) /= N_Generic_Association
8527               or else No (Entity (Selector_Name (Act2)))
8528               or else not Is_Overloadable (Entity (Selector_Name (Act2)))
8529             loop
8530                Next (Act2);
8531             end loop;
8532
8533             --  Add a similar association if the default is global. The
8534             --  renaming declaration for the actual has been analyzed, and
8535             --  its alias is the program it renames. Link the actual in the
8536             --  original generic tree with the node in the analyzed tree.
8537
8538             while Present (Act2) loop
8539                Subp := Entity (Selector_Name (Act2));
8540                Def  := Explicit_Generic_Actual_Parameter (Act2);
8541
8542                --  Following test is defence against rubbish errors
8543
8544                if No (Alias (Subp)) then
8545                   return;
8546                end if;
8547
8548                --  Retrieve the resolved actual from the renaming declaration
8549                --  created for the instantiated formal.
8550
8551                Actual := Entity (Name (Parent (Parent (Subp))));
8552                Set_Entity (Def, Actual);
8553                Set_Etype (Def, Etype (Actual));
8554
8555                if Is_Global (Actual) then
8556                   Ndec :=
8557                     Make_Generic_Association (Loc,
8558                       Selector_Name => New_Occurrence_Of (Subp, Loc),
8559                         Explicit_Generic_Actual_Parameter =>
8560                           New_Occurrence_Of (Actual, Loc));
8561
8562                   Set_Associated_Node
8563                     (Explicit_Generic_Actual_Parameter (Ndec), Def);
8564
8565                   Append (Ndec, Assoc1);
8566
8567                --  If there are other defaults, add a dummy association
8568                --  in case there are other defaulted formals with the same
8569                --  name.
8570
8571                elsif Present (Next (Act2)) then
8572                   Ndec :=
8573                     Make_Generic_Association (Loc,
8574                       Selector_Name => New_Occurrence_Of (Subp, Loc),
8575                         Explicit_Generic_Actual_Parameter => Empty);
8576
8577                   Append (Ndec, Assoc1);
8578                end if;
8579
8580                Next (Act2);
8581             end loop;
8582          end if;
8583
8584          if Nkind (Name (N1)) = N_Identifier
8585            and then Is_Child_Unit (Gen_Id)
8586            and then Is_Global (Gen_Id)
8587            and then Is_Generic_Unit (Scope (Gen_Id))
8588            and then In_Open_Scopes (Scope (Gen_Id))
8589          then
8590             --  This is an instantiation of a child unit within a sibling,
8591             --  so that the generic parent is in scope. An eventual instance
8592             --  must occur within the scope of an instance of the parent.
8593             --  Make name in instance into an expanded name, to preserve the
8594             --  identifier of the parent, so it can be resolved subsequently.
8595
8596             Rewrite (Name (N2),
8597               Make_Expanded_Name (Loc,
8598                 Chars         => Chars (Gen_Id),
8599                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
8600                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
8601             Set_Entity (Name (N2), Gen_Id);
8602
8603             Rewrite (Name (N1),
8604                Make_Expanded_Name (Loc,
8605                 Chars         => Chars (Gen_Id),
8606                 Prefix        => New_Occurrence_Of (Scope (Gen_Id), Loc),
8607                 Selector_Name => New_Occurrence_Of (Gen_Id, Loc)));
8608
8609             Set_Associated_Node (Name (N1), Name (N2));
8610             Set_Associated_Node (Prefix (Name (N1)), Empty);
8611             Set_Associated_Node
8612               (Selector_Name (Name (N1)), Selector_Name (Name (N2)));
8613             Set_Etype (Name (N1), Etype (Gen_Id));
8614          end if;
8615
8616       end Save_Global_Defaults;
8617
8618       ----------------------------
8619       -- Save_Global_Descendant --
8620       ----------------------------
8621
8622       procedure Save_Global_Descendant (D : Union_Id) is
8623          N1 : Node_Id;
8624
8625       begin
8626          if D in Node_Range then
8627             if D = Union_Id (Empty) then
8628                null;
8629
8630             elsif Nkind (Node_Id (D)) /= N_Compilation_Unit then
8631                Save_References (Node_Id (D));
8632             end if;
8633
8634          elsif D in List_Range then
8635             if D = Union_Id (No_List)
8636               or else Is_Empty_List (List_Id (D))
8637             then
8638                null;
8639
8640             else
8641                N1 := First (List_Id (D));
8642                while Present (N1) loop
8643                   Save_References (N1);
8644                   Next (N1);
8645                end loop;
8646             end if;
8647
8648          --  Element list or other non-node field, nothing to do
8649
8650          else
8651             null;
8652          end if;
8653       end Save_Global_Descendant;
8654
8655       ---------------------
8656       -- Save_References --
8657       ---------------------
8658
8659       --  This is the recursive procedure that does the work, once the
8660       --  enclosing generic scope has been established. We have to treat
8661       --  specially a number of node rewritings that are required by semantic
8662       --  processing and which change the kind of nodes in the generic copy:
8663       --  typically constant-folding, replacing an operator node by a string
8664       --  literal, or a selected component by an expanded name. In  each of
8665       --  those cases, the transformation is propagated to the generic unit.
8666
8667       procedure Save_References (N : Node_Id) is
8668       begin
8669          if N = Empty then
8670             null;
8671
8672          elsif (Nkind (N) = N_Character_Literal
8673                  or else Nkind (N) = N_Operator_Symbol)
8674          then
8675             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
8676                Reset_Entity (N);
8677
8678             elsif Nkind (N) = N_Operator_Symbol
8679               and then Nkind (Get_Associated_Node (N)) = N_String_Literal
8680             then
8681                Change_Operator_Symbol_To_String_Literal (N);
8682             end if;
8683
8684          elsif Nkind (N) in N_Op then
8685
8686             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
8687
8688                if Nkind (N) = N_Op_Concat then
8689                   Set_Is_Component_Left_Opnd (N,
8690                     Is_Component_Left_Opnd (Get_Associated_Node (N)));
8691
8692                   Set_Is_Component_Right_Opnd (N,
8693                     Is_Component_Right_Opnd (Get_Associated_Node (N)));
8694                end if;
8695
8696                Reset_Entity (N);
8697             else
8698                --  Node may be transformed into call to a user-defined operator
8699
8700                N2 := Get_Associated_Node (N);
8701
8702                if Nkind (N2) = N_Function_Call then
8703                   E := Entity (Name (N2));
8704
8705                   if Present (E)
8706                     and then Is_Global (E)
8707                   then
8708                      Set_Etype (N, Etype (N2));
8709                   else
8710                      Set_Associated_Node (N, Empty);
8711                      Set_Etype (N, Empty);
8712                   end if;
8713
8714                elsif Nkind (N2) = N_Integer_Literal
8715                  or else Nkind (N2) = N_Real_Literal
8716                  or else Nkind (N2) = N_String_Literal
8717                  or else (Nkind (N2) = N_Identifier
8718                            and then
8719                           Ekind (Entity (N2)) = E_Enumeration_Literal)
8720                then
8721                   --  Operation was constant-folded, perform the same
8722                   --  replacement in generic.
8723
8724                   --  Note: we do a Replace here rather than a Rewrite,
8725                   --  which is a definite violation of the standard rules
8726                   --  with regard to retrievability of the original tree,
8727                   --  and likely ASIS bugs or at least irregularities are
8728                   --  caused by this choice.
8729
8730                   --  The reason we do this is that the appropriate original
8731                   --  nodes are never constructed (we don't go applying the
8732                   --  generic instantiation to rewritten nodes in general).
8733                   --  We could try to create an appropriate copy but it would
8734                   --  be hard work and does not seem worth while, because
8735                   --  the original expression is accessible in the generic,
8736                   --  and ASIS rules for traversing instances are fuzzy.
8737
8738                   Replace (N, New_Copy (N2));
8739                   Set_Analyzed (N, False);
8740                end if;
8741             end if;
8742
8743             --  Complete the check on operands, if node has not been
8744             --  constant-folded.
8745
8746             if Nkind (N) in N_Op then
8747                Save_Entity_Descendants (N);
8748             end if;
8749
8750          elsif Nkind (N) = N_Identifier then
8751             if Nkind (N) = Nkind (Get_Associated_Node (N)) then
8752
8753                --  If this is a discriminant reference, always save it.
8754                --  It is used in the instance to find the corresponding
8755                --  discriminant positionally rather than  by name.
8756
8757                Set_Original_Discriminant
8758                  (N, Original_Discriminant (Get_Associated_Node (N)));
8759                Reset_Entity (N);
8760
8761             else
8762                N2 := Get_Associated_Node (N);
8763
8764                if Nkind (N2) = N_Function_Call then
8765                   E := Entity (Name (N2));
8766
8767                   --  Name resolves to a call to parameterless function.
8768                   --  If original entity is global, mark node as resolved.
8769
8770                   if Present (E)
8771                     and then Is_Global (E)
8772                   then
8773                      Set_Etype (N, Etype (N2));
8774                   else
8775                      Set_Associated_Node (N, Empty);
8776                      Set_Etype (N, Empty);
8777                   end if;
8778
8779                elsif
8780                  Nkind (N2) = N_Integer_Literal or else
8781                  Nkind (N2) = N_Real_Literal    or else
8782                  Nkind (N2) = N_String_Literal
8783                then
8784                   --  Name resolves to named number that is constant-folded,
8785                   --  or to string literal from concatenation.
8786                   --  Perform the same replacement in generic.
8787
8788                   Rewrite (N, New_Copy (N2));
8789                   Set_Analyzed (N, False);
8790
8791                elsif Nkind (N2) = N_Explicit_Dereference then
8792
8793                   --  An identifier is rewritten as a dereference if it is
8794                   --  the prefix in a selected component, and it denotes an
8795                   --  access to a composite type, or a parameterless function
8796                   --  call that returns an access type.
8797
8798                   --  Check whether corresponding entity in prefix is global.
8799
8800                   if Is_Entity_Name (Prefix (N2))
8801                     and then Present (Entity (Prefix (N2)))
8802                     and then Is_Global (Entity (Prefix (N2)))
8803                   then
8804                      Rewrite (N,
8805                        Make_Explicit_Dereference (Sloc (N),
8806                           Prefix => Make_Identifier (Sloc (N),
8807                             Chars => Chars (N))));
8808                      Set_Associated_Node (Prefix (N), Prefix (N2));
8809
8810                   elsif Nkind (Prefix (N2)) = N_Function_Call
8811                     and then Is_Global (Entity (Name (Prefix (N2))))
8812                   then
8813                      Rewrite (N,
8814                        Make_Explicit_Dereference (Sloc (N),
8815                           Prefix => Make_Function_Call (Sloc (N),
8816                             Name  =>
8817                               Make_Identifier (Sloc (N),
8818                               Chars => Chars (N)))));
8819
8820                      Set_Associated_Node
8821                       (Name (Prefix (N)), Name (Prefix (N2)));
8822
8823                   else
8824                      Set_Associated_Node (N, Empty);
8825                      Set_Etype (N, Empty);
8826                   end if;
8827
8828                --  The subtype mark of a nominally unconstrained object
8829                --  is rewritten as a subtype indication using the bounds
8830                --  of the expression. Recover the original subtype mark.
8831
8832                elsif Nkind (N2) = N_Subtype_Indication
8833                  and then Is_Entity_Name (Original_Node (N2))
8834                then
8835                   Set_Associated_Node (N, Original_Node (N2));
8836                   Reset_Entity (N);
8837
8838                else
8839                   null;
8840                end if;
8841             end if;
8842
8843          elsif Nkind (N) in N_Entity then
8844             null;
8845
8846          else
8847             declare
8848                use Atree.Unchecked_Access;
8849                --  This code section is part of implementing an untyped tree
8850                --  traversal, so it needs direct access to node fields.
8851
8852             begin
8853                if Nkind (N) = N_Aggregate
8854                     or else
8855                   Nkind (N) = N_Extension_Aggregate
8856                then
8857                   N2 := Get_Associated_Node (N);
8858
8859                   if No (N2)
8860                     or else No (Etype (N2))
8861                     or else not Is_Global (Etype (N2))
8862                   then
8863                      Set_Associated_Node (N, Empty);
8864                   end if;
8865
8866                   Save_Global_Descendant (Field1 (N));
8867                   Save_Global_Descendant (Field2 (N));
8868                   Save_Global_Descendant (Field3 (N));
8869                   Save_Global_Descendant (Field5 (N));
8870
8871                --  All other cases than aggregates
8872
8873                else
8874                   Save_Global_Descendant (Field1 (N));
8875                   Save_Global_Descendant (Field2 (N));
8876                   Save_Global_Descendant (Field3 (N));
8877                   Save_Global_Descendant (Field4 (N));
8878                   Save_Global_Descendant (Field5 (N));
8879                end if;
8880             end;
8881          end if;
8882       end Save_References;
8883
8884    --  Start of processing for Save_Global_References
8885
8886    begin
8887       Gen_Scope := Current_Scope;
8888
8889       --  If the generic unit is a child unit, references to entities in
8890       --  the parent are treated as local, because they will be resolved
8891       --  anew in the context of the instance of the parent.
8892
8893       while Is_Child_Unit (Gen_Scope)
8894         and then Ekind (Scope (Gen_Scope)) = E_Generic_Package
8895       loop
8896          Gen_Scope := Scope (Gen_Scope);
8897       end loop;
8898
8899       Save_References (N);
8900    end Save_Global_References;
8901
8902    ---------------------
8903    -- Set_Copied_Sloc --
8904    ---------------------
8905
8906    procedure Set_Copied_Sloc (N : Node_Id; E : Entity_Id) is
8907    begin
8908       Create_Instantiation_Source (N, E, S_Adjustment);
8909    end Set_Copied_Sloc;
8910
8911    ---------------------
8912    -- Set_Instance_Of --
8913    ---------------------
8914
8915    procedure Set_Instance_Of (A : Entity_Id; B : Entity_Id) is
8916    begin
8917       Generic_Renamings.Table (Generic_Renamings.Last) := (A, B, Assoc_Null);
8918       Generic_Renamings_HTable.Set (Generic_Renamings.Last);
8919       Generic_Renamings.Increment_Last;
8920    end Set_Instance_Of;
8921
8922    --------------------
8923    -- Set_Next_Assoc --
8924    --------------------
8925
8926    procedure Set_Next_Assoc (E : Assoc_Ptr; Next : Assoc_Ptr) is
8927    begin
8928       Generic_Renamings.Table (E).Next_In_HTable := Next;
8929    end Set_Next_Assoc;
8930
8931    -------------------
8932    -- Start_Generic --
8933    -------------------
8934
8935    procedure Start_Generic is
8936    begin
8937       --  ??? I am sure more things could be factored out in this
8938       --  routine. Should probably be done at a later stage.
8939
8940       Generic_Flags.Increment_Last;
8941       Generic_Flags.Table (Generic_Flags.Last) := Inside_A_Generic;
8942       Inside_A_Generic := True;
8943
8944       Expander_Mode_Save_And_Set (False);
8945    end Start_Generic;
8946
8947    -----------------
8948    -- Switch_View --
8949    -----------------
8950
8951    procedure Switch_View (T : Entity_Id) is
8952       Priv_Elmt : Elmt_Id := No_Elmt;
8953       Priv_Sub  : Entity_Id;
8954       BT        : Entity_Id := Base_Type (T);
8955
8956    begin
8957       --  T may be private but its base type may have been exchanged through
8958       --  some other occurrence, in which case there is nothing to switch.
8959
8960       if not Is_Private_Type (BT) then
8961          return;
8962       end if;
8963
8964       Priv_Elmt := First_Elmt (Private_Dependents (BT));
8965
8966       if Present (Full_View (BT)) then
8967          Append_Elmt (Full_View (BT), Exchanged_Views);
8968          Exchange_Declarations (BT);
8969       end if;
8970
8971       while Present (Priv_Elmt) loop
8972          Priv_Sub := (Node (Priv_Elmt));
8973
8974          --  We avoid flipping the subtype if the Etype of its full
8975          --  view is private because this would result in a malformed
8976          --  subtype. This occurs when the Etype of the subtype full
8977          --  view is the full view of the base type (and since the
8978          --  base types were just switched, the subtype is pointing
8979          --  to the wrong view). This is currently the case for
8980          --  tagged record types, access types (maybe more?) and
8981          --  needs to be resolved. ???
8982
8983          if Present (Full_View (Priv_Sub))
8984            and then not Is_Private_Type (Etype (Full_View (Priv_Sub)))
8985          then
8986             Append_Elmt (Full_View (Priv_Sub), Exchanged_Views);
8987             Exchange_Declarations (Priv_Sub);
8988          end if;
8989
8990          Next_Elmt (Priv_Elmt);
8991       end loop;
8992    end Switch_View;
8993
8994    -----------------------------
8995    -- Valid_Default_Attribute --
8996    -----------------------------
8997
8998    procedure Valid_Default_Attribute (Nam : Entity_Id; Def : Node_Id) is
8999       Attr_Id : constant Attribute_Id :=
9000                   Get_Attribute_Id (Attribute_Name (Def));
9001       F       : Entity_Id;
9002       Num_F   : Int;
9003       T       : Entity_Id := Entity (Prefix (Def));
9004       OK      : Boolean;
9005       Is_Fun  : constant Boolean := (Ekind (Nam) = E_Function);
9006
9007    begin
9008       if No (T)
9009         or else T = Any_Id
9010       then
9011          return;
9012       end if;
9013
9014       Num_F := 0;
9015       F := First_Formal (Nam);
9016       while Present (F) loop
9017          Num_F := Num_F + 1;
9018          Next_Formal (F);
9019       end loop;
9020
9021       case Attr_Id is
9022       when Attribute_Adjacent |  Attribute_Ceiling   | Attribute_Copy_Sign |
9023            Attribute_Floor    |  Attribute_Fraction  | Attribute_Machine   |
9024            Attribute_Model    |  Attribute_Remainder | Attribute_Rounding  |
9025            Attribute_Unbiased_Rounding  =>
9026          OK := (Is_Fun and then Num_F = 1 and then Is_Floating_Point_Type (T));
9027
9028       when Attribute_Image    | Attribute_Pred       | Attribute_Succ |
9029            Attribute_Value    | Attribute_Wide_Image |
9030            Attribute_Wide_Value  =>
9031          OK := (Is_Fun and then Num_F = 1 and then Is_Scalar_Type (T));
9032
9033       when Attribute_Max      |  Attribute_Min  =>
9034          OK := (Is_Fun and then Num_F = 2 and then Is_Scalar_Type (T));
9035
9036       when Attribute_Input =>
9037          OK := (Is_Fun and then Num_F = 1);
9038
9039       when Attribute_Output | Attribute_Read | Attribute_Write =>
9040          OK := (not Is_Fun and then Num_F = 2);
9041
9042       when others => OK := False;
9043       end case;
9044
9045       if not OK then
9046          Error_Msg_N ("attribute reference has wrong profile for subprogram",
9047            Def);
9048       end if;
9049    end Valid_Default_Attribute;
9050
9051 end Sem_Ch12;