OSDN Git Service

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