OSDN Git Service

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