OSDN Git Service

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