OSDN Git Service

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