OSDN Git Service

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