OSDN Git Service

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