OSDN Git Service

2011-08-29 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch8.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M . C H 8                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, 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 3,  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 COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Debug;    use Debug;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Exp_Tss;  use Exp_Tss;
32 with Exp_Util; use Exp_Util;
33 with Fname;    use Fname;
34 with Freeze;   use Freeze;
35 with Impunit;  use Impunit;
36 with Lib;      use Lib;
37 with Lib.Load; use Lib.Load;
38 with Lib.Xref; use Lib.Xref;
39 with Namet;    use Namet;
40 with Namet.Sp; use Namet.Sp;
41 with Nlists;   use Nlists;
42 with Nmake;    use Nmake;
43 with Opt;      use Opt;
44 with Output;   use Output;
45 with Restrict; use Restrict;
46 with Rident;   use Rident;
47 with Rtsfind;  use Rtsfind;
48 with Sem;      use Sem;
49 with Sem_Aux;  use Sem_Aux;
50 with Sem_Cat;  use Sem_Cat;
51 with Sem_Ch3;  use Sem_Ch3;
52 with Sem_Ch4;  use Sem_Ch4;
53 with Sem_Ch6;  use Sem_Ch6;
54 with Sem_Ch12; use Sem_Ch12;
55 with Sem_Disp; use Sem_Disp;
56 with Sem_Dist; use Sem_Dist;
57 with Sem_Eval; use Sem_Eval;
58 with Sem_Res;  use Sem_Res;
59 with Sem_Util; use Sem_Util;
60 with Sem_Type; use Sem_Type;
61 with Stand;    use Stand;
62 with Sinfo;    use Sinfo;
63 with Sinfo.CN; use Sinfo.CN;
64 with Snames;   use Snames;
65 with Style;    use Style;
66 with Table;
67 with Targparm; use Targparm;
68 with Tbuild;   use Tbuild;
69 with Uintp;    use Uintp;
70
71 package body Sem_Ch8 is
72
73    ------------------------------------
74    -- Visibility and Name Resolution --
75    ------------------------------------
76
77    --  This package handles name resolution and the collection of possible
78    --  interpretations for overloaded names, prior to overload resolution.
79
80    --  Name resolution is the process that establishes a mapping between source
81    --  identifiers and the entities they denote at each point in the program.
82    --  Each entity is represented by a defining occurrence. Each identifier
83    --  that denotes an entity points to the corresponding defining occurrence.
84    --  This is the entity of the applied occurrence. Each occurrence holds
85    --  an index into the names table, where source identifiers are stored.
86
87    --  Each entry in the names table for an identifier or designator uses the
88    --  Info pointer to hold a link to the currently visible entity that has
89    --  this name (see subprograms Get_Name_Entity_Id and Set_Name_Entity_Id
90    --  in package Sem_Util). The visibility is initialized at the beginning of
91    --  semantic processing to make entities in package Standard immediately
92    --  visible. The visibility table is used in a more subtle way when
93    --  compiling subunits (see below).
94
95    --  Entities that have the same name (i.e. homonyms) are chained. In the
96    --  case of overloaded entities, this chain holds all the possible meanings
97    --  of a given identifier. The process of overload resolution uses type
98    --  information to select from this chain the unique meaning of a given
99    --  identifier.
100
101    --  Entities are also chained in their scope, through the Next_Entity link.
102    --  As a consequence, the name space is organized as a sparse matrix, where
103    --  each row corresponds to a scope, and each column to a source identifier.
104    --  Open scopes, that is to say scopes currently being compiled, have their
105    --  corresponding rows of entities in order, innermost scope first.
106
107    --  The scopes of packages that are mentioned in  context clauses appear in
108    --  no particular order, interspersed among open scopes. This is because
109    --  in the course of analyzing the context of a compilation, a package
110    --  declaration is first an open scope, and subsequently an element of the
111    --  context. If subunits or child units are present, a parent unit may
112    --  appear under various guises at various times in the compilation.
113
114    --  When the compilation of the innermost scope is complete, the entities
115    --  defined therein are no longer visible. If the scope is not a package
116    --  declaration, these entities are never visible subsequently, and can be
117    --  removed from visibility chains. If the scope is a package declaration,
118    --  its visible declarations may still be accessible. Therefore the entities
119    --  defined in such a scope are left on the visibility chains, and only
120    --  their visibility (immediately visibility or potential use-visibility)
121    --  is affected.
122
123    --  The ordering of homonyms on their chain does not necessarily follow
124    --  the order of their corresponding scopes on the scope stack. For
125    --  example, if package P and the enclosing scope both contain entities
126    --  named E, then when compiling the package body the chain for E will
127    --  hold the global entity first,  and the local one (corresponding to
128    --  the current inner scope) next. As a result, name resolution routines
129    --  do not assume any relative ordering of the homonym chains, either
130    --  for scope nesting or to order of appearance of context clauses.
131
132    --  When compiling a child unit, entities in the parent scope are always
133    --  immediately visible. When compiling the body of a child unit, private
134    --  entities in the parent must also be made immediately visible. There
135    --  are separate routines to make the visible and private declarations
136    --  visible at various times (see package Sem_Ch7).
137
138    --              +--------+         +-----+
139    --              | In use |-------->| EU1 |-------------------------->
140    --              +--------+         +-----+
141    --                                    |                      |
142    --      +--------+                 +-----+                +-----+
143    --      | Stand. |---------------->| ES1 |--------------->| ES2 |--->
144    --      +--------+                 +-----+                +-----+
145    --                                    |                      |
146    --              +---------+           |                   +-----+
147    --              | with'ed |------------------------------>| EW2 |--->
148    --              +---------+           |                   +-----+
149    --                                    |                      |
150    --      +--------+                 +-----+                +-----+
151    --      | Scope2 |---------------->| E12 |--------------->| E22 |--->
152    --      +--------+                 +-----+                +-----+
153    --                                    |                      |
154    --      +--------+                 +-----+                +-----+
155    --      | Scope1 |---------------->| E11 |--------------->| E12 |--->
156    --      +--------+                 +-----+                +-----+
157    --          ^                         |                      |
158    --          |                         |                      |
159    --          |   +---------+           |                      |
160    --          |   | with'ed |----------------------------------------->
161    --          |   +---------+           |                      |
162    --          |                         |                      |
163    --      Scope stack                   |                      |
164    --      (innermost first)             |                      |
165    --                                 +----------------------------+
166    --      Names  table =>            | Id1 |     |    |     | Id2 |
167    --                                 +----------------------------+
168
169    --  Name resolution must deal with several syntactic forms: simple names,
170    --  qualified names, indexed names, and various forms of calls.
171
172    --  Each identifier points to an entry in the names table. The resolution
173    --  of a simple name consists in traversing the homonym chain, starting
174    --  from the names table. If an entry is immediately visible, it is the one
175    --  designated by the identifier. If only potentially use-visible entities
176    --  are on the chain, we must verify that they do not hide each other. If
177    --  the entity we find is overloadable, we collect all other overloadable
178    --  entities on the chain as long as they are not hidden.
179    --
180    --  To resolve expanded names, we must find the entity at the intersection
181    --  of the entity chain for the scope (the prefix) and the homonym chain
182    --  for the selector. In general, homonym chains will be much shorter than
183    --  entity chains, so it is preferable to start from the names table as
184    --  well. If the entity found is overloadable, we must collect all other
185    --  interpretations that are defined in the scope denoted by the prefix.
186
187    --  For records, protected types, and tasks, their local entities are
188    --  removed from visibility chains on exit from the corresponding scope.
189    --  From the outside, these entities are always accessed by selected
190    --  notation, and the entity chain for the record type, protected type,
191    --  etc. is traversed sequentially in  order to find the designated entity.
192
193    --  The discriminants of a type and the operations of a protected type or
194    --  task are unchained on  exit from the first view of the type, (such as
195    --  a private or incomplete type declaration, or a protected type speci-
196    --  fication) and re-chained when compiling the second view.
197
198    --  In the case of operators,  we do not make operators on derived types
199    --  explicit. As a result, the notation P."+" may denote either a user-
200    --  defined function with name "+", or else an implicit declaration of the
201    --  operator "+" in package P. The resolution of expanded names always
202    --  tries to resolve an operator name as such an implicitly defined entity,
203    --  in addition to looking for explicit declarations.
204
205    --  All forms of names that denote entities (simple names, expanded names,
206    --  character literals in some cases) have a Entity attribute, which
207    --  identifies the entity denoted by the name.
208
209    ---------------------
210    -- The Scope Stack --
211    ---------------------
212
213    --  The Scope stack keeps track of the scopes currently been compiled.
214    --  Every entity that contains declarations (including records) is placed
215    --  on the scope stack while it is being processed, and removed at the end.
216    --  Whenever a non-package scope is exited, the entities defined therein
217    --  are removed from the visibility table, so that entities in outer scopes
218    --  become visible (see previous description). On entry to Sem, the scope
219    --  stack only contains the package Standard. As usual, subunits complicate
220    --  this picture ever so slightly.
221
222    --  The Rtsfind mechanism can force a call to Semantics while another
223    --  compilation is in progress. The unit retrieved by Rtsfind must be
224    --  compiled in  its own context, and has no access to the visibility of
225    --  the unit currently being compiled. The procedures Save_Scope_Stack and
226    --  Restore_Scope_Stack make entities in current open scopes invisible
227    --  before compiling the retrieved unit, and restore the compilation
228    --  environment afterwards.
229
230    ------------------------
231    -- Compiling subunits --
232    ------------------------
233
234    --  Subunits must be compiled in the environment of the corresponding stub,
235    --  that is to say with the same visibility into the parent (and its
236    --  context) that is available at the point of the stub declaration, but
237    --  with the additional visibility provided by the context clause of the
238    --  subunit itself. As a result, compilation of a subunit forces compilation
239    --  of the parent (see description in lib-). At the point of the stub
240    --  declaration, Analyze is called recursively to compile the proper body of
241    --  the subunit, but without reinitializing the names table, nor the scope
242    --  stack (i.e. standard is not pushed on the stack). In this fashion the
243    --  context of the subunit is added to the context of the parent, and the
244    --  subunit is compiled in the correct environment. Note that in the course
245    --  of processing the context of a subunit, Standard will appear twice on
246    --  the scope stack: once for the parent of the subunit, and once for the
247    --  unit in the context clause being compiled. However, the two sets of
248    --  entities are not linked by homonym chains, so that the compilation of
249    --  any context unit happens in a fresh visibility environment.
250
251    -------------------------------
252    -- Processing of USE Clauses --
253    -------------------------------
254
255    --  Every defining occurrence has a flag indicating if it is potentially use
256    --  visible. Resolution of simple names examines this flag. The processing
257    --  of use clauses consists in setting this flag on all visible entities
258    --  defined in the corresponding package. On exit from the scope of the use
259    --  clause, the corresponding flag must be reset. However, a package may
260    --  appear in several nested use clauses (pathological but legal, alas!)
261    --  which forces us to use a slightly more involved scheme:
262
263    --    a) The defining occurrence for a package holds a flag -In_Use- to
264    --    indicate that it is currently in the scope of a use clause. If a
265    --    redundant use clause is encountered, then the corresponding occurrence
266    --    of the package name is flagged -Redundant_Use-.
267
268    --    b) On exit from a scope, the use clauses in its declarative part are
269    --    scanned. The visibility flag is reset in all entities declared in
270    --    package named in a use clause, as long as the package is not flagged
271    --    as being in a redundant use clause (in which case the outer use
272    --    clause is still in effect, and the direct visibility of its entities
273    --    must be retained).
274
275    --  Note that entities are not removed from their homonym chains on exit
276    --  from the package specification. A subsequent use clause does not need
277    --  to rechain the visible entities, but only to establish their direct
278    --  visibility.
279
280    -----------------------------------
281    -- Handling private declarations --
282    -----------------------------------
283
284    --  The principle that each entity has a single defining occurrence clashes
285    --  with the presence of two separate definitions for private types: the
286    --  first is the private type declaration, and second is the full type
287    --  declaration. It is important that all references to the type point to
288    --  the same defining occurrence, namely the first one. To enforce the two
289    --  separate views of the entity, the corresponding information is swapped
290    --  between the two declarations. Outside of the package, the defining
291    --  occurrence only contains the private declaration information, while in
292    --  the private part and the body of the package the defining occurrence
293    --  contains the full declaration. To simplify the swap, the defining
294    --  occurrence that currently holds the private declaration points to the
295    --  full declaration. During semantic processing the defining occurrence
296    --  also points to a list of private dependents, that is to say access types
297    --  or composite types whose designated types or component types are
298    --  subtypes or derived types of the private type in question. After the
299    --  full declaration has been seen, the private dependents are updated to
300    --  indicate that they have full definitions.
301
302    ------------------------------------
303    -- Handling of Undefined Messages --
304    ------------------------------------
305
306    --  In normal mode, only the first use of an undefined identifier generates
307    --  a message. The table Urefs is used to record error messages that have
308    --  been issued so that second and subsequent ones do not generate further
309    --  messages. However, the second reference causes text to be added to the
310    --  original undefined message noting "(more references follow)". The
311    --  full error list option (-gnatf) forces messages to be generated for
312    --  every reference and disconnects the use of this table.
313
314    type Uref_Entry is record
315       Node : Node_Id;
316       --  Node for identifier for which original message was posted. The
317       --  Chars field of this identifier is used to detect later references
318       --  to the same identifier.
319
320       Err : Error_Msg_Id;
321       --  Records error message Id of original undefined message. Reset to
322       --  No_Error_Msg after the second occurrence, where it is used to add
323       --  text to the original message as described above.
324
325       Nvis : Boolean;
326       --  Set if the message is not visible rather than undefined
327
328       Loc : Source_Ptr;
329       --  Records location of error message. Used to make sure that we do
330       --  not consider a, b : undefined as two separate instances, which
331       --  would otherwise happen, since the parser converts this sequence
332       --  to a : undefined; b : undefined.
333
334    end record;
335
336    package Urefs is new Table.Table (
337      Table_Component_Type => Uref_Entry,
338      Table_Index_Type     => Nat,
339      Table_Low_Bound      => 1,
340      Table_Initial        => 10,
341      Table_Increment      => 100,
342      Table_Name           => "Urefs");
343
344    Candidate_Renaming : Entity_Id;
345    --  Holds a candidate interpretation that appears in a subprogram renaming
346    --  declaration and does not match the given specification, but matches at
347    --  least on the first formal. Allows better error message when given
348    --  specification omits defaulted parameters, a common error.
349
350    -----------------------
351    -- Local Subprograms --
352    -----------------------
353
354    procedure Analyze_Generic_Renaming
355      (N : Node_Id;
356       K : Entity_Kind);
357    --  Common processing for all three kinds of generic renaming declarations.
358    --  Enter new name and indicate that it renames the generic unit.
359
360    procedure Analyze_Renamed_Character
361      (N       : Node_Id;
362       New_S   : Entity_Id;
363       Is_Body : Boolean);
364    --  Renamed entity is given by a character literal, which must belong
365    --  to the return type of the new entity. Is_Body indicates whether the
366    --  declaration is a renaming_as_body. If the original declaration has
367    --  already been frozen (because of an intervening body, e.g.) the body of
368    --  the function must be built now. The same applies to the following
369    --  various renaming procedures.
370
371    procedure Analyze_Renamed_Dereference
372      (N       : Node_Id;
373       New_S   : Entity_Id;
374       Is_Body : Boolean);
375    --  Renamed entity is given by an explicit dereference. Prefix must be a
376    --  conformant access_to_subprogram type.
377
378    procedure Analyze_Renamed_Entry
379      (N       : Node_Id;
380       New_S   : Entity_Id;
381       Is_Body : Boolean);
382    --  If the renamed entity in a subprogram renaming is an entry or protected
383    --  subprogram, build a body for the new entity whose only statement is a
384    --  call to the renamed entity.
385
386    procedure Analyze_Renamed_Family_Member
387      (N       : Node_Id;
388       New_S   : Entity_Id;
389       Is_Body : Boolean);
390    --  Used when the renamed entity is an indexed component. The prefix must
391    --  denote an entry family.
392
393    procedure Analyze_Renamed_Primitive_Operation
394      (N       : Node_Id;
395       New_S   : Entity_Id;
396       Is_Body : Boolean);
397    --  If the renamed entity in a subprogram renaming is a primitive operation
398    --  or a class-wide operation in prefix form, save the target object, which
399    --  must be added to the list of actuals in any subsequent call.
400
401    function Applicable_Use (Pack_Name : Node_Id) return Boolean;
402    --  Common code to Use_One_Package and Set_Use, to determine whether use
403    --  clause must be processed. Pack_Name is an entity name that references
404    --  the package in question.
405
406    procedure Attribute_Renaming (N : Node_Id);
407    --  Analyze renaming of attribute as subprogram. The renaming declaration N
408    --  is rewritten as a subprogram body that returns the attribute reference
409    --  applied to the formals of the function.
410
411    procedure Set_Entity_Or_Discriminal (N : Node_Id; E : Entity_Id);
412    --  Set Entity, with style check if need be. For a discriminant reference,
413    --  replace by the corresponding discriminal, i.e. the parameter of the
414    --  initialization procedure that corresponds to the discriminant.
415
416    procedure Check_Frozen_Renaming (N : Node_Id; Subp : Entity_Id);
417    --  A renaming_as_body may occur after the entity of the original decla-
418    --  ration has been frozen. In that case, the body of the new entity must
419    --  be built now, because the usual mechanism of building the renamed
420    --  body at the point of freezing will not work. Subp is the subprogram
421    --  for which N provides the Renaming_As_Body.
422
423    procedure Check_In_Previous_With_Clause
424      (N   : Node_Id;
425       Nam : Node_Id);
426    --  N is a use_package clause and Nam the package name, or N is a use_type
427    --  clause and Nam is the prefix of the type name. In either case, verify
428    --  that the package is visible at that point in the context: either  it
429    --  appears in a previous with_clause, or because it is a fully qualified
430    --  name and the root ancestor appears in a previous with_clause.
431
432    procedure Check_Library_Unit_Renaming (N : Node_Id; Old_E : Entity_Id);
433    --  Verify that the entity in a renaming declaration that is a library unit
434    --  is itself a library unit and not a nested unit or subunit. Also check
435    --  that if the renaming is a child unit of a generic parent, then the
436    --  renamed unit must also be a child unit of that parent. Finally, verify
437    --  that a renamed generic unit is not an implicit child declared within
438    --  an instance of the parent.
439
440    procedure Chain_Use_Clause (N : Node_Id);
441    --  Chain use clause onto list of uses clauses headed by First_Use_Clause in
442    --  the proper scope table entry. This is usually the current scope, but it
443    --  will be an inner scope when installing the use clauses of the private
444    --  declarations of a parent unit prior to compiling the private part of a
445    --  child unit. This chain is traversed when installing/removing use clauses
446    --  when compiling a subunit or instantiating a generic body on the fly,
447    --  when it is necessary to save and restore full environments.
448
449    function Has_Implicit_Character_Literal (N : Node_Id) return Boolean;
450    --  Find a type derived from Character or Wide_Character in the prefix of N.
451    --  Used to resolved qualified names whose selector is a character literal.
452
453    function Has_Private_With (E : Entity_Id) return Boolean;
454    --  Ada 2005 (AI-262): Determines if the current compilation unit has a
455    --  private with on E.
456
457    procedure Find_Expanded_Name (N : Node_Id);
458    --  The input is a selected component known to be an expanded name. Verify
459    --  legality of selector given the scope denoted by prefix, and change node
460    --  N into a expanded name with a properly set Entity field.
461
462    function Find_Renamed_Entity
463      (N         : Node_Id;
464       Nam       : Node_Id;
465       New_S     : Entity_Id;
466       Is_Actual : Boolean := False) return Entity_Id;
467    --  Find the renamed entity that corresponds to the given parameter profile
468    --  in a subprogram renaming declaration. The renamed entity may be an
469    --  operator, a subprogram, an entry, or a protected operation. Is_Actual
470    --  indicates that the renaming is the one generated for an actual subpro-
471    --  gram in an instance, for which special visibility checks apply.
472
473    function Has_Implicit_Operator (N : Node_Id) return Boolean;
474    --  N is an expanded name whose selector is an operator name (e.g. P."+").
475    --  declarative part contains an implicit declaration of an operator if it
476    --  has a declaration of a type to which one of the predefined operators
477    --  apply. The existence of this routine is an implementation artifact. A
478    --  more straightforward but more space-consuming choice would be to make
479    --  all inherited operators explicit in the symbol table.
480
481    procedure Inherit_Renamed_Profile (New_S : Entity_Id; Old_S : Entity_Id);
482    --  A subprogram defined by a renaming declaration inherits the parameter
483    --  profile of the renamed entity. The subtypes given in the subprogram
484    --  specification are discarded and replaced with those of the renamed
485    --  subprogram, which are then used to recheck the default values.
486
487    function Is_Appropriate_For_Record (T : Entity_Id) return Boolean;
488    --  Prefix is appropriate for record if it is of a record type, or an access
489    --  to such.
490
491    function Is_Appropriate_For_Entry_Prefix (T : Entity_Id) return Boolean;
492    --  True if it is of a task type, a protected type, or else an access to one
493    --  of these types.
494
495    procedure Note_Redundant_Use (Clause : Node_Id);
496    --  Mark the name in a use clause as redundant if the corresponding entity
497    --  is already use-visible. Emit a warning if the use clause comes from
498    --  source and the proper warnings are enabled.
499
500    procedure Premature_Usage (N : Node_Id);
501    --  Diagnose usage of an entity before it is visible
502
503    procedure Use_One_Package (P : Entity_Id; N : Node_Id);
504    --  Make visible entities declared in package P potentially use-visible
505    --  in the current context. Also used in the analysis of subunits, when
506    --  re-installing use clauses of parent units. N is the use_clause that
507    --  names P (and possibly other packages).
508
509    procedure Use_One_Type (Id : Node_Id; Installed : Boolean := False);
510    --  Id is the subtype mark from a use type clause. This procedure makes
511    --  the primitive operators of the type potentially use-visible. The
512    --  boolean flag Installed indicates that the clause is being reinstalled
513    --  after previous analysis, and primitive operations are already chained
514    --  on the Used_Operations list of the clause.
515
516    procedure Write_Info;
517    --  Write debugging information on entities declared in current scope
518
519    --------------------------------
520    -- Analyze_Exception_Renaming --
521    --------------------------------
522
523    --  The language only allows a single identifier, but the tree holds an
524    --  identifier list. The parser has already issued an error message if
525    --  there is more than one element in the list.
526
527    procedure Analyze_Exception_Renaming (N : Node_Id) is
528       Id  : constant Node_Id := Defining_Identifier (N);
529       Nam : constant Node_Id := Name (N);
530
531    begin
532       Check_SPARK_Restriction ("exception renaming is not allowed", N);
533
534       Enter_Name (Id);
535       Analyze (Nam);
536
537       Set_Ekind          (Id, E_Exception);
538       Set_Exception_Code (Id, Uint_0);
539       Set_Etype          (Id, Standard_Exception_Type);
540       Set_Is_Pure        (Id, Is_Pure (Current_Scope));
541
542       if not Is_Entity_Name (Nam) or else
543         Ekind (Entity (Nam)) /= E_Exception
544       then
545          Error_Msg_N ("invalid exception name in renaming", Nam);
546       else
547          if Present (Renamed_Object (Entity (Nam))) then
548             Set_Renamed_Object (Id, Renamed_Object (Entity (Nam)));
549          else
550             Set_Renamed_Object (Id, Entity (Nam));
551          end if;
552       end if;
553    end Analyze_Exception_Renaming;
554
555    ---------------------------
556    -- Analyze_Expanded_Name --
557    ---------------------------
558
559    procedure Analyze_Expanded_Name (N : Node_Id) is
560    begin
561       --  If the entity pointer is already set, this is an internal node, or a
562       --  node that is analyzed more than once, after a tree modification. In
563       --  such a case there is no resolution to perform, just set the type. For
564       --  completeness, analyze prefix as well.
565
566       if Present (Entity (N)) then
567          if Is_Type (Entity (N)) then
568             Set_Etype (N, Entity (N));
569          else
570             Set_Etype (N, Etype (Entity (N)));
571          end if;
572
573          Analyze (Prefix (N));
574          return;
575       else
576          Find_Expanded_Name (N);
577       end if;
578    end Analyze_Expanded_Name;
579
580    ---------------------------------------
581    -- Analyze_Generic_Function_Renaming --
582    ---------------------------------------
583
584    procedure Analyze_Generic_Function_Renaming  (N : Node_Id) is
585    begin
586       Analyze_Generic_Renaming (N, E_Generic_Function);
587    end Analyze_Generic_Function_Renaming;
588
589    --------------------------------------
590    -- Analyze_Generic_Package_Renaming --
591    --------------------------------------
592
593    procedure Analyze_Generic_Package_Renaming   (N : Node_Id) is
594    begin
595       --  Apply the Text_IO Kludge here, since we may be renaming one of the
596       --  subpackages of Text_IO, then join common routine.
597
598       Text_IO_Kludge (Name (N));
599
600       Analyze_Generic_Renaming (N, E_Generic_Package);
601    end Analyze_Generic_Package_Renaming;
602
603    ----------------------------------------
604    -- Analyze_Generic_Procedure_Renaming --
605    ----------------------------------------
606
607    procedure Analyze_Generic_Procedure_Renaming (N : Node_Id) is
608    begin
609       Analyze_Generic_Renaming (N, E_Generic_Procedure);
610    end Analyze_Generic_Procedure_Renaming;
611
612    ------------------------------
613    -- Analyze_Generic_Renaming --
614    ------------------------------
615
616    procedure Analyze_Generic_Renaming
617      (N : Node_Id;
618       K : Entity_Kind)
619    is
620       New_P : constant Entity_Id := Defining_Entity (N);
621       Old_P : Entity_Id;
622       Inst  : Boolean   := False; -- prevent junk warning
623
624    begin
625       if Name (N) = Error then
626          return;
627       end if;
628
629       Check_SPARK_Restriction ("generic renaming is not allowed", N);
630
631       Generate_Definition (New_P);
632
633       if Current_Scope /= Standard_Standard then
634          Set_Is_Pure (New_P, Is_Pure (Current_Scope));
635       end if;
636
637       if Nkind (Name (N)) = N_Selected_Component then
638          Check_Generic_Child_Unit (Name (N), Inst);
639       else
640          Analyze (Name (N));
641       end if;
642
643       if not Is_Entity_Name (Name (N)) then
644          Error_Msg_N ("expect entity name in renaming declaration", Name (N));
645          Old_P := Any_Id;
646       else
647          Old_P := Entity (Name (N));
648       end if;
649
650       Enter_Name (New_P);
651       Set_Ekind (New_P, K);
652
653       if Etype (Old_P) = Any_Type then
654          null;
655
656       elsif Ekind (Old_P) /= K then
657          Error_Msg_N ("invalid generic unit name", Name (N));
658
659       else
660          if Present (Renamed_Object (Old_P)) then
661             Set_Renamed_Object (New_P,  Renamed_Object (Old_P));
662          else
663             Set_Renamed_Object (New_P, Old_P);
664          end if;
665
666          Set_Is_Pure          (New_P, Is_Pure          (Old_P));
667          Set_Is_Preelaborated (New_P, Is_Preelaborated (Old_P));
668
669          Set_Etype (New_P, Etype (Old_P));
670          Set_Has_Completion (New_P);
671
672          if In_Open_Scopes (Old_P) then
673             Error_Msg_N ("within its scope, generic denotes its instance", N);
674          end if;
675
676          Check_Library_Unit_Renaming (N, Old_P);
677       end if;
678    end Analyze_Generic_Renaming;
679
680    -----------------------------
681    -- Analyze_Object_Renaming --
682    -----------------------------
683
684    procedure Analyze_Object_Renaming (N : Node_Id) is
685       Loc : constant Source_Ptr := Sloc (N);
686       Id  : constant Entity_Id  := Defining_Identifier (N);
687       Dec : Node_Id;
688       Nam : constant Node_Id    := Name (N);
689       T   : Entity_Id;
690       T2  : Entity_Id;
691
692       procedure Check_Constrained_Object;
693       --  If the nominal type is unconstrained but the renamed object is
694       --  constrained, as can happen with renaming an explicit dereference or
695       --  a function return, build a constrained subtype from the object. If
696       --  the renaming is for a formal in an accept statement, the analysis
697       --  has already established its actual subtype. This is only relevant
698       --  if the renamed object is an explicit dereference.
699
700       function In_Generic_Scope (E : Entity_Id) return Boolean;
701       --  Determine whether entity E is inside a generic cope
702
703       ------------------------------
704       -- Check_Constrained_Object --
705       ------------------------------
706
707       procedure Check_Constrained_Object is
708          Subt : Entity_Id;
709
710       begin
711          if Nkind_In (Nam, N_Function_Call, N_Explicit_Dereference)
712            and then Is_Composite_Type (Etype (Nam))
713            and then not Is_Constrained (Etype (Nam))
714            and then not Has_Unknown_Discriminants (Etype (Nam))
715            and then Expander_Active
716          then
717             --  If Actual_Subtype is already set, nothing to do
718
719             if Ekind_In (Id, E_Variable, E_Constant)
720               and then Present (Actual_Subtype (Id))
721             then
722                null;
723
724             else
725                Subt := Make_Temporary (Loc, 'T');
726                Remove_Side_Effects (Nam);
727                Insert_Action (N,
728                  Make_Subtype_Declaration (Loc,
729                    Defining_Identifier => Subt,
730                    Subtype_Indication  =>
731                      Make_Subtype_From_Expr (Nam, Etype (Nam))));
732                Rewrite (Subtype_Mark (N), New_Occurrence_Of (Subt, Loc));
733                Set_Etype (Nam, Subt);
734             end if;
735          end if;
736       end Check_Constrained_Object;
737
738       ----------------------
739       -- In_Generic_Scope --
740       ----------------------
741
742       function In_Generic_Scope (E : Entity_Id) return Boolean is
743          S : Entity_Id;
744
745       begin
746          S := Scope (E);
747          while Present (S) and then S /= Standard_Standard loop
748             if Is_Generic_Unit (S) then
749                return True;
750             end if;
751
752             S := Scope (S);
753          end loop;
754
755          return False;
756       end In_Generic_Scope;
757
758    --  Start of processing for Analyze_Object_Renaming
759
760    begin
761       if Nam = Error then
762          return;
763       end if;
764
765       Check_SPARK_Restriction ("object renaming is not allowed", N);
766
767       Set_Is_Pure (Id, Is_Pure (Current_Scope));
768       Enter_Name (Id);
769
770       --  The renaming of a component that depends on a discriminant requires
771       --  an actual subtype, because in subsequent use of the object Gigi will
772       --  be unable to locate the actual bounds. This explicit step is required
773       --  when the renaming is generated in removing side effects of an
774       --  already-analyzed expression.
775
776       if Nkind (Nam) = N_Selected_Component
777         and then Analyzed (Nam)
778       then
779          T := Etype (Nam);
780          Dec :=  Build_Actual_Subtype_Of_Component (Etype (Nam), Nam);
781
782          if Present (Dec) then
783             Insert_Action (N, Dec);
784             T := Defining_Identifier (Dec);
785             Set_Etype (Nam, T);
786          end if;
787
788          --  Complete analysis of the subtype mark in any case, for ASIS use
789
790          if Present (Subtype_Mark (N)) then
791             Find_Type (Subtype_Mark (N));
792          end if;
793
794       elsif Present (Subtype_Mark (N)) then
795          Find_Type (Subtype_Mark (N));
796          T := Entity (Subtype_Mark (N));
797          Analyze (Nam);
798
799          if Nkind (Nam) = N_Type_Conversion
800             and then not Is_Tagged_Type (T)
801          then
802             Error_Msg_N
803               ("renaming of conversion only allowed for tagged types", Nam);
804          end if;
805
806          Resolve (Nam, T);
807
808          --  If the renamed object is a function call of a limited type,
809          --  the expansion of the renaming is complicated by the presence
810          --  of various temporaries and subtypes that capture constraints
811          --  of the renamed object. Rewrite node as an object declaration,
812          --  whose expansion is simpler. Given that the object is limited
813          --  there is no copy involved and no performance hit.
814
815          if Nkind (Nam) = N_Function_Call
816            and then Is_Immutably_Limited_Type (Etype (Nam))
817            and then not Is_Constrained (Etype (Nam))
818            and then Comes_From_Source (N)
819          then
820             Set_Etype (Id, T);
821             Set_Ekind (Id, E_Constant);
822             Rewrite (N,
823               Make_Object_Declaration (Loc,
824                 Defining_Identifier => Id,
825                 Constant_Present    => True,
826                 Object_Definition   => New_Occurrence_Of (Etype (Nam), Loc),
827                 Expression          => Relocate_Node (Nam)));
828             return;
829          end if;
830
831          --  Check that a class-wide object is not being renamed as an object
832          --  of a specific type. The test for access types is needed to exclude
833          --  cases where the renamed object is a dynamically tagged access
834          --  result, such as occurs in certain expansions.
835
836          if Is_Tagged_Type (T) then
837             Check_Dynamically_Tagged_Expression
838               (Expr        => Nam,
839                Typ         => T,
840                Related_Nod => N);
841          end if;
842
843       --  Ada 2005 (AI-230/AI-254): Access renaming
844
845       else pragma Assert (Present (Access_Definition (N)));
846          T := Access_Definition
847                 (Related_Nod => N,
848                  N           => Access_Definition (N));
849
850          Analyze (Nam);
851
852          --  Ada 2005 AI05-105: if the declaration has an anonymous access
853          --  type, the renamed object must also have an anonymous type, and
854          --  this is a name resolution rule. This was implicit in the last part
855          --  of the first sentence in 8.5.1(3/2), and is made explicit by this
856          --  recent AI.
857
858          if not Is_Overloaded (Nam) then
859             if Ekind (Etype (Nam)) /= Ekind (T) then
860                Error_Msg_N
861                  ("expect anonymous access type in object renaming", N);
862             end if;
863
864          else
865             declare
866                I    : Interp_Index;
867                It   : Interp;
868                Typ  : Entity_Id := Empty;
869                Seen : Boolean   := False;
870
871             begin
872                Get_First_Interp (Nam, I, It);
873                while Present (It.Typ) loop
874
875                   --  Renaming is ambiguous if more than one candidate
876                   --  interpretation is type-conformant with the context.
877
878                   if Ekind (It.Typ) = Ekind (T) then
879                      if Ekind (T) = E_Anonymous_Access_Subprogram_Type
880                        and then
881                          Type_Conformant
882                            (Designated_Type (T), Designated_Type (It.Typ))
883                      then
884                         if not Seen then
885                            Seen := True;
886                         else
887                            Error_Msg_N
888                              ("ambiguous expression in renaming", Nam);
889                         end if;
890
891                      elsif Ekind (T) = E_Anonymous_Access_Type
892                        and then
893                          Covers (Designated_Type (T), Designated_Type (It.Typ))
894                      then
895                         if not Seen then
896                            Seen := True;
897                         else
898                            Error_Msg_N
899                              ("ambiguous expression in renaming", Nam);
900                         end if;
901                      end if;
902
903                      if Covers (T, It.Typ) then
904                         Typ := It.Typ;
905                         Set_Etype (Nam, Typ);
906                         Set_Is_Overloaded (Nam, False);
907                      end if;
908                   end if;
909
910                   Get_Next_Interp (I, It);
911                end loop;
912             end;
913          end if;
914
915          Resolve (Nam, T);
916
917          --  Ada 2005 (AI-231): "In the case where the type is defined by an
918          --  access_definition, the renamed entity shall be of an access-to-
919          --  constant type if and only if the access_definition defines an
920          --  access-to-constant type" ARM 8.5.1(4)
921
922          if Constant_Present (Access_Definition (N))
923            and then not Is_Access_Constant (Etype (Nam))
924          then
925             Error_Msg_N ("(Ada 2005): the renamed object is not "
926                          & "access-to-constant (RM 8.5.1(6))", N);
927
928          elsif not Constant_Present (Access_Definition (N))
929            and then Is_Access_Constant (Etype (Nam))
930          then
931             Error_Msg_N ("(Ada 2005): the renamed object is not "
932                          & "access-to-variable (RM 8.5.1(6))", N);
933          end if;
934
935          if Is_Access_Subprogram_Type (Etype (Nam)) then
936             Check_Subtype_Conformant
937               (Designated_Type (T), Designated_Type (Etype (Nam)));
938
939          elsif not Subtypes_Statically_Match
940                      (Designated_Type (T),
941                       Available_View (Designated_Type (Etype (Nam))))
942          then
943             Error_Msg_N
944               ("subtype of renamed object does not statically match", N);
945          end if;
946       end if;
947
948       --  Special processing for renaming function return object. Some errors
949       --  and warnings are produced only for calls that come from source.
950
951       if Nkind (Nam) = N_Function_Call then
952          case Ada_Version is
953
954             --  Usage is illegal in Ada 83
955
956             when Ada_83 =>
957                if Comes_From_Source (Nam) then
958                   Error_Msg_N
959                     ("(Ada 83) cannot rename function return object", Nam);
960                end if;
961
962             --  In Ada 95, warn for odd case of renaming parameterless function
963             --  call if this is not a limited type (where this is useful).
964
965             when others =>
966                if Warn_On_Object_Renames_Function
967                  and then No (Parameter_Associations (Nam))
968                  and then not Is_Limited_Type (Etype (Nam))
969                  and then Comes_From_Source (Nam)
970                then
971                   Error_Msg_N
972                     ("?renaming function result object is suspicious", Nam);
973                   Error_Msg_NE
974                     ("\?function & will be called only once", Nam,
975                      Entity (Name (Nam)));
976                   Error_Msg_N -- CODEFIX
977                     ("\?suggest using an initialized constant object instead",
978                      Nam);
979                end if;
980
981          end case;
982       end if;
983
984       Check_Constrained_Object;
985
986       --  An object renaming requires an exact match of the type. Class-wide
987       --  matching is not allowed.
988
989       if Is_Class_Wide_Type (T)
990         and then Base_Type (Etype (Nam)) /= Base_Type (T)
991       then
992          Wrong_Type (Nam, T);
993       end if;
994
995       T2 := Etype (Nam);
996
997       --  Ada 2005 (AI-326): Handle wrong use of incomplete type
998
999       if Nkind (Nam) = N_Explicit_Dereference
1000         and then Ekind (Etype (T2)) = E_Incomplete_Type
1001       then
1002          Error_Msg_NE ("invalid use of incomplete type&", Id, T2);
1003          return;
1004
1005       elsif Ekind (Etype (T)) = E_Incomplete_Type then
1006          Error_Msg_NE ("invalid use of incomplete type&", Id, T);
1007          return;
1008       end if;
1009
1010       --  Ada 2005 (AI-327)
1011
1012       if Ada_Version >= Ada_2005
1013         and then Nkind (Nam) = N_Attribute_Reference
1014         and then Attribute_Name (Nam) = Name_Priority
1015       then
1016          null;
1017
1018       elsif Ada_Version >= Ada_2005
1019         and then Nkind (Nam) in N_Has_Entity
1020       then
1021          declare
1022             Nam_Decl : Node_Id;
1023             Nam_Ent  : Entity_Id;
1024
1025          begin
1026             if Nkind (Nam) = N_Attribute_Reference then
1027                Nam_Ent := Entity (Prefix (Nam));
1028             else
1029                Nam_Ent := Entity (Nam);
1030             end if;
1031
1032             Nam_Decl := Parent (Nam_Ent);
1033
1034             if Has_Null_Exclusion (N)
1035               and then not Has_Null_Exclusion (Nam_Decl)
1036             then
1037                --  Ada 2005 (AI-423): If the object name denotes a generic
1038                --  formal object of a generic unit G, and the object renaming
1039                --  declaration occurs within the body of G or within the body
1040                --  of a generic unit declared within the declarative region
1041                --  of G, then the declaration of the formal object of G must
1042                --  have a null exclusion or a null-excluding subtype.
1043
1044                if Is_Formal_Object (Nam_Ent)
1045                     and then In_Generic_Scope (Id)
1046                then
1047                   if not Can_Never_Be_Null (Etype (Nam_Ent)) then
1048                      Error_Msg_N
1049                        ("renamed formal does not exclude `NULL` "
1050                         & "(RM 8.5.1(4.6/2))", N);
1051
1052                   elsif In_Package_Body (Scope (Id)) then
1053                      Error_Msg_N
1054                        ("formal object does not have a null exclusion"
1055                         & "(RM 8.5.1(4.6/2))", N);
1056                   end if;
1057
1058                --  Ada 2005 (AI-423): Otherwise, the subtype of the object name
1059                --  shall exclude null.
1060
1061                elsif not Can_Never_Be_Null (Etype (Nam_Ent)) then
1062                   Error_Msg_N
1063                     ("renamed object does not exclude `NULL` "
1064                      & "(RM 8.5.1(4.6/2))", N);
1065
1066                --  An instance is illegal if it contains a renaming that
1067                --  excludes null, and the actual does not. The renaming
1068                --  declaration has already indicated that the declaration
1069                --  of the renamed actual in the instance will raise
1070                --  constraint_error.
1071
1072                elsif Nkind (Nam_Decl) = N_Object_Declaration
1073                  and then In_Instance
1074                  and then Present
1075                    (Corresponding_Generic_Association (Nam_Decl))
1076                  and then Nkind (Expression (Nam_Decl))
1077                    = N_Raise_Constraint_Error
1078                then
1079                   Error_Msg_N
1080                     ("renamed actual does not exclude `NULL` "
1081                      & "(RM 8.5.1(4.6/2))", N);
1082
1083                --  Finally, if there is a null exclusion, the subtype mark
1084                --  must not be null-excluding.
1085
1086                elsif No (Access_Definition (N))
1087                  and then Can_Never_Be_Null (T)
1088                then
1089                   Error_Msg_NE
1090                     ("`NOT NULL` not allowed (& already excludes null)",
1091                       N, T);
1092
1093                end if;
1094
1095             elsif Can_Never_Be_Null (T)
1096               and then not Can_Never_Be_Null (Etype (Nam_Ent))
1097             then
1098                Error_Msg_N
1099                  ("renamed object does not exclude `NULL` "
1100                   & "(RM 8.5.1(4.6/2))", N);
1101
1102             elsif Has_Null_Exclusion (N)
1103               and then No (Access_Definition (N))
1104               and then Can_Never_Be_Null (T)
1105             then
1106                Error_Msg_NE
1107                  ("`NOT NULL` not allowed (& already excludes null)", N, T);
1108             end if;
1109          end;
1110       end if;
1111
1112       Set_Ekind (Id, E_Variable);
1113       Init_Size_Align (Id);
1114
1115       if T = Any_Type or else Etype (Nam) = Any_Type then
1116          return;
1117
1118       --  Verify that the renamed entity is an object or a function call. It
1119       --  may have been rewritten in several ways.
1120
1121       elsif Is_Object_Reference (Nam) then
1122          if Comes_From_Source (N)
1123            and then Is_Dependent_Component_Of_Mutable_Object (Nam)
1124          then
1125             Error_Msg_N
1126               ("illegal renaming of discriminant-dependent component", Nam);
1127          end if;
1128
1129       --  A static function call may have been folded into a literal
1130
1131       elsif Nkind (Original_Node (Nam)) = N_Function_Call
1132
1133             --  When expansion is disabled, attribute reference is not
1134             --  rewritten as function call. Otherwise it may be rewritten
1135             --  as a conversion, so check original node.
1136
1137         or else (Nkind (Original_Node (Nam)) = N_Attribute_Reference
1138                   and then Is_Function_Attribute_Name
1139                              (Attribute_Name (Original_Node (Nam))))
1140
1141             --  Weird but legal, equivalent to renaming a function call.
1142             --  Illegal if the literal is the result of constant-folding an
1143             --  attribute reference that is not a function.
1144
1145         or else (Is_Entity_Name (Nam)
1146                   and then Ekind (Entity (Nam)) = E_Enumeration_Literal
1147                   and then
1148                     Nkind (Original_Node (Nam)) /= N_Attribute_Reference)
1149
1150         or else (Nkind (Nam) = N_Type_Conversion
1151                     and then Is_Tagged_Type (Entity (Subtype_Mark (Nam))))
1152       then
1153          null;
1154
1155       elsif Nkind (Nam) = N_Type_Conversion then
1156          Error_Msg_N
1157            ("renaming of conversion only allowed for tagged types", Nam);
1158
1159       --  Ada 2005 (AI-327)
1160
1161       elsif Ada_Version >= Ada_2005
1162         and then Nkind (Nam) = N_Attribute_Reference
1163         and then Attribute_Name (Nam) = Name_Priority
1164       then
1165          null;
1166
1167       --  Allow internally generated x'Reference expression
1168
1169       elsif Nkind (Nam) = N_Reference then
1170          null;
1171
1172       else
1173          Error_Msg_N ("expect object name in renaming", Nam);
1174       end if;
1175
1176       Set_Etype (Id, T2);
1177
1178       if not Is_Variable (Nam) then
1179          Set_Ekind               (Id, E_Constant);
1180          Set_Never_Set_In_Source (Id, True);
1181          Set_Is_True_Constant    (Id, True);
1182       end if;
1183
1184       Set_Renamed_Object (Id, Nam);
1185    end Analyze_Object_Renaming;
1186
1187    ------------------------------
1188    -- Analyze_Package_Renaming --
1189    ------------------------------
1190
1191    procedure Analyze_Package_Renaming (N : Node_Id) is
1192       New_P : constant Entity_Id := Defining_Entity (N);
1193       Old_P : Entity_Id;
1194       Spec  : Node_Id;
1195
1196    begin
1197       if Name (N) = Error then
1198          return;
1199       end if;
1200
1201       --  Apply Text_IO kludge here since we may be renaming a child of Text_IO
1202
1203       Text_IO_Kludge (Name (N));
1204
1205       if Current_Scope /= Standard_Standard then
1206          Set_Is_Pure (New_P, Is_Pure (Current_Scope));
1207       end if;
1208
1209       Enter_Name (New_P);
1210       Analyze (Name (N));
1211
1212       if Is_Entity_Name (Name (N)) then
1213          Old_P := Entity (Name (N));
1214       else
1215          Old_P := Any_Id;
1216       end if;
1217
1218       if Etype (Old_P) = Any_Type then
1219          Error_Msg_N ("expect package name in renaming", Name (N));
1220
1221       elsif Ekind (Old_P) /= E_Package
1222         and then not (Ekind (Old_P) = E_Generic_Package
1223                        and then In_Open_Scopes (Old_P))
1224       then
1225          if Ekind (Old_P) = E_Generic_Package then
1226             Error_Msg_N
1227                ("generic package cannot be renamed as a package", Name (N));
1228          else
1229             Error_Msg_Sloc := Sloc (Old_P);
1230             Error_Msg_NE
1231              ("expect package name in renaming, found& declared#",
1232                Name (N), Old_P);
1233          end if;
1234
1235          --  Set basic attributes to minimize cascaded errors
1236
1237          Set_Ekind (New_P, E_Package);
1238          Set_Etype (New_P, Standard_Void_Type);
1239
1240       --  Here for OK package renaming
1241
1242       else
1243          --  Entities in the old package are accessible through the renaming
1244          --  entity. The simplest implementation is to have both packages share
1245          --  the entity list.
1246
1247          Set_Ekind (New_P, E_Package);
1248          Set_Etype (New_P, Standard_Void_Type);
1249
1250          if Present (Renamed_Object (Old_P)) then
1251             Set_Renamed_Object (New_P,  Renamed_Object (Old_P));
1252          else
1253             Set_Renamed_Object (New_P, Old_P);
1254          end if;
1255
1256          Set_Has_Completion (New_P);
1257
1258          Set_First_Entity (New_P,  First_Entity (Old_P));
1259          Set_Last_Entity  (New_P,  Last_Entity  (Old_P));
1260          Set_First_Private_Entity (New_P, First_Private_Entity (Old_P));
1261          Check_Library_Unit_Renaming (N, Old_P);
1262          Generate_Reference (Old_P, Name (N));
1263
1264          --  If the renaming is in the visible part of a package, then we set
1265          --  Renamed_In_Spec for the renamed package, to prevent giving
1266          --  warnings about no entities referenced. Such a warning would be
1267          --  overenthusiastic, since clients can see entities in the renamed
1268          --  package via the visible package renaming.
1269
1270          declare
1271             Ent : constant Entity_Id := Cunit_Entity (Current_Sem_Unit);
1272          begin
1273             if Ekind (Ent) = E_Package
1274               and then not In_Private_Part (Ent)
1275               and then In_Extended_Main_Source_Unit (N)
1276               and then Ekind (Old_P) = E_Package
1277             then
1278                Set_Renamed_In_Spec (Old_P);
1279             end if;
1280          end;
1281
1282          --  If this is the renaming declaration of a package instantiation
1283          --  within itself, it is the declaration that ends the list of actuals
1284          --  for the instantiation. At this point, the subtypes that rename
1285          --  the actuals are flagged as generic, to avoid spurious ambiguities
1286          --  if the actuals for two distinct formals happen to coincide. If
1287          --  the actual is a private type, the subtype has a private completion
1288          --  that is flagged in the same fashion.
1289
1290          --  Resolution is identical to what is was in the original generic.
1291          --  On exit from the generic instance, these are turned into regular
1292          --  subtypes again, so they are compatible with types in their class.
1293
1294          if not Is_Generic_Instance (Old_P) then
1295             return;
1296          else
1297             Spec := Specification (Unit_Declaration_Node (Old_P));
1298          end if;
1299
1300          if Nkind (Spec) = N_Package_Specification
1301            and then Present (Generic_Parent (Spec))
1302            and then Old_P = Current_Scope
1303            and then Chars (New_P) = Chars (Generic_Parent (Spec))
1304          then
1305             declare
1306                E : Entity_Id;
1307
1308             begin
1309                E := First_Entity (Old_P);
1310                while Present (E)
1311                  and then E /= New_P
1312                loop
1313                   if Is_Type (E)
1314                     and then Nkind (Parent (E)) = N_Subtype_Declaration
1315                   then
1316                      Set_Is_Generic_Actual_Type (E);
1317
1318                      if Is_Private_Type (E)
1319                        and then Present (Full_View (E))
1320                      then
1321                         Set_Is_Generic_Actual_Type (Full_View (E));
1322                      end if;
1323                   end if;
1324
1325                   Next_Entity (E);
1326                end loop;
1327             end;
1328          end if;
1329       end if;
1330    end Analyze_Package_Renaming;
1331
1332    -------------------------------
1333    -- Analyze_Renamed_Character --
1334    -------------------------------
1335
1336    procedure Analyze_Renamed_Character
1337      (N       : Node_Id;
1338       New_S   : Entity_Id;
1339       Is_Body : Boolean)
1340    is
1341       C : constant Node_Id := Name (N);
1342
1343    begin
1344       if Ekind (New_S) = E_Function then
1345          Resolve (C, Etype (New_S));
1346
1347          if Is_Body then
1348             Check_Frozen_Renaming (N, New_S);
1349          end if;
1350
1351       else
1352          Error_Msg_N ("character literal can only be renamed as function", N);
1353       end if;
1354    end Analyze_Renamed_Character;
1355
1356    ---------------------------------
1357    -- Analyze_Renamed_Dereference --
1358    ---------------------------------
1359
1360    procedure Analyze_Renamed_Dereference
1361      (N       : Node_Id;
1362       New_S   : Entity_Id;
1363       Is_Body : Boolean)
1364    is
1365       Nam : constant Node_Id := Name (N);
1366       P   : constant Node_Id := Prefix (Nam);
1367       Typ : Entity_Id;
1368       Ind : Interp_Index;
1369       It  : Interp;
1370
1371    begin
1372       if not Is_Overloaded (P) then
1373          if Ekind (Etype (Nam)) /= E_Subprogram_Type
1374            or else not Type_Conformant (Etype (Nam), New_S)
1375          then
1376             Error_Msg_N ("designated type does not match specification", P);
1377          else
1378             Resolve (P);
1379          end if;
1380
1381          return;
1382
1383       else
1384          Typ := Any_Type;
1385          Get_First_Interp (Nam, Ind, It);
1386
1387          while Present (It.Nam) loop
1388
1389             if Ekind (It.Nam) = E_Subprogram_Type
1390               and then Type_Conformant (It.Nam, New_S)
1391             then
1392                if Typ /= Any_Id then
1393                   Error_Msg_N ("ambiguous renaming", P);
1394                   return;
1395                else
1396                   Typ := It.Nam;
1397                end if;
1398             end if;
1399
1400             Get_Next_Interp (Ind, It);
1401          end loop;
1402
1403          if Typ = Any_Type then
1404             Error_Msg_N ("designated type does not match specification", P);
1405          else
1406             Resolve (N, Typ);
1407
1408             if Is_Body then
1409                Check_Frozen_Renaming (N, New_S);
1410             end if;
1411          end if;
1412       end if;
1413    end Analyze_Renamed_Dereference;
1414
1415    ---------------------------
1416    -- Analyze_Renamed_Entry --
1417    ---------------------------
1418
1419    procedure Analyze_Renamed_Entry
1420      (N       : Node_Id;
1421       New_S   : Entity_Id;
1422       Is_Body : Boolean)
1423    is
1424       Nam   : constant Node_Id := Name (N);
1425       Sel   : constant Node_Id := Selector_Name (Nam);
1426       Old_S : Entity_Id;
1427
1428    begin
1429       if Entity (Sel) = Any_Id then
1430
1431          --  Selector is undefined on prefix. Error emitted already
1432
1433          Set_Has_Completion (New_S);
1434          return;
1435       end if;
1436
1437       --  Otherwise find renamed entity and build body of New_S as a call to it
1438
1439       Old_S := Find_Renamed_Entity (N, Selector_Name (Nam), New_S);
1440
1441       if Old_S = Any_Id then
1442          Error_Msg_N (" no subprogram or entry matches specification",  N);
1443       else
1444          if Is_Body then
1445             Check_Subtype_Conformant (New_S, Old_S, N);
1446             Generate_Reference (New_S, Defining_Entity (N), 'b');
1447             Style.Check_Identifier (Defining_Entity (N), New_S);
1448
1449          else
1450             --  Only mode conformance required for a renaming_as_declaration
1451
1452             Check_Mode_Conformant (New_S, Old_S, N);
1453          end if;
1454
1455          Inherit_Renamed_Profile (New_S, Old_S);
1456
1457          --  The prefix can be an arbitrary expression that yields a task type,
1458          --  so it must be resolved.
1459
1460          Resolve (Prefix (Nam), Scope (Old_S));
1461       end if;
1462
1463       Set_Convention (New_S, Convention (Old_S));
1464       Set_Has_Completion (New_S, Inside_A_Generic);
1465
1466       if Is_Body then
1467          Check_Frozen_Renaming (N, New_S);
1468       end if;
1469    end Analyze_Renamed_Entry;
1470
1471    -----------------------------------
1472    -- Analyze_Renamed_Family_Member --
1473    -----------------------------------
1474
1475    procedure Analyze_Renamed_Family_Member
1476      (N       : Node_Id;
1477       New_S   : Entity_Id;
1478       Is_Body : Boolean)
1479    is
1480       Nam   : constant Node_Id := Name (N);
1481       P     : constant Node_Id := Prefix (Nam);
1482       Old_S : Entity_Id;
1483
1484    begin
1485       if (Is_Entity_Name (P) and then Ekind (Entity (P)) = E_Entry_Family)
1486         or else (Nkind (P) = N_Selected_Component
1487                    and then
1488                  Ekind (Entity (Selector_Name (P))) = E_Entry_Family)
1489       then
1490          if Is_Entity_Name (P) then
1491             Old_S := Entity (P);
1492          else
1493             Old_S := Entity (Selector_Name (P));
1494          end if;
1495
1496          if not Entity_Matches_Spec (Old_S, New_S) then
1497             Error_Msg_N ("entry family does not match specification", N);
1498
1499          elsif Is_Body then
1500             Check_Subtype_Conformant (New_S, Old_S, N);
1501             Generate_Reference (New_S, Defining_Entity (N), 'b');
1502             Style.Check_Identifier (Defining_Entity (N), New_S);
1503          end if;
1504
1505       else
1506          Error_Msg_N ("no entry family matches specification", N);
1507       end if;
1508
1509       Set_Has_Completion (New_S, Inside_A_Generic);
1510
1511       if Is_Body then
1512          Check_Frozen_Renaming (N, New_S);
1513       end if;
1514    end Analyze_Renamed_Family_Member;
1515
1516    -----------------------------------------
1517    -- Analyze_Renamed_Primitive_Operation --
1518    -----------------------------------------
1519
1520    procedure Analyze_Renamed_Primitive_Operation
1521      (N       : Node_Id;
1522       New_S   : Entity_Id;
1523       Is_Body : Boolean)
1524    is
1525       Old_S : Entity_Id;
1526
1527       function Conforms
1528         (Subp : Entity_Id;
1529          Ctyp : Conformance_Type) return Boolean;
1530       --  Verify that the signatures of the renamed entity and the new entity
1531       --  match. The first formal of the renamed entity is skipped because it
1532       --  is the target object in any subsequent call.
1533
1534       function Conforms
1535         (Subp : Entity_Id;
1536          Ctyp : Conformance_Type) return Boolean
1537       is
1538          Old_F : Entity_Id;
1539          New_F : Entity_Id;
1540
1541       begin
1542          if Ekind (Subp) /= Ekind (New_S) then
1543             return False;
1544          end if;
1545
1546          Old_F := Next_Formal (First_Formal (Subp));
1547          New_F := First_Formal (New_S);
1548          while Present (Old_F) and then Present (New_F) loop
1549             if not Conforming_Types (Etype (Old_F), Etype (New_F), Ctyp) then
1550                return False;
1551             end if;
1552
1553             if Ctyp >= Mode_Conformant
1554               and then Ekind (Old_F) /= Ekind (New_F)
1555             then
1556                return False;
1557             end if;
1558
1559             Next_Formal (New_F);
1560             Next_Formal (Old_F);
1561          end loop;
1562
1563          return True;
1564       end Conforms;
1565
1566    begin
1567       if not Is_Overloaded (Selector_Name (Name (N))) then
1568          Old_S := Entity (Selector_Name (Name (N)));
1569
1570          if not Conforms (Old_S, Type_Conformant) then
1571             Old_S := Any_Id;
1572          end if;
1573
1574       else
1575          --  Find the operation that matches the given signature
1576
1577          declare
1578             It  : Interp;
1579             Ind : Interp_Index;
1580
1581          begin
1582             Old_S := Any_Id;
1583             Get_First_Interp (Selector_Name (Name (N)), Ind, It);
1584
1585             while Present (It.Nam) loop
1586                if Conforms (It.Nam, Type_Conformant) then
1587                   Old_S := It.Nam;
1588                end if;
1589
1590                Get_Next_Interp (Ind, It);
1591             end loop;
1592          end;
1593       end if;
1594
1595       if Old_S = Any_Id then
1596          Error_Msg_N (" no subprogram or entry matches specification",  N);
1597
1598       else
1599          if Is_Body then
1600             if not Conforms (Old_S, Subtype_Conformant) then
1601                Error_Msg_N ("subtype conformance error in renaming", N);
1602             end if;
1603
1604             Generate_Reference (New_S, Defining_Entity (N), 'b');
1605             Style.Check_Identifier (Defining_Entity (N), New_S);
1606
1607          else
1608             --  Only mode conformance required for a renaming_as_declaration
1609
1610             if not Conforms (Old_S, Mode_Conformant) then
1611                Error_Msg_N ("mode conformance error in renaming", N);
1612             end if;
1613          end if;
1614
1615          --  Inherit_Renamed_Profile (New_S, Old_S);
1616
1617          --  The prefix can be an arbitrary expression that yields an
1618          --  object, so it must be resolved.
1619
1620          Resolve (Prefix (Name (N)));
1621       end if;
1622    end Analyze_Renamed_Primitive_Operation;
1623
1624    ---------------------------------
1625    -- Analyze_Subprogram_Renaming --
1626    ---------------------------------
1627
1628    procedure Analyze_Subprogram_Renaming (N : Node_Id) is
1629       Formal_Spec : constant Node_Id := Corresponding_Formal_Spec (N);
1630       Is_Actual   : constant Boolean := Present (Formal_Spec);
1631
1632       CW_Actual : Boolean := False;
1633       --  True if the renaming is for a defaulted formal subprogram when the
1634       --  actual for a related formal type is class-wide. For AI05-0071.
1635
1636       Inst_Node   : Node_Id                   := Empty;
1637       Nam         : constant Node_Id          := Name (N);
1638       New_S       : Entity_Id;
1639       Old_S       : Entity_Id                 := Empty;
1640       Rename_Spec : Entity_Id;
1641       Save_AV     : constant Ada_Version_Type := Ada_Version;
1642       Save_AV_Exp : constant Ada_Version_Type := Ada_Version_Explicit;
1643       Spec        : constant Node_Id          := Specification (N);
1644
1645       procedure Check_Null_Exclusion
1646         (Ren : Entity_Id;
1647          Sub : Entity_Id);
1648       --  Ada 2005 (AI-423): Given renaming Ren of subprogram Sub, check the
1649       --  following AI rules:
1650       --
1651       --    If Ren is a renaming of a formal subprogram and one of its
1652       --    parameters has a null exclusion, then the corresponding formal
1653       --    in Sub must also have one. Otherwise the subtype of the Sub's
1654       --    formal parameter must exclude null.
1655       --
1656       --    If Ren is a renaming of a formal function and its return
1657       --    profile has a null exclusion, then Sub's return profile must
1658       --    have one. Otherwise the subtype of Sub's return profile must
1659       --    exclude null.
1660
1661       function Original_Subprogram (Subp : Entity_Id) return Entity_Id;
1662       --  Find renamed entity when the declaration is a renaming_as_body and
1663       --  the renamed entity may itself be a renaming_as_body. Used to enforce
1664       --  rule that a renaming_as_body is illegal if the declaration occurs
1665       --  before the subprogram it completes is frozen, and renaming indirectly
1666       --  renames the subprogram itself.(Defect Report 8652/0027).
1667
1668       function Check_Class_Wide_Actual return Entity_Id;
1669       --  AI05-0071: In an instance, if the actual for a formal type FT with
1670       --  unknown discriminants is a class-wide type CT, and the generic has
1671       --  a formal subprogram with a box for a primitive operation of FT,
1672       --  then the corresponding actual subprogram denoted by the default is a
1673       --  class-wide operation whose body is a dispatching call. We replace the
1674       --  generated renaming declaration:
1675       --
1676       --    procedure P (X : CT) renames P;
1677       --
1678       --  by a different renaming and a class-wide operation:
1679       --
1680       --    procedure Pr (X : T) renames P;   --  renames primitive operation
1681       --    procedure P (X : CT);             --  class-wide operation
1682       --    ...
1683       --    procedure P (X : CT) is begin Pr (X); end;  -- dispatching call
1684       --
1685       --  This rule only applies if there is no explicit visible class-wide
1686       --  operation at the point of the instantiation.
1687
1688       -----------------------------
1689       -- Check_Class_Wide_Actual --
1690       -----------------------------
1691
1692       function Check_Class_Wide_Actual return Entity_Id is
1693          Loc : constant Source_Ptr := Sloc (N);
1694
1695          F           : Entity_Id;
1696          Formal_Type : Entity_Id;
1697          Actual_Type : Entity_Id;
1698          New_Body    : Node_Id;
1699          New_Decl    : Node_Id;
1700          Result      : Entity_Id;
1701
1702          function Make_Call (Prim_Op : Entity_Id) return Node_Id;
1703          --  Build dispatching call for body of class-wide operation
1704
1705          function Make_Spec return Node_Id;
1706          --  Create subprogram specification for declaration and body of
1707          --  class-wide operation, using signature of renaming declaration.
1708
1709          ---------------
1710          -- Make_Call --
1711          ---------------
1712
1713          function Make_Call (Prim_Op : Entity_Id) return Node_Id is
1714             Actuals : List_Id;
1715             F       : Node_Id;
1716
1717          begin
1718             Actuals := New_List;
1719             F := First (Parameter_Specifications (Specification (New_Decl)));
1720             while Present (F) loop
1721                Append_To (Actuals,
1722                  Make_Identifier (Loc, Chars (Defining_Identifier (F))));
1723                Next (F);
1724             end loop;
1725
1726             if Ekind (Prim_Op) = E_Function then
1727                return Make_Simple_Return_Statement (Loc,
1728                   Expression =>
1729                     Make_Function_Call (Loc,
1730                       Name => New_Occurrence_Of (Prim_Op, Loc),
1731                       Parameter_Associations => Actuals));
1732             else
1733                return
1734                  Make_Procedure_Call_Statement (Loc,
1735                       Name => New_Occurrence_Of (Prim_Op, Loc),
1736                       Parameter_Associations => Actuals);
1737             end if;
1738          end Make_Call;
1739
1740          ---------------
1741          -- Make_Spec --
1742          ---------------
1743
1744          function Make_Spec return Node_Id is
1745             Param_Specs : constant List_Id := Copy_Parameter_List (New_S);
1746
1747          begin
1748             if Ekind (New_S) = E_Procedure then
1749                return
1750                  Make_Procedure_Specification (Loc,
1751                    Defining_Unit_Name =>
1752                      Make_Defining_Identifier (Loc,
1753                        Chars (Defining_Unit_Name (Spec))),
1754                    Parameter_Specifications => Param_Specs);
1755             else
1756                return
1757                   Make_Function_Specification (Loc,
1758                     Defining_Unit_Name =>
1759                       Make_Defining_Identifier (Loc,
1760                         Chars (Defining_Unit_Name (Spec))),
1761                     Parameter_Specifications => Param_Specs,
1762                     Result_Definition =>
1763                       New_Copy_Tree (Result_Definition (Spec)));
1764             end if;
1765          end Make_Spec;
1766
1767       --  Start of processing for Check_Class_Wide_Actual
1768
1769       begin
1770          Result := Any_Id;
1771          Formal_Type := Empty;
1772          Actual_Type := Empty;
1773
1774          F := First_Formal (Formal_Spec);
1775          while Present (F) loop
1776             if Has_Unknown_Discriminants (Etype (F))
1777               and then Is_Class_Wide_Type (Get_Instance_Of (Etype (F)))
1778             then
1779                Formal_Type := Etype (F);
1780                Actual_Type := Etype (Get_Instance_Of (Formal_Type));
1781                exit;
1782             end if;
1783
1784             Next_Formal (F);
1785          end loop;
1786
1787          if Present (Formal_Type) then
1788             CW_Actual := True;
1789
1790             --  Create declaration and body for class-wide operation
1791
1792             New_Decl :=
1793               Make_Subprogram_Declaration (Loc, Specification => Make_Spec);
1794
1795             New_Body :=
1796               Make_Subprogram_Body (Loc,
1797                 Specification => Make_Spec,
1798                 Declarations => No_List,
1799                 Handled_Statement_Sequence =>
1800                   Make_Handled_Sequence_Of_Statements (Loc, New_List));
1801
1802             --  Modify Spec and create internal name for renaming of primitive
1803             --  operation.
1804
1805             Set_Defining_Unit_Name (Spec, Make_Temporary (Loc, 'R'));
1806             F := First (Parameter_Specifications (Spec));
1807             while Present (F) loop
1808                if Nkind (Parameter_Type (F)) = N_Identifier
1809                  and then Is_Class_Wide_Type (Entity (Parameter_Type (F)))
1810                then
1811                   Set_Parameter_Type (F, New_Occurrence_Of (Actual_Type, Loc));
1812                end if;
1813                Next (F);
1814             end loop;
1815
1816             New_S := Analyze_Subprogram_Specification (Spec);
1817             Result :=  Find_Renamed_Entity (N, Name (N), New_S, Is_Actual);
1818          end if;
1819
1820          if Result /= Any_Id then
1821             Insert_Before (N, New_Decl);
1822             Analyze (New_Decl);
1823
1824             --  Add dispatching call to body of class-wide operation
1825
1826             Append (Make_Call (Result),
1827               Statements (Handled_Statement_Sequence (New_Body)));
1828
1829             --  The generated body does not freeze. It is analyzed when the
1830             --  generated operation is frozen.
1831
1832             Append_Freeze_Action (Defining_Entity (New_Decl), New_Body);
1833
1834             Result := Defining_Entity (New_Decl);
1835          end if;
1836
1837          --  Return the class-wide operation if one was created
1838
1839          return Result;
1840       end Check_Class_Wide_Actual;
1841
1842       --------------------------
1843       -- Check_Null_Exclusion --
1844       --------------------------
1845
1846       procedure Check_Null_Exclusion
1847         (Ren : Entity_Id;
1848          Sub : Entity_Id)
1849       is
1850          Ren_Formal : Entity_Id;
1851          Sub_Formal : Entity_Id;
1852
1853       begin
1854          --  Parameter check
1855
1856          Ren_Formal := First_Formal (Ren);
1857          Sub_Formal := First_Formal (Sub);
1858          while Present (Ren_Formal)
1859            and then Present (Sub_Formal)
1860          loop
1861             if Has_Null_Exclusion (Parent (Ren_Formal))
1862               and then
1863                 not (Has_Null_Exclusion (Parent (Sub_Formal))
1864                        or else Can_Never_Be_Null (Etype (Sub_Formal)))
1865             then
1866                Error_Msg_NE
1867                  ("`NOT NULL` required for parameter &",
1868                   Parent (Sub_Formal), Sub_Formal);
1869             end if;
1870
1871             Next_Formal (Ren_Formal);
1872             Next_Formal (Sub_Formal);
1873          end loop;
1874
1875          --  Return profile check
1876
1877          if Nkind (Parent (Ren)) = N_Function_Specification
1878            and then Nkind (Parent (Sub)) = N_Function_Specification
1879            and then Has_Null_Exclusion (Parent (Ren))
1880            and then
1881              not (Has_Null_Exclusion (Parent (Sub))
1882                     or else Can_Never_Be_Null (Etype (Sub)))
1883          then
1884             Error_Msg_N
1885               ("return must specify `NOT NULL`",
1886                Result_Definition (Parent (Sub)));
1887          end if;
1888       end Check_Null_Exclusion;
1889
1890       -------------------------
1891       -- Original_Subprogram --
1892       -------------------------
1893
1894       function Original_Subprogram (Subp : Entity_Id) return Entity_Id is
1895          Orig_Decl : Node_Id;
1896          Orig_Subp : Entity_Id;
1897
1898       begin
1899          --  First case: renamed entity is itself a renaming
1900
1901          if Present (Alias (Subp)) then
1902             return Alias (Subp);
1903
1904          elsif
1905            Nkind (Unit_Declaration_Node (Subp)) = N_Subprogram_Declaration
1906              and then Present
1907               (Corresponding_Body (Unit_Declaration_Node (Subp)))
1908          then
1909             --  Check if renamed entity is a renaming_as_body
1910
1911             Orig_Decl :=
1912               Unit_Declaration_Node
1913                 (Corresponding_Body (Unit_Declaration_Node (Subp)));
1914
1915             if Nkind (Orig_Decl) = N_Subprogram_Renaming_Declaration then
1916                Orig_Subp := Entity (Name (Orig_Decl));
1917
1918                if Orig_Subp = Rename_Spec then
1919
1920                   --  Circularity detected
1921
1922                   return Orig_Subp;
1923
1924                else
1925                   return (Original_Subprogram (Orig_Subp));
1926                end if;
1927             else
1928                return Subp;
1929             end if;
1930          else
1931             return Subp;
1932          end if;
1933       end Original_Subprogram;
1934
1935    --  Start of processing for Analyze_Subprogram_Renaming
1936
1937    begin
1938       --  We must test for the attribute renaming case before the Analyze
1939       --  call because otherwise Sem_Attr will complain that the attribute
1940       --  is missing an argument when it is analyzed.
1941
1942       if Nkind (Nam) = N_Attribute_Reference then
1943
1944          --  In the case of an abstract formal subprogram association, rewrite
1945          --  an actual given by a stream attribute as the name of the
1946          --  corresponding stream primitive of the type.
1947
1948          --  In a generic context the stream operations are not generated, and
1949          --  this must be treated as a normal attribute reference, to be
1950          --  expanded in subsequent instantiations.
1951
1952          if Is_Actual and then Is_Abstract_Subprogram (Formal_Spec)
1953            and then Expander_Active
1954          then
1955             declare
1956                Stream_Prim : Entity_Id;
1957                Prefix_Type : constant Entity_Id := Entity (Prefix (Nam));
1958
1959             begin
1960                --  The class-wide forms of the stream attributes are not
1961                --  primitive dispatching operations (even though they
1962                --  internally dispatch to a stream attribute).
1963
1964                if Is_Class_Wide_Type (Prefix_Type) then
1965                   Error_Msg_N
1966                     ("attribute must be a primitive dispatching operation",
1967                      Nam);
1968                   return;
1969                end if;
1970
1971                --  Retrieve the primitive subprogram associated with the
1972                --  attribute. This can only be a stream attribute, since those
1973                --  are the only ones that are dispatching (and the actual for
1974                --  an abstract formal subprogram must be dispatching
1975                --  operation).
1976
1977                begin
1978                   case Attribute_Name (Nam) is
1979                      when Name_Input  =>
1980                         Stream_Prim :=
1981                           Find_Prim_Op (Prefix_Type, TSS_Stream_Input);
1982                      when Name_Output =>
1983                         Stream_Prim :=
1984                           Find_Prim_Op (Prefix_Type, TSS_Stream_Output);
1985                      when Name_Read   =>
1986                         Stream_Prim :=
1987                           Find_Prim_Op (Prefix_Type, TSS_Stream_Read);
1988                      when Name_Write  =>
1989                         Stream_Prim :=
1990                           Find_Prim_Op (Prefix_Type, TSS_Stream_Write);
1991                      when others      =>
1992                         Error_Msg_N
1993                           ("attribute must be a primitive"
1994                             & " dispatching operation", Nam);
1995                         return;
1996                   end case;
1997
1998                exception
1999
2000                   --  If no operation was found, and the type is limited,
2001                   --  the user should have defined one.
2002
2003                   when Program_Error =>
2004                      if Is_Limited_Type (Prefix_Type) then
2005                         Error_Msg_NE
2006                          ("stream operation not defined for type&",
2007                            N, Prefix_Type);
2008                         return;
2009
2010                      --  Otherwise, compiler should have generated default
2011
2012                      else
2013                         raise;
2014                      end if;
2015                end;
2016
2017                --  Rewrite the attribute into the name of its corresponding
2018                --  primitive dispatching subprogram. We can then proceed with
2019                --  the usual processing for subprogram renamings.
2020
2021                declare
2022                   Prim_Name : constant Node_Id :=
2023                                 Make_Identifier (Sloc (Nam),
2024                                   Chars => Chars (Stream_Prim));
2025                begin
2026                   Set_Entity (Prim_Name, Stream_Prim);
2027                   Rewrite (Nam, Prim_Name);
2028                   Analyze (Nam);
2029                end;
2030             end;
2031
2032          --  Normal processing for a renaming of an attribute
2033
2034          else
2035             Attribute_Renaming (N);
2036             return;
2037          end if;
2038       end if;
2039
2040       --  Check whether this declaration corresponds to the instantiation
2041       --  of a formal subprogram.
2042
2043       --  If this is an instantiation, the corresponding actual is frozen and
2044       --  error messages can be made more precise. If this is a default
2045       --  subprogram, the entity is already established in the generic, and is
2046       --  not retrieved by visibility. If it is a default with a box, the
2047       --  candidate interpretations, if any, have been collected when building
2048       --  the renaming declaration. If overloaded, the proper interpretation is
2049       --  determined in Find_Renamed_Entity. If the entity is an operator,
2050       --  Find_Renamed_Entity applies additional visibility checks.
2051
2052       if Is_Actual then
2053          Inst_Node := Unit_Declaration_Node (Formal_Spec);
2054
2055          if Is_Entity_Name (Nam)
2056            and then Present (Entity (Nam))
2057            and then not Comes_From_Source (Nam)
2058            and then not Is_Overloaded (Nam)
2059          then
2060             Old_S := Entity (Nam);
2061             New_S := Analyze_Subprogram_Specification (Spec);
2062
2063             --  Operator case
2064
2065             if Ekind (Entity (Nam)) = E_Operator then
2066
2067                --  Box present
2068
2069                if Box_Present (Inst_Node) then
2070                   Old_S := Find_Renamed_Entity (N, Name (N), New_S, Is_Actual);
2071
2072                --  If there is an immediately visible homonym of the operator
2073                --  and the declaration has a default, this is worth a warning
2074                --  because the user probably did not intend to get the pre-
2075                --  defined operator, visible in the generic declaration. To
2076                --  find if there is an intended candidate, analyze the renaming
2077                --  again in the current context.
2078
2079                elsif Scope (Old_S) = Standard_Standard
2080                  and then Present (Default_Name (Inst_Node))
2081                then
2082                   declare
2083                      Decl   : constant Node_Id := New_Copy_Tree (N);
2084                      Hidden : Entity_Id;
2085
2086                   begin
2087                      Set_Entity (Name (Decl), Empty);
2088                      Analyze (Name (Decl));
2089                      Hidden :=
2090                        Find_Renamed_Entity (Decl, Name (Decl), New_S, True);
2091
2092                      if Present (Hidden)
2093                        and then In_Open_Scopes (Scope (Hidden))
2094                        and then Is_Immediately_Visible (Hidden)
2095                        and then Comes_From_Source (Hidden)
2096                        and then Hidden /= Old_S
2097                      then
2098                         Error_Msg_Sloc := Sloc (Hidden);
2099                         Error_Msg_N ("?default subprogram is resolved " &
2100                                      "in the generic declaration " &
2101                                      "(RM 12.6(17))", N);
2102                         Error_Msg_NE ("\?and will not use & #", N, Hidden);
2103                      end if;
2104                   end;
2105                end if;
2106             end if;
2107
2108          else
2109             Analyze (Nam);
2110             New_S := Analyze_Subprogram_Specification (Spec);
2111          end if;
2112
2113       else
2114          --  Renamed entity must be analyzed first, to avoid being hidden by
2115          --  new name (which might be the same in a generic instance).
2116
2117          Analyze (Nam);
2118
2119          --  The renaming defines a new overloaded entity, which is analyzed
2120          --  like a subprogram declaration.
2121
2122          New_S := Analyze_Subprogram_Specification (Spec);
2123       end if;
2124
2125       if Current_Scope /= Standard_Standard then
2126          Set_Is_Pure (New_S, Is_Pure (Current_Scope));
2127       end if;
2128
2129       Rename_Spec := Find_Corresponding_Spec (N);
2130
2131       --  Case of Renaming_As_Body
2132
2133       if Present (Rename_Spec) then
2134
2135          --  Renaming declaration is the completion of the declaration of
2136          --  Rename_Spec. We build an actual body for it at the freezing point.
2137
2138          Set_Corresponding_Spec (N, Rename_Spec);
2139
2140          --  Deal with special case of stream functions of abstract types
2141          --  and interfaces.
2142
2143          if Nkind (Unit_Declaration_Node (Rename_Spec)) =
2144                                      N_Abstract_Subprogram_Declaration
2145          then
2146             --  Input stream functions are abstract if the object type is
2147             --  abstract. Similarly, all default stream functions for an
2148             --  interface type are abstract. However, these subprograms may
2149             --  receive explicit declarations in representation clauses, making
2150             --  the attribute subprograms usable as defaults in subsequent
2151             --  type extensions.
2152             --  In this case we rewrite the declaration to make the subprogram
2153             --  non-abstract. We remove the previous declaration, and insert
2154             --  the new one at the point of the renaming, to prevent premature
2155             --  access to unfrozen types. The new declaration reuses the
2156             --  specification of the previous one, and must not be analyzed.
2157
2158             pragma Assert
2159               (Is_Primitive (Entity (Nam))
2160                  and then
2161                    Is_Abstract_Type (Find_Dispatching_Type (Entity (Nam))));
2162             declare
2163                Old_Decl : constant Node_Id :=
2164                             Unit_Declaration_Node (Rename_Spec);
2165                New_Decl : constant Node_Id :=
2166                             Make_Subprogram_Declaration (Sloc (N),
2167                               Specification =>
2168                                 Relocate_Node (Specification (Old_Decl)));
2169             begin
2170                Remove (Old_Decl);
2171                Insert_After (N, New_Decl);
2172                Set_Is_Abstract_Subprogram (Rename_Spec, False);
2173                Set_Analyzed (New_Decl);
2174             end;
2175          end if;
2176
2177          Set_Corresponding_Body (Unit_Declaration_Node (Rename_Spec), New_S);
2178
2179          if Ada_Version = Ada_83 and then Comes_From_Source (N) then
2180             Error_Msg_N ("(Ada 83) renaming cannot serve as a body", N);
2181          end if;
2182
2183          Set_Convention (New_S, Convention (Rename_Spec));
2184          Check_Fully_Conformant (New_S, Rename_Spec);
2185          Set_Public_Status (New_S);
2186
2187          --  The specification does not introduce new formals, but only
2188          --  repeats the formals of the original subprogram declaration.
2189          --  For cross-reference purposes, and for refactoring tools, we
2190          --  treat the formals of the renaming declaration as body formals.
2191
2192          Reference_Body_Formals (Rename_Spec, New_S);
2193
2194          --  Indicate that the entity in the declaration functions like the
2195          --  corresponding body, and is not a new entity. The body will be
2196          --  constructed later at the freeze point, so indicate that the
2197          --  completion has not been seen yet.
2198
2199          Set_Ekind (New_S, E_Subprogram_Body);
2200          New_S := Rename_Spec;
2201          Set_Has_Completion (Rename_Spec, False);
2202
2203          --  Ada 2005: check overriding indicator
2204
2205          if Present (Overridden_Operation (Rename_Spec)) then
2206             if Must_Not_Override (Specification (N)) then
2207                Error_Msg_NE
2208                  ("subprogram& overrides inherited operation",
2209                     N, Rename_Spec);
2210             elsif
2211               Style_Check and then not Must_Override (Specification (N))
2212             then
2213                Style.Missing_Overriding (N, Rename_Spec);
2214             end if;
2215
2216          elsif Must_Override (Specification (N)) then
2217             Error_Msg_NE ("subprogram& is not overriding", N, Rename_Spec);
2218          end if;
2219
2220       --  Normal subprogram renaming (not renaming as body)
2221
2222       else
2223          Generate_Definition (New_S);
2224          New_Overloaded_Entity (New_S);
2225
2226          if Is_Entity_Name (Nam)
2227            and then Is_Intrinsic_Subprogram (Entity (Nam))
2228          then
2229             null;
2230          else
2231             Check_Delayed_Subprogram (New_S);
2232          end if;
2233       end if;
2234
2235       --  There is no need for elaboration checks on the new entity, which may
2236       --  be called before the next freezing point where the body will appear.
2237       --  Elaboration checks refer to the real entity, not the one created by
2238       --  the renaming declaration.
2239
2240       Set_Kill_Elaboration_Checks (New_S, True);
2241
2242       if Etype (Nam) = Any_Type then
2243          Set_Has_Completion (New_S);
2244          return;
2245
2246       elsif Nkind (Nam) = N_Selected_Component then
2247
2248          --  A prefix of the form  A.B can designate an entry of task A, a
2249          --  protected operation of protected object A, or finally a primitive
2250          --  operation of object A. In the later case, A is an object of some
2251          --  tagged type, or an access type that denotes one such. To further
2252          --  distinguish these cases, note that the scope of a task entry or
2253          --  protected operation is type of the prefix.
2254
2255          --  The prefix could be an overloaded function call that returns both
2256          --  kinds of operations. This overloading pathology is left to the
2257          --  dedicated reader ???
2258
2259          declare
2260             T : constant Entity_Id := Etype (Prefix (Nam));
2261
2262          begin
2263             if Present (T)
2264               and then
2265                 (Is_Tagged_Type (T)
2266                   or else
2267                     (Is_Access_Type (T)
2268                       and then
2269                         Is_Tagged_Type (Designated_Type (T))))
2270               and then Scope (Entity (Selector_Name (Nam))) /= T
2271             then
2272                Analyze_Renamed_Primitive_Operation
2273                  (N, New_S, Present (Rename_Spec));
2274                return;
2275
2276             else
2277                --  Renamed entity is an entry or protected operation. For those
2278                --  cases an explicit body is built (at the point of freezing of
2279                --  this entity) that contains a call to the renamed entity.
2280
2281                --  This is not allowed for renaming as body if the renamed
2282                --  spec is already frozen (see RM 8.5.4(5) for details).
2283
2284                if Present (Rename_Spec)
2285                  and then Is_Frozen (Rename_Spec)
2286                then
2287                   Error_Msg_N
2288                     ("renaming-as-body cannot rename entry as subprogram", N);
2289                   Error_Msg_NE
2290                     ("\since & is already frozen (RM 8.5.4(5))",
2291                      N, Rename_Spec);
2292                else
2293                   Analyze_Renamed_Entry (N, New_S, Present (Rename_Spec));
2294                end if;
2295
2296                return;
2297             end if;
2298          end;
2299
2300       elsif Nkind (Nam) = N_Explicit_Dereference then
2301
2302          --  Renamed entity is designated by access_to_subprogram expression.
2303          --  Must build body to encapsulate call, as in the entry case.
2304
2305          Analyze_Renamed_Dereference (N, New_S, Present (Rename_Spec));
2306          return;
2307
2308       elsif Nkind (Nam) = N_Indexed_Component then
2309          Analyze_Renamed_Family_Member (N, New_S, Present (Rename_Spec));
2310          return;
2311
2312       elsif Nkind (Nam) = N_Character_Literal then
2313          Analyze_Renamed_Character (N, New_S, Present (Rename_Spec));
2314          return;
2315
2316       elsif not Is_Entity_Name (Nam)
2317         or else not Is_Overloadable (Entity (Nam))
2318       then
2319          Error_Msg_N ("expect valid subprogram name in renaming", N);
2320          return;
2321       end if;
2322
2323       --  Find the renamed entity that matches the given specification. Disable
2324       --  Ada_83 because there is no requirement of full conformance between
2325       --  renamed entity and new entity, even though the same circuit is used.
2326
2327       --  This is a bit of a kludge, which introduces a really irregular use of
2328       --  Ada_Version[_Explicit]. Would be nice to find cleaner way to do this
2329       --  ???
2330
2331       Ada_Version := Ada_Version_Type'Max (Ada_Version, Ada_95);
2332       Ada_Version_Explicit := Ada_Version;
2333
2334       if No (Old_S) then
2335          Old_S := Find_Renamed_Entity (N, Name (N), New_S, Is_Actual);
2336
2337          --  The visible operation may be an inherited abstract operation that
2338          --  was overridden in the private part, in which case a call will
2339          --  dispatch to the overriding operation. Use the overriding one in
2340          --  the renaming declaration, to prevent spurious errors below.
2341
2342          if Is_Overloadable (Old_S)
2343            and then Is_Abstract_Subprogram (Old_S)
2344            and then No (DTC_Entity (Old_S))
2345            and then Present (Alias (Old_S))
2346            and then not Is_Abstract_Subprogram (Alias (Old_S))
2347            and then Present (Overridden_Operation (Alias (Old_S)))
2348          then
2349             Old_S := Alias (Old_S);
2350          end if;
2351
2352          --  When the renamed subprogram is overloaded and used as an actual
2353          --  of a generic, its entity is set to the first available homonym.
2354          --  We must first disambiguate the name, then set the proper entity.
2355
2356          if Is_Actual and then Is_Overloaded (Nam) then
2357             Set_Entity (Nam, Old_S);
2358          end if;
2359       end if;
2360
2361       --  Most common case: subprogram renames subprogram. No body is generated
2362       --  in this case, so we must indicate the declaration is complete as is.
2363       --  and inherit various attributes of the renamed subprogram.
2364
2365       if No (Rename_Spec) then
2366          Set_Has_Completion   (New_S);
2367          Set_Is_Imported      (New_S, Is_Imported      (Entity (Nam)));
2368          Set_Is_Pure          (New_S, Is_Pure          (Entity (Nam)));
2369          Set_Is_Preelaborated (New_S, Is_Preelaborated (Entity (Nam)));
2370
2371          --  Ada 2005 (AI-423): Check the consistency of null exclusions
2372          --  between a subprogram and its correct renaming.
2373
2374          --  Note: the Any_Id check is a guard that prevents compiler crashes
2375          --  when performing a null exclusion check between a renaming and a
2376          --  renamed subprogram that has been found to be illegal.
2377
2378          if Ada_Version >= Ada_2005
2379            and then Entity (Nam) /= Any_Id
2380          then
2381             Check_Null_Exclusion
2382               (Ren => New_S,
2383                Sub => Entity (Nam));
2384          end if;
2385
2386          --  Enforce the Ada 2005 rule that the renamed entity cannot require
2387          --  overriding. The flag Requires_Overriding is set very selectively
2388          --  and misses some other illegal cases. The additional conditions
2389          --  checked below are sufficient but not necessary ???
2390
2391          --  The rule does not apply to the renaming generated for an actual
2392          --  subprogram in an instance.
2393
2394          if Is_Actual then
2395             null;
2396
2397          --  Guard against previous errors, and omit renamings of predefined
2398          --  operators.
2399
2400          elsif not Ekind_In (Old_S, E_Function, E_Procedure) then
2401             null;
2402
2403          elsif Requires_Overriding (Old_S)
2404            or else
2405               (Is_Abstract_Subprogram (Old_S)
2406                  and then Present (Find_Dispatching_Type (Old_S))
2407                  and then
2408                    not Is_Abstract_Type (Find_Dispatching_Type (Old_S)))
2409          then
2410             Error_Msg_N
2411               ("renamed entity cannot be "
2412                & "subprogram that requires overriding (RM 8.5.4 (5.1))", N);
2413          end if;
2414       end if;
2415
2416       --  If no renamed entity was found, check whether the renaming is for
2417       --  a defaulted actual subprogram with a class-wide actual.
2418
2419       if Old_S = Any_Id
2420         and then Is_Actual
2421         and then From_Default (N)
2422       then
2423          Old_S := Check_Class_Wide_Actual;
2424       end if;
2425
2426       if Old_S /= Any_Id then
2427          if Is_Actual and then From_Default (N) then
2428
2429             --  This is an implicit reference to the default actual
2430
2431             Generate_Reference (Old_S, Nam, Typ => 'i', Force => True);
2432
2433          else
2434             Generate_Reference (Old_S, Nam);
2435          end if;
2436
2437          --  For a renaming-as-body, require subtype conformance, but if the
2438          --  declaration being completed has not been frozen, then inherit the
2439          --  convention of the renamed subprogram prior to checking conformance
2440          --  (unless the renaming has an explicit convention established; the
2441          --  rule stated in the RM doesn't seem to address this ???).
2442
2443          if Present (Rename_Spec) then
2444             Generate_Reference (Rename_Spec, Defining_Entity (Spec), 'b');
2445             Style.Check_Identifier (Defining_Entity (Spec), Rename_Spec);
2446
2447             if not Is_Frozen (Rename_Spec) then
2448                if not Has_Convention_Pragma (Rename_Spec) then
2449                   Set_Convention (New_S, Convention (Old_S));
2450                end if;
2451
2452                if Ekind (Old_S) /= E_Operator then
2453                   Check_Mode_Conformant (New_S, Old_S, Spec);
2454                end if;
2455
2456                if Original_Subprogram (Old_S) = Rename_Spec then
2457                   Error_Msg_N ("unfrozen subprogram cannot rename itself ", N);
2458                end if;
2459             else
2460                Check_Subtype_Conformant (New_S, Old_S, Spec);
2461             end if;
2462
2463             Check_Frozen_Renaming (N, Rename_Spec);
2464
2465             --  Check explicitly that renamed entity is not intrinsic, because
2466             --  in a generic the renamed body is not built. In this case,
2467             --  the renaming_as_body is a completion.
2468
2469             if Inside_A_Generic then
2470                if Is_Frozen (Rename_Spec)
2471                  and then Is_Intrinsic_Subprogram (Old_S)
2472                then
2473                   Error_Msg_N
2474                     ("subprogram in renaming_as_body cannot be intrinsic",
2475                        Name (N));
2476                end if;
2477
2478                Set_Has_Completion (Rename_Spec);
2479             end if;
2480
2481          elsif Ekind (Old_S) /= E_Operator then
2482
2483             --  If this a defaulted subprogram for a class-wide actual there is
2484             --  no check for mode conformance,  given that the signatures don't
2485             --  match (the source mentions T but the actual mentions T'Class).
2486
2487             if CW_Actual then
2488                null;
2489             else
2490                Check_Mode_Conformant (New_S, Old_S);
2491             end if;
2492
2493             if Is_Actual
2494               and then Error_Posted (New_S)
2495             then
2496                Error_Msg_NE ("invalid actual subprogram: & #!", N, Old_S);
2497             end if;
2498          end if;
2499
2500          if No (Rename_Spec) then
2501
2502             --  The parameter profile of the new entity is that of the renamed
2503             --  entity: the subtypes given in the specification are irrelevant.
2504
2505             Inherit_Renamed_Profile (New_S, Old_S);
2506
2507             --  A call to the subprogram is transformed into a call to the
2508             --  renamed entity. This is transitive if the renamed entity is
2509             --  itself a renaming.
2510
2511             if Present (Alias (Old_S)) then
2512                Set_Alias (New_S, Alias (Old_S));
2513             else
2514                Set_Alias (New_S, Old_S);
2515             end if;
2516
2517             --  Note that we do not set Is_Intrinsic_Subprogram if we have a
2518             --  renaming as body, since the entity in this case is not an
2519             --  intrinsic (it calls an intrinsic, but we have a real body for
2520             --  this call, and it is in this body that the required intrinsic
2521             --  processing will take place).
2522
2523             --  Also, if this is a renaming of inequality, the renamed operator
2524             --  is intrinsic, but what matters is the corresponding equality
2525             --  operator, which may be user-defined.
2526
2527             Set_Is_Intrinsic_Subprogram
2528               (New_S,
2529                 Is_Intrinsic_Subprogram (Old_S)
2530                   and then
2531                     (Chars (Old_S) /= Name_Op_Ne
2532                        or else Ekind (Old_S) = E_Operator
2533                        or else
2534                          Is_Intrinsic_Subprogram
2535                             (Corresponding_Equality (Old_S))));
2536
2537             if Ekind (Alias (New_S)) = E_Operator then
2538                Set_Has_Delayed_Freeze (New_S, False);
2539             end if;
2540
2541             --  If the renaming corresponds to an association for an abstract
2542             --  formal subprogram, then various attributes must be set to
2543             --  indicate that the renaming is an abstract dispatching operation
2544             --  with a controlling type.
2545
2546             if Is_Actual and then Is_Abstract_Subprogram (Formal_Spec) then
2547
2548                --  Mark the renaming as abstract here, so Find_Dispatching_Type
2549                --  see it as corresponding to a generic association for a
2550                --  formal abstract subprogram
2551
2552                Set_Is_Abstract_Subprogram (New_S);
2553
2554                declare
2555                   New_S_Ctrl_Type : constant Entity_Id :=
2556                                       Find_Dispatching_Type (New_S);
2557                   Old_S_Ctrl_Type : constant Entity_Id :=
2558                                       Find_Dispatching_Type (Old_S);
2559
2560                begin
2561                   if Old_S_Ctrl_Type /= New_S_Ctrl_Type then
2562                      Error_Msg_NE
2563                        ("actual must be dispatching subprogram for type&",
2564                         Nam, New_S_Ctrl_Type);
2565
2566                   else
2567                      Set_Is_Dispatching_Operation (New_S);
2568                      Check_Controlling_Formals (New_S_Ctrl_Type, New_S);
2569
2570                      --  If the actual in the formal subprogram is itself a
2571                      --  formal abstract subprogram association, there's no
2572                      --  dispatch table component or position to inherit.
2573
2574                      if Present (DTC_Entity (Old_S)) then
2575                         Set_DTC_Entity  (New_S, DTC_Entity (Old_S));
2576                         Set_DT_Position (New_S, DT_Position (Old_S));
2577                      end if;
2578                   end if;
2579                end;
2580             end if;
2581          end if;
2582
2583          if not Is_Actual
2584            and then (Old_S = New_S
2585                       or else (Nkind (Nam) /= N_Expanded_Name
2586                         and then  Chars (Old_S) = Chars (New_S)))
2587          then
2588             Error_Msg_N ("subprogram cannot rename itself", N);
2589          end if;
2590
2591          Set_Convention (New_S, Convention (Old_S));
2592
2593          if Is_Abstract_Subprogram (Old_S) then
2594             if Present (Rename_Spec) then
2595                Error_Msg_N
2596                  ("a renaming-as-body cannot rename an abstract subprogram",
2597                   N);
2598                Set_Has_Completion (Rename_Spec);
2599             else
2600                Set_Is_Abstract_Subprogram (New_S);
2601             end if;
2602          end if;
2603
2604          Check_Library_Unit_Renaming (N, Old_S);
2605
2606          --  Pathological case: procedure renames entry in the scope of its
2607          --  task. Entry is given by simple name, but body must be built for
2608          --  procedure. Of course if called it will deadlock.
2609
2610          if Ekind (Old_S) = E_Entry then
2611             Set_Has_Completion (New_S, False);
2612             Set_Alias (New_S, Empty);
2613          end if;
2614
2615          if Is_Actual then
2616             Freeze_Before (N, Old_S);
2617             Set_Has_Delayed_Freeze (New_S, False);
2618             Freeze_Before (N, New_S);
2619
2620             --  An abstract subprogram is only allowed as an actual in the case
2621             --  where the formal subprogram is also abstract.
2622
2623             if (Ekind (Old_S) = E_Procedure or else Ekind (Old_S) = E_Function)
2624               and then Is_Abstract_Subprogram (Old_S)
2625               and then not Is_Abstract_Subprogram (Formal_Spec)
2626             then
2627                Error_Msg_N
2628                  ("abstract subprogram not allowed as generic actual", Nam);
2629             end if;
2630          end if;
2631
2632       else
2633          --  A common error is to assume that implicit operators for types are
2634          --  defined in Standard, or in the scope of a subtype. In those cases
2635          --  where the renamed entity is given with an expanded name, it is
2636          --  worth mentioning that operators for the type are not declared in
2637          --  the scope given by the prefix.
2638
2639          if Nkind (Nam) = N_Expanded_Name
2640            and then Nkind (Selector_Name (Nam)) = N_Operator_Symbol
2641            and then Scope (Entity (Nam)) = Standard_Standard
2642          then
2643             declare
2644                T : constant Entity_Id :=
2645                      Base_Type (Etype (First_Formal (New_S)));
2646             begin
2647                Error_Msg_Node_2 := Prefix (Nam);
2648                Error_Msg_NE
2649                  ("operator for type& is not declared in&", Prefix (Nam), T);
2650             end;
2651
2652          else
2653             Error_Msg_NE
2654               ("no visible subprogram matches the specification for&",
2655                 Spec, New_S);
2656          end if;
2657
2658          if Present (Candidate_Renaming) then
2659             declare
2660                F1 : Entity_Id;
2661                F2 : Entity_Id;
2662                T1 : Entity_Id;
2663
2664             begin
2665                F1 := First_Formal (Candidate_Renaming);
2666                F2 := First_Formal (New_S);
2667                T1 := First_Subtype (Etype (F1));
2668
2669                while Present (F1) and then Present (F2) loop
2670                   Next_Formal (F1);
2671                   Next_Formal (F2);
2672                end loop;
2673
2674                if Present (F1) and then Present (Default_Value (F1)) then
2675                   if Present (Next_Formal (F1)) then
2676                      Error_Msg_NE
2677                        ("\missing specification for &" &
2678                           " and other formals with defaults", Spec, F1);
2679                   else
2680                      Error_Msg_NE
2681                     ("\missing specification for &", Spec, F1);
2682                   end if;
2683                end if;
2684
2685                if Nkind (Nam) = N_Operator_Symbol
2686                  and then From_Default (N)
2687                then
2688                   Error_Msg_Node_2 := T1;
2689                   Error_Msg_NE
2690                     ("default & on & is not directly visible",
2691                       Nam, Nam);
2692                end if;
2693             end;
2694          end if;
2695       end if;
2696
2697       --  Ada 2005 AI 404: if the new subprogram is dispatching, verify that
2698       --  controlling access parameters are known non-null for the renamed
2699       --  subprogram. Test also applies to a subprogram instantiation that
2700       --  is dispatching. Test is skipped if some previous error was detected
2701       --  that set Old_S to Any_Id.
2702
2703       if Ada_Version >= Ada_2005
2704         and then Old_S /= Any_Id
2705         and then not Is_Dispatching_Operation (Old_S)
2706         and then Is_Dispatching_Operation (New_S)
2707       then
2708          declare
2709             Old_F : Entity_Id;
2710             New_F : Entity_Id;
2711
2712          begin
2713             Old_F := First_Formal (Old_S);
2714             New_F := First_Formal (New_S);
2715             while Present (Old_F) loop
2716                if Ekind (Etype (Old_F)) = E_Anonymous_Access_Type
2717                  and then Is_Controlling_Formal (New_F)
2718                  and then not Can_Never_Be_Null (Old_F)
2719                then
2720                   Error_Msg_N ("access parameter is controlling,", New_F);
2721                   Error_Msg_NE
2722                     ("\corresponding parameter of& "
2723                      & "must be explicitly null excluding", New_F, Old_S);
2724                end if;
2725
2726                Next_Formal (Old_F);
2727                Next_Formal (New_F);
2728             end loop;
2729          end;
2730       end if;
2731
2732       --  A useful warning, suggested by Ada Bug Finder (Ada-Europe 2005)
2733       --  is to warn if an operator is being renamed as a different operator.
2734       --  If the operator is predefined, examine the kind of the entity, not
2735       --  the abbreviated declaration in Standard.
2736
2737       if Comes_From_Source (N)
2738         and then Present (Old_S)
2739         and then
2740           (Nkind (Old_S) = N_Defining_Operator_Symbol
2741             or else Ekind (Old_S) = E_Operator)
2742         and then Nkind (New_S) = N_Defining_Operator_Symbol
2743         and then Chars (Old_S) /= Chars (New_S)
2744       then
2745          Error_Msg_NE
2746            ("?& is being renamed as a different operator", N, Old_S);
2747       end if;
2748
2749       --  Check for renaming of obsolescent subprogram
2750
2751       Check_Obsolescent_2005_Entity (Entity (Nam), Nam);
2752
2753       --  Another warning or some utility: if the new subprogram as the same
2754       --  name as the old one, the old one is not hidden by an outer homograph,
2755       --  the new one is not a public symbol, and the old one is otherwise
2756       --  directly visible, the renaming is superfluous.
2757
2758       if Chars (Old_S) = Chars (New_S)
2759         and then Comes_From_Source (N)
2760         and then Scope (Old_S) /= Standard_Standard
2761         and then Warn_On_Redundant_Constructs
2762         and then
2763           (Is_Immediately_Visible (Old_S)
2764             or else Is_Potentially_Use_Visible (Old_S))
2765         and then Is_Overloadable (Current_Scope)
2766         and then Chars (Current_Scope) /= Chars (Old_S)
2767       then
2768          Error_Msg_N
2769           ("?redundant renaming, entity is directly visible", Name (N));
2770       end if;
2771
2772       Ada_Version := Save_AV;
2773       Ada_Version_Explicit := Save_AV_Exp;
2774    end Analyze_Subprogram_Renaming;
2775
2776    -------------------------
2777    -- Analyze_Use_Package --
2778    -------------------------
2779
2780    --  Resolve the package names in the use clause, and make all the visible
2781    --  entities defined in the package potentially use-visible. If the package
2782    --  is already in use from a previous use clause, its visible entities are
2783    --  already use-visible. In that case, mark the occurrence as a redundant
2784    --  use. If the package is an open scope, i.e. if the use clause occurs
2785    --  within the package itself, ignore it.
2786
2787    procedure Analyze_Use_Package (N : Node_Id) is
2788       Pack_Name : Node_Id;
2789       Pack      : Entity_Id;
2790
2791    --  Start of processing for Analyze_Use_Package
2792
2793    begin
2794       Check_SPARK_Restriction ("use clause is not allowed", N);
2795
2796       Set_Hidden_By_Use_Clause (N, No_Elist);
2797
2798       --  Use clause not allowed in a spec of a predefined package declaration
2799       --  except that packages whose file name starts a-n are OK (these are
2800       --  children of Ada.Numerics, which are never loaded by Rtsfind).
2801
2802       if Is_Predefined_File_Name (Unit_File_Name (Current_Sem_Unit))
2803         and then Name_Buffer (1 .. 3) /= "a-n"
2804         and then
2805           Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Declaration
2806       then
2807          Error_Msg_N ("use clause not allowed in predefined spec", N);
2808       end if;
2809
2810       --  Chain clause to list of use clauses in current scope
2811
2812       if Nkind (Parent (N)) /= N_Compilation_Unit then
2813          Chain_Use_Clause (N);
2814       end if;
2815
2816       --  Loop through package names to identify referenced packages
2817
2818       Pack_Name := First (Names (N));
2819       while Present (Pack_Name) loop
2820          Analyze (Pack_Name);
2821
2822          if Nkind (Parent (N)) = N_Compilation_Unit
2823            and then Nkind (Pack_Name) = N_Expanded_Name
2824          then
2825             declare
2826                Pref : Node_Id;
2827
2828             begin
2829                Pref := Prefix (Pack_Name);
2830                while Nkind (Pref) = N_Expanded_Name loop
2831                   Pref := Prefix (Pref);
2832                end loop;
2833
2834                if Entity (Pref) = Standard_Standard then
2835                   Error_Msg_N
2836                    ("predefined package Standard cannot appear"
2837                      & " in a context clause", Pref);
2838                end if;
2839             end;
2840          end if;
2841
2842          Next (Pack_Name);
2843       end loop;
2844
2845       --  Loop through package names to mark all entities as potentially
2846       --  use visible.
2847
2848       Pack_Name := First (Names (N));
2849       while Present (Pack_Name) loop
2850          if Is_Entity_Name (Pack_Name) then
2851             Pack := Entity (Pack_Name);
2852
2853             if Ekind (Pack) /= E_Package
2854               and then Etype (Pack) /= Any_Type
2855             then
2856                if Ekind (Pack) = E_Generic_Package then
2857                   Error_Msg_N  -- CODEFIX
2858                    ("a generic package is not allowed in a use clause",
2859                       Pack_Name);
2860                else
2861                   Error_Msg_N ("& is not a usable package", Pack_Name);
2862                end if;
2863
2864             else
2865                if Nkind (Parent (N)) = N_Compilation_Unit then
2866                   Check_In_Previous_With_Clause (N, Pack_Name);
2867                end if;
2868
2869                if Applicable_Use (Pack_Name) then
2870                   Use_One_Package (Pack, N);
2871                end if;
2872             end if;
2873
2874          --  Report error because name denotes something other than a package
2875
2876          else
2877             Error_Msg_N ("& is not a package", Pack_Name);
2878          end if;
2879
2880          Next (Pack_Name);
2881       end loop;
2882    end Analyze_Use_Package;
2883
2884    ----------------------
2885    -- Analyze_Use_Type --
2886    ----------------------
2887
2888    procedure Analyze_Use_Type (N : Node_Id) is
2889       E  : Entity_Id;
2890       Id : Node_Id;
2891
2892    begin
2893       Set_Hidden_By_Use_Clause (N, No_Elist);
2894
2895       --  Chain clause to list of use clauses in current scope
2896
2897       if Nkind (Parent (N)) /= N_Compilation_Unit then
2898          Chain_Use_Clause (N);
2899       end if;
2900
2901       --  If the Used_Operations list is already initialized, the clause has
2902       --  been analyzed previously, and it is begin reinstalled, for example
2903       --  when the clause appears in a package spec and we are compiling the
2904       --  corresponding package body. In that case, make the entities on the
2905       --  existing list use_visible, and mark the corresponding types In_Use.
2906
2907       if Present (Used_Operations (N)) then
2908          declare
2909             Mark : Node_Id;
2910             Elmt : Elmt_Id;
2911
2912          begin
2913             Mark := First (Subtype_Marks (N));
2914             while Present (Mark) loop
2915                Use_One_Type (Mark, Installed => True);
2916                Next (Mark);
2917             end loop;
2918
2919             Elmt := First_Elmt (Used_Operations (N));
2920             while Present (Elmt) loop
2921                Set_Is_Potentially_Use_Visible (Node (Elmt));
2922                Next_Elmt (Elmt);
2923             end loop;
2924          end;
2925
2926          return;
2927       end if;
2928
2929       --  Otherwise, create new list and attach to it the operations that
2930       --  are made use-visible by the clause.
2931
2932       Set_Used_Operations (N, New_Elmt_List);
2933       Id := First (Subtype_Marks (N));
2934       while Present (Id) loop
2935          Find_Type (Id);
2936          E := Entity (Id);
2937
2938          if E /= Any_Type then
2939             Use_One_Type (Id);
2940
2941             if Nkind (Parent (N)) = N_Compilation_Unit then
2942                if Nkind (Id) = N_Identifier then
2943                   Error_Msg_N ("type is not directly visible", Id);
2944
2945                elsif Is_Child_Unit (Scope (E))
2946                  and then Scope (E) /= System_Aux_Id
2947                then
2948                   Check_In_Previous_With_Clause (N, Prefix (Id));
2949                end if;
2950             end if;
2951
2952          else
2953             --  If the use_type_clause appears in a compilation unit context,
2954             --  check whether it comes from a unit that may appear in a
2955             --  limited_with_clause, for a better error message.
2956
2957             if Nkind (Parent (N)) = N_Compilation_Unit
2958               and then Nkind (Id) /= N_Identifier
2959             then
2960                declare
2961                   Item : Node_Id;
2962                   Pref : Node_Id;
2963
2964                   function Mentioned (Nam : Node_Id) return Boolean;
2965                   --  Check whether the prefix of expanded name for the type
2966                   --  appears in the prefix of some limited_with_clause.
2967
2968                   ---------------
2969                   -- Mentioned --
2970                   ---------------
2971
2972                   function Mentioned (Nam : Node_Id) return Boolean is
2973                   begin
2974                      return Nkind (Name (Item)) = N_Selected_Component
2975                               and then
2976                             Chars (Prefix (Name (Item))) = Chars (Nam);
2977                   end Mentioned;
2978
2979                begin
2980                   Pref := Prefix (Id);
2981                   Item := First (Context_Items (Parent (N)));
2982
2983                   while Present (Item) and then Item /= N loop
2984                      if Nkind (Item) = N_With_Clause
2985                        and then Limited_Present (Item)
2986                        and then Mentioned (Pref)
2987                      then
2988                         Change_Error_Text
2989                           (Get_Msg_Id, "premature usage of incomplete type");
2990                      end if;
2991
2992                      Next (Item);
2993                   end loop;
2994                end;
2995             end if;
2996          end if;
2997
2998          Next (Id);
2999       end loop;
3000    end Analyze_Use_Type;
3001
3002    --------------------
3003    -- Applicable_Use --
3004    --------------------
3005
3006    function Applicable_Use (Pack_Name : Node_Id) return Boolean is
3007       Pack : constant Entity_Id := Entity (Pack_Name);
3008
3009    begin
3010       if In_Open_Scopes (Pack) then
3011          if Warn_On_Redundant_Constructs
3012            and then Pack = Current_Scope
3013          then
3014             Error_Msg_NE -- CODEFIX
3015               ("& is already use-visible within itself?", Pack_Name, Pack);
3016          end if;
3017
3018          return False;
3019
3020       elsif In_Use (Pack) then
3021          Note_Redundant_Use (Pack_Name);
3022          return False;
3023
3024       elsif Present (Renamed_Object (Pack))
3025         and then In_Use (Renamed_Object (Pack))
3026       then
3027          Note_Redundant_Use (Pack_Name);
3028          return False;
3029
3030       else
3031          return True;
3032       end if;
3033    end Applicable_Use;
3034
3035    ------------------------
3036    -- Attribute_Renaming --
3037    ------------------------
3038
3039    procedure Attribute_Renaming (N : Node_Id) is
3040       Loc        : constant Source_Ptr := Sloc (N);
3041       Nam        : constant Node_Id    := Name (N);
3042       Spec       : constant Node_Id    := Specification (N);
3043       New_S      : constant Entity_Id  := Defining_Unit_Name (Spec);
3044       Aname      : constant Name_Id    := Attribute_Name (Nam);
3045
3046       Form_Num   : Nat      := 0;
3047       Expr_List  : List_Id  := No_List;
3048
3049       Attr_Node  : Node_Id;
3050       Body_Node  : Node_Id;
3051       Param_Spec : Node_Id;
3052
3053    begin
3054       Generate_Definition (New_S);
3055
3056       --  This procedure is called in the context of subprogram renaming, and
3057       --  thus the attribute must be one that is a subprogram. All of those
3058       --  have at least one formal parameter, with the singular exception of
3059       --  AST_Entry (which is a real oddity, it is odd that this can be renamed
3060       --  at all!)
3061
3062       if not Is_Non_Empty_List (Parameter_Specifications (Spec)) then
3063          if Aname /= Name_AST_Entry then
3064             Error_Msg_N
3065               ("subprogram renaming an attribute must have formals", N);
3066             return;
3067          end if;
3068
3069       else
3070          Param_Spec := First (Parameter_Specifications (Spec));
3071          while Present (Param_Spec) loop
3072             Form_Num := Form_Num + 1;
3073
3074             if Nkind (Parameter_Type (Param_Spec)) /= N_Access_Definition then
3075                Find_Type (Parameter_Type (Param_Spec));
3076
3077                --  The profile of the new entity denotes the base type (s) of
3078                --  the types given in the specification. For access parameters
3079                --  there are no subtypes involved.
3080
3081                Rewrite (Parameter_Type (Param_Spec),
3082                 New_Reference_To
3083                   (Base_Type (Entity (Parameter_Type (Param_Spec))), Loc));
3084             end if;
3085
3086             if No (Expr_List) then
3087                Expr_List := New_List;
3088             end if;
3089
3090             Append_To (Expr_List,
3091               Make_Identifier (Loc,
3092                 Chars => Chars (Defining_Identifier (Param_Spec))));
3093
3094             --  The expressions in the attribute reference are not freeze
3095             --  points. Neither is the attribute as a whole, see below.
3096
3097             Set_Must_Not_Freeze (Last (Expr_List));
3098             Next (Param_Spec);
3099          end loop;
3100       end if;
3101
3102       --  Immediate error if too many formals. Other mismatches in number or
3103       --  types of parameters are detected when we analyze the body of the
3104       --  subprogram that we construct.
3105
3106       if Form_Num > 2 then
3107          Error_Msg_N ("too many formals for attribute", N);
3108
3109       --  Error if the attribute reference has expressions that look like
3110       --  formal parameters.
3111
3112       elsif Present (Expressions (Nam)) then
3113          Error_Msg_N ("illegal expressions in attribute reference", Nam);
3114
3115       elsif
3116         Aname = Name_Compose      or else
3117         Aname = Name_Exponent     or else
3118         Aname = Name_Leading_Part or else
3119         Aname = Name_Pos          or else
3120         Aname = Name_Round        or else
3121         Aname = Name_Scaling      or else
3122         Aname = Name_Val
3123       then
3124          if Nkind (N) = N_Subprogram_Renaming_Declaration
3125            and then Present (Corresponding_Formal_Spec (N))
3126          then
3127             Error_Msg_N
3128               ("generic actual cannot be attribute involving universal type",
3129                Nam);
3130          else
3131             Error_Msg_N
3132               ("attribute involving a universal type cannot be renamed",
3133                Nam);
3134          end if;
3135       end if;
3136
3137       --  AST_Entry is an odd case. It doesn't really make much sense to allow
3138       --  it to be renamed, but that's the DEC rule, so we have to do it right.
3139       --  The point is that the AST_Entry call should be made now, and what the
3140       --  function will return is the returned value.
3141
3142       --  Note that there is no Expr_List in this case anyway
3143
3144       if Aname = Name_AST_Entry then
3145          declare
3146             Ent  : constant Entity_Id := Make_Temporary (Loc, 'R', Nam);
3147             Decl : Node_Id;
3148
3149          begin
3150             Decl :=
3151               Make_Object_Declaration (Loc,
3152                 Defining_Identifier => Ent,
3153                 Object_Definition   =>
3154                   New_Occurrence_Of (RTE (RE_AST_Handler), Loc),
3155                 Expression          => Nam,
3156                 Constant_Present    => True);
3157
3158             Set_Assignment_OK (Decl, True);
3159             Insert_Action (N, Decl);
3160             Attr_Node := Make_Identifier (Loc, Chars (Ent));
3161          end;
3162
3163       --  For all other attributes, we rewrite the attribute node to have
3164       --  a list of expressions corresponding to the subprogram formals.
3165       --  A renaming declaration is not a freeze point, and the analysis of
3166       --  the attribute reference should not freeze the type of the prefix.
3167
3168       else
3169          Attr_Node :=
3170            Make_Attribute_Reference (Loc,
3171              Prefix         => Prefix (Nam),
3172              Attribute_Name => Aname,
3173              Expressions    => Expr_List);
3174
3175          Set_Must_Not_Freeze (Attr_Node);
3176          Set_Must_Not_Freeze (Prefix (Nam));
3177       end if;
3178
3179       --  Case of renaming a function
3180
3181       if Nkind (Spec) = N_Function_Specification then
3182          if Is_Procedure_Attribute_Name (Aname) then
3183             Error_Msg_N ("attribute can only be renamed as procedure", Nam);
3184             return;
3185          end if;
3186
3187          Find_Type (Result_Definition (Spec));
3188          Rewrite (Result_Definition (Spec),
3189              New_Reference_To (
3190                Base_Type (Entity (Result_Definition (Spec))), Loc));
3191
3192          Body_Node :=
3193            Make_Subprogram_Body (Loc,
3194              Specification => Spec,
3195              Declarations => New_List,
3196              Handled_Statement_Sequence =>
3197                Make_Handled_Sequence_Of_Statements (Loc,
3198                    Statements => New_List (
3199                      Make_Simple_Return_Statement (Loc,
3200                        Expression => Attr_Node))));
3201
3202       --  Case of renaming a procedure
3203
3204       else
3205          if not Is_Procedure_Attribute_Name (Aname) then
3206             Error_Msg_N ("attribute can only be renamed as function", Nam);
3207             return;
3208          end if;
3209
3210          Body_Node :=
3211            Make_Subprogram_Body (Loc,
3212              Specification => Spec,
3213              Declarations => New_List,
3214              Handled_Statement_Sequence =>
3215                Make_Handled_Sequence_Of_Statements (Loc,
3216                    Statements => New_List (Attr_Node)));
3217       end if;
3218
3219       --  In case of tagged types we add the body of the generated function to
3220       --  the freezing actions of the type (because in the general case such
3221       --  type is still not frozen). We exclude from this processing generic
3222       --  formal subprograms found in instantiations and AST_Entry renamings.
3223
3224       --  We must exclude VM targets because entity AST_Handler is defined in
3225       --  package System.Aux_Dec which is not available in those platforms.
3226
3227       if VM_Target = No_VM
3228         and then not Present (Corresponding_Formal_Spec (N))
3229         and then Etype (Nam) /= RTE (RE_AST_Handler)
3230       then
3231          declare
3232             P : constant Entity_Id := Prefix (Nam);
3233
3234          begin
3235             Find_Type (P);
3236
3237             if Is_Tagged_Type (Etype (P)) then
3238                Ensure_Freeze_Node (Etype (P));
3239                Append_Freeze_Action (Etype (P), Body_Node);
3240             else
3241                Rewrite (N, Body_Node);
3242                Analyze (N);
3243                Set_Etype (New_S, Base_Type (Etype (New_S)));
3244             end if;
3245          end;
3246
3247       --  Generic formal subprograms or AST_Handler renaming
3248
3249       else
3250          Rewrite (N, Body_Node);
3251          Analyze (N);
3252          Set_Etype (New_S, Base_Type (Etype (New_S)));
3253       end if;
3254
3255       if Is_Compilation_Unit (New_S) then
3256          Error_Msg_N
3257            ("a library unit can only rename another library unit", N);
3258       end if;
3259
3260       --  We suppress elaboration warnings for the resulting entity, since
3261       --  clearly they are not needed, and more particularly, in the case
3262       --  of a generic formal subprogram, the resulting entity can appear
3263       --  after the instantiation itself, and thus look like a bogus case
3264       --  of access before elaboration.
3265
3266       Set_Suppress_Elaboration_Warnings (New_S);
3267
3268    end Attribute_Renaming;
3269
3270    ----------------------
3271    -- Chain_Use_Clause --
3272    ----------------------
3273
3274    procedure Chain_Use_Clause (N : Node_Id) is
3275       Pack : Entity_Id;
3276       Level : Int := Scope_Stack.Last;
3277
3278    begin
3279       if not Is_Compilation_Unit (Current_Scope)
3280         or else not Is_Child_Unit (Current_Scope)
3281       then
3282          null;   --  Common case
3283
3284       elsif Defining_Entity (Parent (N)) = Current_Scope then
3285          null;   --  Common case for compilation unit
3286
3287       else
3288          --  If declaration appears in some other scope, it must be in some
3289          --  parent unit when compiling a child.
3290
3291          Pack := Defining_Entity (Parent (N));
3292          if not In_Open_Scopes (Pack) then
3293             null;  --  default as well
3294
3295          else
3296             --  Find entry for parent unit in scope stack
3297
3298             while Scope_Stack.Table (Level).Entity /= Pack loop
3299                Level := Level - 1;
3300             end loop;
3301          end if;
3302       end if;
3303
3304       Set_Next_Use_Clause (N,
3305         Scope_Stack.Table (Level).First_Use_Clause);
3306       Scope_Stack.Table (Level).First_Use_Clause := N;
3307    end Chain_Use_Clause;
3308
3309    ---------------------------
3310    -- Check_Frozen_Renaming --
3311    ---------------------------
3312
3313    procedure Check_Frozen_Renaming (N : Node_Id; Subp : Entity_Id) is
3314       B_Node : Node_Id;
3315       Old_S  : Entity_Id;
3316
3317    begin
3318       if Is_Frozen (Subp)
3319         and then not Has_Completion (Subp)
3320       then
3321          B_Node :=
3322            Build_Renamed_Body
3323              (Parent (Declaration_Node (Subp)), Defining_Entity (N));
3324
3325          if Is_Entity_Name (Name (N)) then
3326             Old_S := Entity (Name (N));
3327
3328             if not Is_Frozen (Old_S)
3329               and then Operating_Mode /= Check_Semantics
3330             then
3331                Append_Freeze_Action (Old_S, B_Node);
3332             else
3333                Insert_After (N, B_Node);
3334                Analyze (B_Node);
3335             end if;
3336
3337             if Is_Intrinsic_Subprogram (Old_S)
3338               and then not In_Instance
3339             then
3340                Error_Msg_N
3341                  ("subprogram used in renaming_as_body cannot be intrinsic",
3342                     Name (N));
3343             end if;
3344
3345          else
3346             Insert_After (N, B_Node);
3347             Analyze (B_Node);
3348          end if;
3349       end if;
3350    end Check_Frozen_Renaming;
3351
3352    -------------------------------
3353    -- Set_Entity_Or_Discriminal --
3354    -------------------------------
3355
3356    procedure Set_Entity_Or_Discriminal (N : Node_Id; E : Entity_Id) is
3357       P : Node_Id;
3358
3359    begin
3360       --  If the entity is not a discriminant, or else expansion is disabled,
3361       --  simply set the entity.
3362
3363       if not In_Spec_Expression
3364         or else Ekind (E) /= E_Discriminant
3365         or else Inside_A_Generic
3366       then
3367          Set_Entity_With_Style_Check (N, E);
3368
3369       --  The replacement of a discriminant by the corresponding discriminal
3370       --  is not done for a task discriminant that appears in a default
3371       --  expression of an entry parameter. See Exp_Ch2.Expand_Discriminant
3372       --  for details on their handling.
3373
3374       elsif Is_Concurrent_Type (Scope (E)) then
3375
3376          P := Parent (N);
3377          while Present (P)
3378            and then not Nkind_In (P, N_Parameter_Specification,
3379                                   N_Component_Declaration)
3380          loop
3381             P := Parent (P);
3382          end loop;
3383
3384          if Present (P)
3385            and then Nkind (P) = N_Parameter_Specification
3386          then
3387             null;
3388
3389          else
3390             Set_Entity (N, Discriminal (E));
3391          end if;
3392
3393          --  Otherwise, this is a discriminant in a context in which
3394          --  it is a reference to the corresponding parameter of the
3395          --  init proc for the enclosing type.
3396
3397       else
3398          Set_Entity (N, Discriminal (E));
3399       end if;
3400    end Set_Entity_Or_Discriminal;
3401
3402    -----------------------------------
3403    -- Check_In_Previous_With_Clause --
3404    -----------------------------------
3405
3406    procedure Check_In_Previous_With_Clause
3407      (N   : Node_Id;
3408       Nam : Entity_Id)
3409    is
3410       Pack : constant Entity_Id := Entity (Original_Node (Nam));
3411       Item : Node_Id;
3412       Par  : Node_Id;
3413
3414    begin
3415       Item := First (Context_Items (Parent (N)));
3416
3417       while Present (Item)
3418         and then Item /= N
3419       loop
3420          if Nkind (Item) = N_With_Clause
3421
3422             --  Protect the frontend against previous critical errors
3423
3424            and then Nkind (Name (Item)) /= N_Selected_Component
3425            and then Entity (Name (Item)) = Pack
3426          then
3427             Par := Nam;
3428
3429             --  Find root library unit in with_clause
3430
3431             while Nkind (Par) = N_Expanded_Name loop
3432                Par := Prefix (Par);
3433             end loop;
3434
3435             if Is_Child_Unit (Entity (Original_Node (Par))) then
3436                Error_Msg_NE ("& is not directly visible", Par, Entity (Par));
3437             else
3438                return;
3439             end if;
3440          end if;
3441
3442          Next (Item);
3443       end loop;
3444
3445       --  On exit, package is not mentioned in a previous with_clause.
3446       --  Check if its prefix is.
3447
3448       if Nkind (Nam) = N_Expanded_Name then
3449          Check_In_Previous_With_Clause (N, Prefix (Nam));
3450
3451       elsif Pack /= Any_Id then
3452          Error_Msg_NE ("& is not visible", Nam, Pack);
3453       end if;
3454    end Check_In_Previous_With_Clause;
3455
3456    ---------------------------------
3457    -- Check_Library_Unit_Renaming --
3458    ---------------------------------
3459
3460    procedure Check_Library_Unit_Renaming (N : Node_Id; Old_E : Entity_Id) is
3461       New_E : Entity_Id;
3462
3463    begin
3464       if Nkind (Parent (N)) /= N_Compilation_Unit then
3465          return;
3466
3467       --  Check for library unit. Note that we used to check for the scope
3468       --  being Standard here, but that was wrong for Standard itself.
3469
3470       elsif not Is_Compilation_Unit (Old_E)
3471         and then not Is_Child_Unit (Old_E)
3472       then
3473          Error_Msg_N ("renamed unit must be a library unit", Name (N));
3474
3475       --  Entities defined in Standard (operators and boolean literals) cannot
3476       --  be renamed as library units.
3477
3478       elsif Scope (Old_E) = Standard_Standard
3479         and then Sloc (Old_E) = Standard_Location
3480       then
3481          Error_Msg_N ("renamed unit must be a library unit", Name (N));
3482
3483       elsif Present (Parent_Spec (N))
3484         and then Nkind (Unit (Parent_Spec (N))) = N_Generic_Package_Declaration
3485         and then not Is_Child_Unit (Old_E)
3486       then
3487          Error_Msg_N
3488            ("renamed unit must be a child unit of generic parent", Name (N));
3489
3490       elsif Nkind (N) in N_Generic_Renaming_Declaration
3491          and then  Nkind (Name (N)) = N_Expanded_Name
3492          and then Is_Generic_Instance (Entity (Prefix (Name (N))))
3493          and then Is_Generic_Unit (Old_E)
3494       then
3495          Error_Msg_N
3496            ("renamed generic unit must be a library unit", Name (N));
3497
3498       elsif Is_Package_Or_Generic_Package (Old_E) then
3499
3500          --  Inherit categorization flags
3501
3502          New_E := Defining_Entity (N);
3503          Set_Is_Pure                  (New_E, Is_Pure           (Old_E));
3504          Set_Is_Preelaborated         (New_E, Is_Preelaborated  (Old_E));
3505          Set_Is_Remote_Call_Interface (New_E,
3506                                        Is_Remote_Call_Interface (Old_E));
3507          Set_Is_Remote_Types          (New_E, Is_Remote_Types   (Old_E));
3508          Set_Is_Shared_Passive        (New_E, Is_Shared_Passive (Old_E));
3509       end if;
3510    end Check_Library_Unit_Renaming;
3511
3512    ---------------
3513    -- End_Scope --
3514    ---------------
3515
3516    procedure End_Scope is
3517       Id    : Entity_Id;
3518       Prev  : Entity_Id;
3519       Outer : Entity_Id;
3520
3521    begin
3522       Id := First_Entity (Current_Scope);
3523       while Present (Id) loop
3524          --  An entity in the current scope is not necessarily the first one
3525          --  on its homonym chain. Find its predecessor if any,
3526          --  If it is an internal entity, it will not be in the visibility
3527          --  chain altogether,  and there is nothing to unchain.
3528
3529          if Id /= Current_Entity (Id) then
3530             Prev := Current_Entity (Id);
3531             while Present (Prev)
3532               and then Present (Homonym (Prev))
3533               and then Homonym (Prev) /= Id
3534             loop
3535                Prev := Homonym (Prev);
3536             end loop;
3537
3538             --  Skip to end of loop if Id is not in the visibility chain
3539
3540             if No (Prev) or else Homonym (Prev) /= Id then
3541                goto Next_Ent;
3542             end if;
3543
3544          else
3545             Prev := Empty;
3546          end if;
3547
3548          Set_Is_Immediately_Visible (Id, False);
3549
3550          Outer := Homonym (Id);
3551          while Present (Outer) and then Scope (Outer) = Current_Scope loop
3552             Outer := Homonym (Outer);
3553          end loop;
3554
3555          --  Reset homonym link of other entities, but do not modify link
3556          --  between entities in current scope, so that the back-end can have
3557          --  a proper count of local overloadings.
3558
3559          if No (Prev) then
3560             Set_Name_Entity_Id (Chars (Id), Outer);
3561
3562          elsif Scope (Prev) /= Scope (Id) then
3563             Set_Homonym (Prev,  Outer);
3564          end if;
3565
3566          <<Next_Ent>>
3567             Next_Entity (Id);
3568       end loop;
3569
3570       --  If the scope generated freeze actions, place them before the
3571       --  current declaration and analyze them. Type declarations and
3572       --  the bodies of initialization procedures can generate such nodes.
3573       --  We follow the parent chain until we reach a list node, which is
3574       --  the enclosing list of declarations. If the list appears within
3575       --  a protected definition, move freeze nodes outside the protected
3576       --  type altogether.
3577
3578       if Present
3579          (Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions)
3580       then
3581          declare
3582             Decl : Node_Id;
3583             L    : constant List_Id := Scope_Stack.Table
3584                     (Scope_Stack.Last).Pending_Freeze_Actions;
3585
3586          begin
3587             if Is_Itype (Current_Scope) then
3588                Decl := Associated_Node_For_Itype (Current_Scope);
3589             else
3590                Decl := Parent (Current_Scope);
3591             end if;
3592
3593             Pop_Scope;
3594
3595             while not (Is_List_Member (Decl))
3596               or else Nkind_In (Parent (Decl), N_Protected_Definition,
3597                                                N_Task_Definition)
3598             loop
3599                Decl := Parent (Decl);
3600             end loop;
3601
3602             Insert_List_Before_And_Analyze (Decl, L);
3603          end;
3604
3605       else
3606          Pop_Scope;
3607       end if;
3608
3609    end End_Scope;
3610
3611    ---------------------
3612    -- End_Use_Clauses --
3613    ---------------------
3614
3615    procedure End_Use_Clauses (Clause : Node_Id) is
3616       U   : Node_Id;
3617
3618    begin
3619       --  Remove Use_Type clauses first, because they affect the
3620       --  visibility of operators in subsequent used packages.
3621
3622       U := Clause;
3623       while Present (U) loop
3624          if Nkind (U) = N_Use_Type_Clause then
3625             End_Use_Type (U);
3626          end if;
3627
3628          Next_Use_Clause (U);
3629       end loop;
3630
3631       U := Clause;
3632       while Present (U) loop
3633          if Nkind (U) = N_Use_Package_Clause then
3634             End_Use_Package (U);
3635          end if;
3636
3637          Next_Use_Clause (U);
3638       end loop;
3639    end End_Use_Clauses;
3640
3641    ---------------------
3642    -- End_Use_Package --
3643    ---------------------
3644
3645    procedure End_Use_Package (N : Node_Id) is
3646       Pack_Name : Node_Id;
3647       Pack      : Entity_Id;
3648       Id        : Entity_Id;
3649       Elmt      : Elmt_Id;
3650
3651       function Is_Primitive_Operator_In_Use
3652         (Op : Entity_Id;
3653          F  : Entity_Id) return Boolean;
3654       --  Check whether Op is a primitive operator of a use-visible type
3655
3656       ----------------------------------
3657       -- Is_Primitive_Operator_In_Use --
3658       ----------------------------------
3659
3660       function Is_Primitive_Operator_In_Use
3661         (Op : Entity_Id;
3662          F  : Entity_Id) return Boolean
3663       is
3664          T : constant Entity_Id := Base_Type (Etype (F));
3665       begin
3666          return In_Use (T) and then Scope (T) = Scope (Op);
3667       end Is_Primitive_Operator_In_Use;
3668
3669    --  Start of processing for End_Use_Package
3670
3671    begin
3672       Pack_Name := First (Names (N));
3673       while Present (Pack_Name) loop
3674
3675          --  Test that Pack_Name actually denotes a package before processing
3676
3677          if Is_Entity_Name (Pack_Name)
3678            and then Ekind (Entity (Pack_Name)) = E_Package
3679          then
3680             Pack := Entity (Pack_Name);
3681
3682             if In_Open_Scopes (Pack) then
3683                null;
3684
3685             elsif not Redundant_Use (Pack_Name) then
3686                Set_In_Use (Pack, False);
3687                Set_Current_Use_Clause (Pack, Empty);
3688
3689                Id := First_Entity (Pack);
3690                while Present (Id) loop
3691
3692                   --  Preserve use-visibility of operators that are primitive
3693                   --  operators of a type that is use-visible through an active
3694                   --  use_type clause.
3695
3696                   if Nkind (Id) = N_Defining_Operator_Symbol
3697                        and then
3698                          (Is_Primitive_Operator_In_Use
3699                            (Id, First_Formal (Id))
3700                             or else
3701                           (Present (Next_Formal (First_Formal (Id)))
3702                              and then
3703                                Is_Primitive_Operator_In_Use
3704                                  (Id, Next_Formal (First_Formal (Id)))))
3705                   then
3706                      null;
3707
3708                   else
3709                      Set_Is_Potentially_Use_Visible (Id, False);
3710                   end if;
3711
3712                   if Is_Private_Type (Id)
3713                     and then Present (Full_View (Id))
3714                   then
3715                      Set_Is_Potentially_Use_Visible (Full_View (Id), False);
3716                   end if;
3717
3718                   Next_Entity (Id);
3719                end loop;
3720
3721                if Present (Renamed_Object (Pack)) then
3722                   Set_In_Use (Renamed_Object (Pack), False);
3723                   Set_Current_Use_Clause (Renamed_Object (Pack), Empty);
3724                end if;
3725
3726                if Chars (Pack) = Name_System
3727                  and then Scope (Pack) = Standard_Standard
3728                  and then Present_System_Aux
3729                then
3730                   Id := First_Entity (System_Aux_Id);
3731                   while Present (Id) loop
3732                      Set_Is_Potentially_Use_Visible (Id, False);
3733
3734                      if Is_Private_Type (Id)
3735                        and then Present (Full_View (Id))
3736                      then
3737                         Set_Is_Potentially_Use_Visible (Full_View (Id), False);
3738                      end if;
3739
3740                      Next_Entity (Id);
3741                   end loop;
3742
3743                   Set_In_Use (System_Aux_Id, False);
3744                end if;
3745
3746             else
3747                Set_Redundant_Use (Pack_Name, False);
3748             end if;
3749          end if;
3750
3751          Next (Pack_Name);
3752       end loop;
3753
3754       if Present (Hidden_By_Use_Clause (N)) then
3755          Elmt := First_Elmt (Hidden_By_Use_Clause (N));
3756          while Present (Elmt) loop
3757             declare
3758                E : constant Entity_Id := Node (Elmt);
3759
3760             begin
3761                --  Reset either Use_Visibility or Direct_Visibility, depending
3762                --  on how the entity was hidden by the use clause.
3763
3764                if In_Use (Scope (E))
3765                  and then Used_As_Generic_Actual (Scope (E))
3766                then
3767                   Set_Is_Potentially_Use_Visible (Node (Elmt));
3768                else
3769                   Set_Is_Immediately_Visible (Node (Elmt));
3770                end if;
3771
3772                Next_Elmt (Elmt);
3773             end;
3774          end loop;
3775
3776          Set_Hidden_By_Use_Clause (N, No_Elist);
3777       end if;
3778    end End_Use_Package;
3779
3780    ------------------
3781    -- End_Use_Type --
3782    ------------------
3783
3784    procedure End_Use_Type (N : Node_Id) is
3785       Elmt    : Elmt_Id;
3786       Id      : Entity_Id;
3787       T       : Entity_Id;
3788
3789    --  Start of processing for End_Use_Type
3790
3791    begin
3792       Id := First (Subtype_Marks (N));
3793       while Present (Id) loop
3794
3795          --  A call to Rtsfind may occur while analyzing a use_type clause,
3796          --  in which case the type marks are not resolved yet, and there is
3797          --  nothing to remove.
3798
3799          if not Is_Entity_Name (Id) or else No (Entity (Id)) then
3800             goto Continue;
3801          end if;
3802
3803          T := Entity (Id);
3804
3805          if T = Any_Type or else From_With_Type (T) then
3806             null;
3807
3808          --  Note that the use_type clause may mention a subtype of the type
3809          --  whose primitive operations have been made visible. Here as
3810          --  elsewhere, it is the base type that matters for visibility.
3811
3812          elsif In_Open_Scopes (Scope (Base_Type (T))) then
3813             null;
3814
3815          elsif not Redundant_Use (Id) then
3816             Set_In_Use (T, False);
3817             Set_In_Use (Base_Type (T), False);
3818             Set_Current_Use_Clause (T, Empty);
3819             Set_Current_Use_Clause (Base_Type (T), Empty);
3820          end if;
3821
3822          <<Continue>>
3823             Next (Id);
3824       end loop;
3825
3826       if Is_Empty_Elmt_List (Used_Operations (N)) then
3827          return;
3828
3829       else
3830          Elmt := First_Elmt (Used_Operations (N));
3831          while Present (Elmt) loop
3832             Set_Is_Potentially_Use_Visible (Node (Elmt), False);
3833             Next_Elmt (Elmt);
3834          end loop;
3835       end if;
3836    end End_Use_Type;
3837
3838    ----------------------
3839    -- Find_Direct_Name --
3840    ----------------------
3841
3842    procedure Find_Direct_Name (N : Node_Id) is
3843       E    : Entity_Id;
3844       E2   : Entity_Id;
3845       Msg  : Boolean;
3846
3847       Inst : Entity_Id := Empty;
3848       --  Enclosing instance, if any
3849
3850       Homonyms : Entity_Id;
3851       --  Saves start of homonym chain
3852
3853       Nvis_Entity : Boolean;
3854       --  Set True to indicate that there is at least one entity on the homonym
3855       --  chain which, while not visible, is visible enough from the user point
3856       --  of view to warrant an error message of "not visible" rather than
3857       --  undefined.
3858
3859       Nvis_Is_Private_Subprg : Boolean := False;
3860       --  Ada 2005 (AI-262): Set True to indicate that a form of Beaujolais
3861       --  effect concerning library subprograms has been detected. Used to
3862       --  generate the precise error message.
3863
3864       function From_Actual_Package (E : Entity_Id) return Boolean;
3865       --  Returns true if the entity is declared in a package that is
3866       --  an actual for a formal package of the current instance. Such an
3867       --  entity requires special handling because it may be use-visible
3868       --  but hides directly visible entities defined outside the instance.
3869
3870       function Is_Actual_Parameter return Boolean;
3871       --  This function checks if the node N is an identifier that is an actual
3872       --  parameter of a procedure call. If so it returns True, otherwise it
3873       --  return False. The reason for this check is that at this stage we do
3874       --  not know what procedure is being called if the procedure might be
3875       --  overloaded, so it is premature to go setting referenced flags or
3876       --  making calls to Generate_Reference. We will wait till Resolve_Actuals
3877       --  for that processing
3878
3879       function Known_But_Invisible (E : Entity_Id) return Boolean;
3880       --  This function determines whether the entity E (which is not
3881       --  visible) can reasonably be considered to be known to the writer
3882       --  of the reference. This is a heuristic test, used only for the
3883       --  purposes of figuring out whether we prefer to complain that an
3884       --  entity is undefined or invisible (and identify the declaration
3885       --  of the invisible entity in the latter case). The point here is
3886       --  that we don't want to complain that something is invisible and
3887       --  then point to something entirely mysterious to the writer.
3888
3889       procedure Nvis_Messages;
3890       --  Called if there are no visible entries for N, but there is at least
3891       --  one non-directly visible, or hidden declaration. This procedure
3892       --  outputs an appropriate set of error messages.
3893
3894       procedure Undefined (Nvis : Boolean);
3895       --  This function is called if the current node has no corresponding
3896       --  visible entity or entities. The value set in Msg indicates whether
3897       --  an error message was generated (multiple error messages for the
3898       --  same variable are generally suppressed, see body for details).
3899       --  Msg is True if an error message was generated, False if not. This
3900       --  value is used by the caller to determine whether or not to output
3901       --  additional messages where appropriate. The parameter is set False
3902       --  to get the message "X is undefined", and True to get the message
3903       --  "X is not visible".
3904
3905       -------------------------
3906       -- From_Actual_Package --
3907       -------------------------
3908
3909       function From_Actual_Package (E : Entity_Id) return Boolean is
3910          Scop : constant Entity_Id := Scope (E);
3911          Act  : Entity_Id;
3912
3913       begin
3914          if not In_Instance then
3915             return False;
3916          else
3917             Inst := Current_Scope;
3918             while Present (Inst)
3919               and then Ekind (Inst) /= E_Package
3920               and then not Is_Generic_Instance (Inst)
3921             loop
3922                Inst := Scope (Inst);
3923             end loop;
3924
3925             if No (Inst) then
3926                return False;
3927             end if;
3928
3929             Act := First_Entity (Inst);
3930             while Present (Act) loop
3931                if Ekind (Act) = E_Package then
3932
3933                   --  Check for end of actuals list
3934
3935                   if Renamed_Object (Act) = Inst then
3936                      return False;
3937
3938                   elsif Present (Associated_Formal_Package (Act))
3939                     and then Renamed_Object (Act) = Scop
3940                   then
3941                      --  Entity comes from (instance of) formal package
3942
3943                      return True;
3944
3945                   else
3946                      Next_Entity (Act);
3947                   end if;
3948
3949                else
3950                   Next_Entity (Act);
3951                end if;
3952             end loop;
3953
3954             return False;
3955          end if;
3956       end From_Actual_Package;
3957
3958       -------------------------
3959       -- Is_Actual_Parameter --
3960       -------------------------
3961
3962       function Is_Actual_Parameter return Boolean is
3963       begin
3964          return
3965            Nkind (N) = N_Identifier
3966              and then
3967                (Nkind (Parent (N)) = N_Procedure_Call_Statement
3968                   or else
3969                     (Nkind (Parent (N)) = N_Parameter_Association
3970                        and then N = Explicit_Actual_Parameter (Parent (N))
3971                        and then Nkind (Parent (Parent (N))) =
3972                                           N_Procedure_Call_Statement));
3973       end Is_Actual_Parameter;
3974
3975       -------------------------
3976       -- Known_But_Invisible --
3977       -------------------------
3978
3979       function Known_But_Invisible (E : Entity_Id) return Boolean is
3980          Fname : File_Name_Type;
3981
3982       begin
3983          --  Entities in Standard are always considered to be known
3984
3985          if Sloc (E) <= Standard_Location then
3986             return True;
3987
3988          --  An entity that does not come from source is always considered
3989          --  to be unknown, since it is an artifact of code expansion.
3990
3991          elsif not Comes_From_Source (E) then
3992             return False;
3993
3994          --  In gnat internal mode, we consider all entities known
3995
3996          elsif GNAT_Mode then
3997             return True;
3998          end if;
3999
4000          --  Here we have an entity that is not from package Standard, and
4001          --  which comes from Source. See if it comes from an internal file.
4002
4003          Fname := Unit_File_Name (Get_Source_Unit (E));
4004
4005          --  Case of from internal file
4006
4007          if Is_Internal_File_Name (Fname) then
4008
4009             --  Private part entities in internal files are never considered
4010             --  to be known to the writer of normal application code.
4011
4012             if Is_Hidden (E) then
4013                return False;
4014             end if;
4015
4016             --  Entities from System packages other than System and
4017             --  System.Storage_Elements are not considered to be known.
4018             --  System.Auxxxx files are also considered known to the user.
4019
4020             --  Should refine this at some point to generally distinguish
4021             --  between known and unknown internal files ???
4022
4023             Get_Name_String (Fname);
4024
4025             return
4026               Name_Len < 2
4027                 or else
4028               Name_Buffer (1 .. 2) /= "s-"
4029                 or else
4030               Name_Buffer (3 .. 8) = "stoele"
4031                 or else
4032               Name_Buffer (3 .. 5) = "aux";
4033
4034          --  If not an internal file, then entity is definitely known,
4035          --  even if it is in a private part (the message generated will
4036          --  note that it is in a private part)
4037
4038          else
4039             return True;
4040          end if;
4041       end Known_But_Invisible;
4042
4043       -------------------
4044       -- Nvis_Messages --
4045       -------------------
4046
4047       procedure Nvis_Messages is
4048          Comp_Unit : Node_Id;
4049          Ent       : Entity_Id;
4050          Found     : Boolean := False;
4051          Hidden    : Boolean := False;
4052          Item      : Node_Id;
4053
4054       begin
4055          --  Ada 2005 (AI-262): Generate a precise error concerning the
4056          --  Beaujolais effect that was previously detected
4057
4058          if Nvis_Is_Private_Subprg then
4059
4060             pragma Assert (Nkind (E2) = N_Defining_Identifier
4061                             and then Ekind (E2) = E_Function
4062                             and then Scope (E2) = Standard_Standard
4063                             and then Has_Private_With (E2));
4064
4065             --  Find the sloc corresponding to the private with'ed unit
4066
4067             Comp_Unit := Cunit (Current_Sem_Unit);
4068             Error_Msg_Sloc := No_Location;
4069
4070             Item := First (Context_Items (Comp_Unit));
4071             while Present (Item) loop
4072                if Nkind (Item) = N_With_Clause
4073                  and then Private_Present (Item)
4074                  and then Entity (Name (Item)) = E2
4075                then
4076                   Error_Msg_Sloc := Sloc (Item);
4077                   exit;
4078                end if;
4079
4080                Next (Item);
4081             end loop;
4082
4083             pragma Assert (Error_Msg_Sloc /= No_Location);
4084
4085             Error_Msg_N ("(Ada 2005): hidden by private with clause #", N);
4086             return;
4087          end if;
4088
4089          Undefined (Nvis => True);
4090
4091          if Msg then
4092
4093             --  First loop does hidden declarations
4094
4095             Ent := Homonyms;
4096             while Present (Ent) loop
4097                if Is_Potentially_Use_Visible (Ent) then
4098                   if not Hidden then
4099                      Error_Msg_N -- CODEFIX
4100                        ("multiple use clauses cause hiding!", N);
4101                      Hidden := True;
4102                   end if;
4103
4104                   Error_Msg_Sloc := Sloc (Ent);
4105                   Error_Msg_N -- CODEFIX
4106                     ("hidden declaration#!", N);
4107                end if;
4108
4109                Ent := Homonym (Ent);
4110             end loop;
4111
4112             --  If we found hidden declarations, then that's enough, don't
4113             --  bother looking for non-visible declarations as well.
4114
4115             if Hidden then
4116                return;
4117             end if;
4118
4119             --  Second loop does non-directly visible declarations
4120
4121             Ent := Homonyms;
4122             while Present (Ent) loop
4123                if not Is_Potentially_Use_Visible (Ent) then
4124
4125                   --  Do not bother the user with unknown entities
4126
4127                   if not Known_But_Invisible (Ent) then
4128                      goto Continue;
4129                   end if;
4130
4131                   Error_Msg_Sloc := Sloc (Ent);
4132
4133                   --  Output message noting that there is a non-visible
4134                   --  declaration, distinguishing the private part case.
4135
4136                   if Is_Hidden (Ent) then
4137                      Error_Msg_N ("non-visible (private) declaration#!", N);
4138
4139                   --  If the entity is declared in a generic package, it
4140                   --  cannot be visible, so there is no point in adding it
4141                   --  to the list of candidates if another homograph from a
4142                   --  non-generic package has been seen.
4143
4144                   elsif Ekind (Scope (Ent)) = E_Generic_Package
4145                     and then Found
4146                   then
4147                      null;
4148
4149                   else
4150                      Error_Msg_N -- CODEFIX
4151                        ("non-visible declaration#!", N);
4152
4153                      if Ekind (Scope (Ent)) /= E_Generic_Package then
4154                         Found := True;
4155                      end if;
4156
4157                      if Is_Compilation_Unit (Ent)
4158                        and then
4159                          Nkind (Parent (Parent (N))) = N_Use_Package_Clause
4160                      then
4161                         Error_Msg_Qual_Level := 99;
4162                         Error_Msg_NE -- CODEFIX
4163                           ("\\missing `WITH &;`", N, Ent);
4164                         Error_Msg_Qual_Level := 0;
4165                      end if;
4166
4167                      if Ekind (Ent) = E_Discriminant
4168                        and then Present (Corresponding_Discriminant (Ent))
4169                        and then Scope (Corresponding_Discriminant (Ent)) =
4170                                                         Etype (Scope (Ent))
4171                      then
4172                         Error_Msg_N
4173                           ("inherited discriminant not allowed here" &
4174                             " (RM 3.8 (12), 3.8.1 (6))!", N);
4175                      end if;
4176                   end if;
4177
4178                   --  Set entity and its containing package as referenced. We
4179                   --  can't be sure of this, but this seems a better choice
4180                   --  to avoid unused entity messages.
4181
4182                   if Comes_From_Source (Ent) then
4183                      Set_Referenced (Ent);
4184                      Set_Referenced (Cunit_Entity (Get_Source_Unit (Ent)));
4185                   end if;
4186                end if;
4187
4188                <<Continue>>
4189                Ent := Homonym (Ent);
4190             end loop;
4191          end if;
4192       end Nvis_Messages;
4193
4194       ---------------
4195       -- Undefined --
4196       ---------------
4197
4198       procedure Undefined (Nvis : Boolean) is
4199          Emsg : Error_Msg_Id;
4200
4201       begin
4202          --  We should never find an undefined internal name. If we do, then
4203          --  see if we have previous errors. If so, ignore on the grounds that
4204          --  it is probably a cascaded message (e.g. a block label from a badly
4205          --  formed block). If no previous errors, then we have a real internal
4206          --  error of some kind so raise an exception.
4207
4208          if Is_Internal_Name (Chars (N)) then
4209             if Total_Errors_Detected /= 0 then
4210                return;
4211             else
4212                raise Program_Error;
4213             end if;
4214          end if;
4215
4216          --  A very specialized error check, if the undefined variable is
4217          --  a case tag, and the case type is an enumeration type, check
4218          --  for a possible misspelling, and if so, modify the identifier
4219
4220          --  Named aggregate should also be handled similarly ???
4221
4222          if Nkind (N) = N_Identifier
4223            and then Nkind (Parent (N)) = N_Case_Statement_Alternative
4224          then
4225             declare
4226                Case_Stm : constant Node_Id   := Parent (Parent (N));
4227                Case_Typ : constant Entity_Id := Etype (Expression (Case_Stm));
4228
4229                Lit : Node_Id;
4230
4231             begin
4232                if Is_Enumeration_Type (Case_Typ)
4233                  and then not Is_Standard_Character_Type (Case_Typ)
4234                then
4235                   Lit := First_Literal (Case_Typ);
4236                   Get_Name_String (Chars (Lit));
4237
4238                   if Chars (Lit) /= Chars (N)
4239                     and then Is_Bad_Spelling_Of (Chars (N), Chars (Lit)) then
4240                      Error_Msg_Node_2 := Lit;
4241                      Error_Msg_N -- CODEFIX
4242                        ("& is undefined, assume misspelling of &", N);
4243                      Rewrite (N, New_Occurrence_Of (Lit, Sloc (N)));
4244                      return;
4245                   end if;
4246
4247                   Lit := Next_Literal (Lit);
4248                end if;
4249             end;
4250          end if;
4251
4252          --  Normal processing
4253
4254          Set_Entity (N, Any_Id);
4255          Set_Etype  (N, Any_Type);
4256
4257          --  We use the table Urefs to keep track of entities for which we
4258          --  have issued errors for undefined references. Multiple errors
4259          --  for a single name are normally suppressed, however we modify
4260          --  the error message to alert the programmer to this effect.
4261
4262          for J in Urefs.First .. Urefs.Last loop
4263             if Chars (N) = Chars (Urefs.Table (J).Node) then
4264                if Urefs.Table (J).Err /= No_Error_Msg
4265                  and then Sloc (N) /= Urefs.Table (J).Loc
4266                then
4267                   Error_Msg_Node_1 := Urefs.Table (J).Node;
4268
4269                   if Urefs.Table (J).Nvis then
4270                      Change_Error_Text (Urefs.Table (J).Err,
4271                        "& is not visible (more references follow)");
4272                   else
4273                      Change_Error_Text (Urefs.Table (J).Err,
4274                        "& is undefined (more references follow)");
4275                   end if;
4276
4277                   Urefs.Table (J).Err := No_Error_Msg;
4278                end if;
4279
4280                --  Although we will set Msg False, and thus suppress the
4281                --  message, we also set Error_Posted True, to avoid any
4282                --  cascaded messages resulting from the undefined reference.
4283
4284                Msg := False;
4285                Set_Error_Posted (N, True);
4286                return;
4287             end if;
4288          end loop;
4289
4290          --  If entry not found, this is first undefined occurrence
4291
4292          if Nvis then
4293             Error_Msg_N ("& is not visible!", N);
4294             Emsg := Get_Msg_Id;
4295
4296          else
4297             Error_Msg_N ("& is undefined!", N);
4298             Emsg := Get_Msg_Id;
4299
4300             --  A very bizarre special check, if the undefined identifier
4301             --  is put or put_line, then add a special error message (since
4302             --  this is a very common error for beginners to make).
4303
4304             if Chars (N) = Name_Put or else Chars (N) = Name_Put_Line then
4305                Error_Msg_N -- CODEFIX
4306                  ("\\possible missing `WITH Ada.Text_'I'O; " &
4307                   "USE Ada.Text_'I'O`!", N);
4308
4309             --  Another special check if N is the prefix of a selected
4310             --  component which is a known unit, add message complaining
4311             --  about missing with for this unit.
4312
4313             elsif Nkind (Parent (N)) = N_Selected_Component
4314               and then N = Prefix (Parent (N))
4315               and then Is_Known_Unit (Parent (N))
4316             then
4317                Error_Msg_Node_2 := Selector_Name (Parent (N));
4318                Error_Msg_N -- CODEFIX
4319                  ("\\missing `WITH &.&;`", Prefix (Parent (N)));
4320             end if;
4321
4322             --  Now check for possible misspellings
4323
4324             declare
4325                E      : Entity_Id;
4326                Ematch : Entity_Id := Empty;
4327
4328                Last_Name_Id : constant Name_Id :=
4329                                 Name_Id (Nat (First_Name_Id) +
4330                                            Name_Entries_Count - 1);
4331
4332             begin
4333                for Nam in First_Name_Id .. Last_Name_Id loop
4334                   E := Get_Name_Entity_Id (Nam);
4335
4336                   if Present (E)
4337                      and then (Is_Immediately_Visible (E)
4338                                  or else
4339                                Is_Potentially_Use_Visible (E))
4340                   then
4341                      if Is_Bad_Spelling_Of (Chars (N), Nam) then
4342                         Ematch := E;
4343                         exit;
4344                      end if;
4345                   end if;
4346                end loop;
4347
4348                if Present (Ematch) then
4349                   Error_Msg_NE -- CODEFIX
4350                     ("\possible misspelling of&", N, Ematch);
4351                end if;
4352             end;
4353          end if;
4354
4355          --  Make entry in undefined references table unless the full errors
4356          --  switch is set, in which case by refraining from generating the
4357          --  table entry, we guarantee that we get an error message for every
4358          --  undefined reference.
4359
4360          if not All_Errors_Mode then
4361             Urefs.Append (
4362               (Node => N,
4363                Err  => Emsg,
4364                Nvis => Nvis,
4365                Loc  => Sloc (N)));
4366          end if;
4367
4368          Msg := True;
4369       end Undefined;
4370
4371    --  Start of processing for Find_Direct_Name
4372
4373    begin
4374       --  If the entity pointer is already set, this is an internal node, or
4375       --  a node that is analyzed more than once, after a tree modification.
4376       --  In such a case there is no resolution to perform, just set the type.
4377
4378       if Present (Entity (N)) then
4379          if Is_Type (Entity (N)) then
4380             Set_Etype (N, Entity (N));
4381
4382          else
4383             declare
4384                Entyp : constant Entity_Id := Etype (Entity (N));
4385
4386             begin
4387                --  One special case here. If the Etype field is already set,
4388                --  and references the packed array type corresponding to the
4389                --  etype of the referenced entity, then leave it alone. This
4390                --  happens for trees generated from Exp_Pakd, where expressions
4391                --  can be deliberately "mis-typed" to the packed array type.
4392
4393                if Is_Array_Type (Entyp)
4394                  and then Is_Packed (Entyp)
4395                  and then Present (Etype (N))
4396                  and then Etype (N) = Packed_Array_Type (Entyp)
4397                then
4398                   null;
4399
4400                --  If not that special case, then just reset the Etype
4401
4402                else
4403                   Set_Etype (N, Etype (Entity (N)));
4404                end if;
4405             end;
4406          end if;
4407
4408          return;
4409       end if;
4410
4411       --  Here if Entity pointer was not set, we need full visibility analysis
4412       --  First we generate debugging output if the debug E flag is set.
4413
4414       if Debug_Flag_E then
4415          Write_Str ("Looking for ");
4416          Write_Name (Chars (N));
4417          Write_Eol;
4418       end if;
4419
4420       Homonyms := Current_Entity (N);
4421       Nvis_Entity := False;
4422
4423       E := Homonyms;
4424       while Present (E) loop
4425
4426          --  If entity is immediately visible or potentially use visible, then
4427          --  process the entity and we are done.
4428
4429          if Is_Immediately_Visible (E) then
4430             goto Immediately_Visible_Entity;
4431
4432          elsif Is_Potentially_Use_Visible (E) then
4433             goto Potentially_Use_Visible_Entity;
4434
4435          --  Note if a known but invisible entity encountered
4436
4437          elsif Known_But_Invisible (E) then
4438             Nvis_Entity := True;
4439          end if;
4440
4441          --  Move to next entity in chain and continue search
4442
4443          E := Homonym (E);
4444       end loop;
4445
4446       --  If no entries on homonym chain that were potentially visible,
4447       --  and no entities reasonably considered as non-visible, then
4448       --  we have a plain undefined reference, with no additional
4449       --  explanation required!
4450
4451       if not Nvis_Entity then
4452          Undefined (Nvis => False);
4453
4454       --  Otherwise there is at least one entry on the homonym chain that
4455       --  is reasonably considered as being known and non-visible.
4456
4457       else
4458          Nvis_Messages;
4459       end if;
4460
4461       return;
4462
4463       --  Processing for a potentially use visible entry found. We must search
4464       --  the rest of the homonym chain for two reasons. First, if there is a
4465       --  directly visible entry, then none of the potentially use-visible
4466       --  entities are directly visible (RM 8.4(10)). Second, we need to check
4467       --  for the case of multiple potentially use-visible entries hiding one
4468       --  another and as a result being non-directly visible (RM 8.4(11)).
4469
4470       <<Potentially_Use_Visible_Entity>> declare
4471          Only_One_Visible : Boolean := True;
4472          All_Overloadable : Boolean := Is_Overloadable (E);
4473
4474       begin
4475          E2 := Homonym (E);
4476          while Present (E2) loop
4477             if Is_Immediately_Visible (E2) then
4478
4479                --  If the use-visible entity comes from the actual for a
4480                --  formal package, it hides a directly visible entity from
4481                --  outside the instance.
4482
4483                if From_Actual_Package (E)
4484                  and then Scope_Depth (E2) < Scope_Depth (Inst)
4485                then
4486                   goto Found;
4487                else
4488                   E := E2;
4489                   goto Immediately_Visible_Entity;
4490                end if;
4491
4492             elsif Is_Potentially_Use_Visible (E2) then
4493                Only_One_Visible := False;
4494                All_Overloadable := All_Overloadable and Is_Overloadable (E2);
4495
4496             --  Ada 2005 (AI-262): Protect against a form of Beaujolais effect
4497             --  that can occur in private_with clauses. Example:
4498
4499             --    with A;
4500             --    private with B;              package A is
4501             --    package C is                   function B return Integer;
4502             --      use A;                     end A;
4503             --      V1 : Integer := B;
4504             --    private                      function B return Integer;
4505             --      V2 : Integer := B;
4506             --    end C;
4507
4508             --  V1 resolves to A.B, but V2 resolves to library unit B
4509
4510             elsif Ekind (E2) = E_Function
4511               and then Scope (E2) = Standard_Standard
4512               and then Has_Private_With (E2)
4513             then
4514                Only_One_Visible       := False;
4515                All_Overloadable       := False;
4516                Nvis_Is_Private_Subprg := True;
4517                exit;
4518             end if;
4519
4520             E2 := Homonym (E2);
4521          end loop;
4522
4523          --  On falling through this loop, we have checked that there are no
4524          --  immediately visible entities. Only_One_Visible is set if exactly
4525          --  one potentially use visible entity exists. All_Overloadable is
4526          --  set if all the potentially use visible entities are overloadable.
4527          --  The condition for legality is that either there is one potentially
4528          --  use visible entity, or if there is more than one, then all of them
4529          --  are overloadable.
4530
4531          if Only_One_Visible or All_Overloadable then
4532             goto Found;
4533
4534          --  If there is more than one potentially use-visible entity and at
4535          --  least one of them non-overloadable, we have an error (RM 8.4(11).
4536          --  Note that E points to the first such entity on the homonym list.
4537          --  Special case: if one of the entities is declared in an actual
4538          --  package, it was visible in the generic, and takes precedence over
4539          --  other entities that are potentially use-visible. Same if it is
4540          --  declared in a local instantiation of the current instance.
4541
4542          else
4543             if In_Instance then
4544
4545                --  Find current instance
4546
4547                Inst := Current_Scope;
4548                while Present (Inst)
4549                  and then Inst /= Standard_Standard
4550                loop
4551                   if Is_Generic_Instance (Inst) then
4552                      exit;
4553                   end if;
4554
4555                   Inst := Scope (Inst);
4556                end loop;
4557
4558                E2 := E;
4559                while Present (E2) loop
4560                   if From_Actual_Package (E2)
4561                     or else
4562                       (Is_Generic_Instance (Scope (E2))
4563                         and then Scope_Depth (Scope (E2)) > Scope_Depth (Inst))
4564                   then
4565                      E := E2;
4566                      goto Found;
4567                   end if;
4568
4569                   E2 := Homonym (E2);
4570                end loop;
4571
4572                Nvis_Messages;
4573                return;
4574
4575             elsif
4576               Is_Predefined_File_Name (Unit_File_Name (Current_Sem_Unit))
4577             then
4578                --  A use-clause in the body of a system file creates conflict
4579                --  with some entity in a user scope, while rtsfind is active.
4580                --  Keep only the entity coming from another predefined unit.
4581
4582                E2 := E;
4583                while Present (E2) loop
4584                   if Is_Predefined_File_Name
4585                     (Unit_File_Name (Get_Source_Unit (Sloc (E2))))
4586                   then
4587                      E := E2;
4588                      goto Found;
4589                   end if;
4590
4591                   E2 := Homonym (E2);
4592                end loop;
4593
4594                --  Entity must exist because predefined unit is correct
4595
4596                raise Program_Error;
4597
4598             else
4599                Nvis_Messages;
4600                return;
4601             end if;
4602          end if;
4603       end;
4604
4605       --  Come here with E set to the first immediately visible entity on
4606       --  the homonym chain. This is the one we want unless there is another
4607       --  immediately visible entity further on in the chain for an inner
4608       --  scope (RM 8.3(8)).
4609
4610       <<Immediately_Visible_Entity>> declare
4611          Level : Int;
4612          Scop  : Entity_Id;
4613
4614       begin
4615          --  Find scope level of initial entity. When compiling through
4616          --  Rtsfind, the previous context is not completely invisible, and
4617          --  an outer entity may appear on the chain, whose scope is below
4618          --  the entry for Standard that delimits the current scope stack.
4619          --  Indicate that the level for this spurious entry is outside of
4620          --  the current scope stack.
4621
4622          Level := Scope_Stack.Last;
4623          loop
4624             Scop := Scope_Stack.Table (Level).Entity;
4625             exit when Scop = Scope (E);
4626             Level := Level - 1;
4627             exit when Scop = Standard_Standard;
4628          end loop;
4629
4630          --  Now search remainder of homonym chain for more inner entry
4631          --  If the entity is Standard itself, it has no scope, and we
4632          --  compare it with the stack entry directly.
4633
4634          E2 := Homonym (E);
4635          while Present (E2) loop
4636             if Is_Immediately_Visible (E2) then
4637
4638                --  If a generic package contains a local declaration that
4639                --  has the same name as the generic, there may be a visibility
4640                --  conflict in an instance, where the local declaration must
4641                --  also hide the name of the corresponding package renaming.
4642                --  We check explicitly for a package declared by a renaming,
4643                --  whose renamed entity is an instance that is on the scope
4644                --  stack, and that contains a homonym in the same scope. Once
4645                --  we have found it, we know that the package renaming is not
4646                --  immediately visible, and that the identifier denotes the
4647                --  other entity (and its homonyms if overloaded).
4648
4649                if Scope (E) = Scope (E2)
4650                  and then Ekind (E) = E_Package
4651                  and then Present (Renamed_Object (E))
4652                  and then Is_Generic_Instance (Renamed_Object (E))
4653                  and then In_Open_Scopes (Renamed_Object (E))
4654                  and then Comes_From_Source (N)
4655                then
4656                   Set_Is_Immediately_Visible (E, False);
4657                   E := E2;
4658
4659                else
4660                   for J in Level + 1 .. Scope_Stack.Last loop
4661                      if Scope_Stack.Table (J).Entity = Scope (E2)
4662                        or else Scope_Stack.Table (J).Entity = E2
4663                      then
4664                         Level := J;
4665                         E := E2;
4666                         exit;
4667                      end if;
4668                   end loop;
4669                end if;
4670             end if;
4671
4672             E2 := Homonym (E2);
4673          end loop;
4674
4675          --  At the end of that loop, E is the innermost immediately
4676          --  visible entity, so we are all set.
4677       end;
4678
4679       --  Come here with entity found, and stored in E
4680
4681       <<Found>> begin
4682
4683          --  Check violation of No_Wide_Characters restriction
4684
4685          Check_Wide_Character_Restriction (E, N);
4686
4687          --  When distribution features are available (Get_PCS_Name /=
4688          --  Name_No_DSA), a remote access-to-subprogram type is converted
4689          --  into a record type holding whatever information is needed to
4690          --  perform a remote call on an RCI subprogram. In that case we
4691          --  rewrite any occurrence of the RAS type into the equivalent record
4692          --  type here. 'Access attribute references and RAS dereferences are
4693          --  then implemented using specific TSSs. However when distribution is
4694          --  not available (case of Get_PCS_Name = Name_No_DSA), we bypass the
4695          --  generation of these TSSs, and we must keep the RAS type in its
4696          --  original access-to-subprogram form (since all calls through a
4697          --  value of such type will be local anyway in the absence of a PCS).
4698
4699          if Comes_From_Source (N)
4700            and then Is_Remote_Access_To_Subprogram_Type (E)
4701            and then Expander_Active
4702            and then Get_PCS_Name /= Name_No_DSA
4703          then
4704             Rewrite (N,
4705               New_Occurrence_Of (Equivalent_Type (E), Sloc (N)));
4706             return;
4707          end if;
4708
4709          --  Set the entity. Note that the reason we call Set_Entity for the
4710          --  overloadable case, as opposed to Set_Entity_With_Style_Check is
4711          --  that in the overloaded case, the initial call can set the wrong
4712          --  homonym. The call that sets the right homonym is in Sem_Res and
4713          --  that call does use Set_Entity_With_Style_Check, so we don't miss
4714          --  a style check.
4715
4716          if Is_Overloadable (E) then
4717             Set_Entity (N, E);
4718          else
4719             Set_Entity_With_Style_Check (N, E);
4720          end if;
4721
4722          if Is_Type (E) then
4723             Set_Etype (N, E);
4724          else
4725             Set_Etype (N, Get_Full_View (Etype (E)));
4726          end if;
4727
4728          if Debug_Flag_E then
4729             Write_Str (" found  ");
4730             Write_Entity_Info (E, "      ");
4731          end if;
4732
4733          --  If the Ekind of the entity is Void, it means that all homonyms
4734          --  are hidden from all visibility (RM 8.3(5,14-20)). However, this
4735          --  test is skipped if the current scope is a record and the name is
4736          --  a pragma argument expression (case of Atomic and Volatile pragmas
4737          --  and possibly other similar pragmas added later, which are allowed
4738          --  to reference components in the current record).
4739
4740          if Ekind (E) = E_Void
4741            and then
4742              (not Is_Record_Type (Current_Scope)
4743                or else Nkind (Parent (N)) /= N_Pragma_Argument_Association)
4744          then
4745             Premature_Usage (N);
4746
4747          --  If the entity is overloadable, collect all interpretations of the
4748          --  name for subsequent overload resolution. We optimize a bit here to
4749          --  do this only if we have an overloadable entity that is not on its
4750          --  own on the homonym chain.
4751
4752          elsif Is_Overloadable (E)
4753            and then (Present (Homonym (E)) or else Current_Entity (N) /= E)
4754          then
4755             Collect_Interps (N);
4756
4757             --  If no homonyms were visible, the entity is unambiguous
4758
4759             if not Is_Overloaded (N) then
4760                if not Is_Actual_Parameter then
4761                   Generate_Reference (E, N);
4762                end if;
4763             end if;
4764
4765          --  Case of non-overloadable entity, set the entity providing that
4766          --  we do not have the case of a discriminant reference within a
4767          --  default expression. Such references are replaced with the
4768          --  corresponding discriminal, which is the formal corresponding to
4769          --  to the discriminant in the initialization procedure.
4770
4771          else
4772             --  Entity is unambiguous, indicate that it is referenced here
4773
4774             --  For a renaming of an object, always generate simple reference,
4775             --  we don't try to keep track of assignments in this case.
4776
4777             if Is_Object (E) and then Present (Renamed_Object (E)) then
4778                Generate_Reference (E, N);
4779
4780                --  If the renamed entity is a private protected component,
4781                --  reference the original component as well. This needs to be
4782                --  done because the private renamings are installed before any
4783                --  analysis has occurred. Reference to a private component will
4784                --  resolve to the renaming and the original component will be
4785                --  left unreferenced, hence the following.
4786
4787                if Is_Prival (E) then
4788                   Generate_Reference (Prival_Link (E), N);
4789                end if;
4790
4791             --  One odd case is that we do not want to set the Referenced flag
4792             --  if the entity is a label, and the identifier is the label in
4793             --  the source, since this is not a reference from the point of
4794             --  view of the user.
4795
4796             elsif Nkind (Parent (N)) = N_Label then
4797                declare
4798                   R : constant Boolean := Referenced (E);
4799
4800                begin
4801                   --  Generate reference unless this is an actual parameter
4802                   --  (see comment below)
4803
4804                   if Is_Actual_Parameter then
4805                      Generate_Reference (E, N);
4806                      Set_Referenced (E, R);
4807                   end if;
4808                end;
4809
4810             --  Normal case, not a label: generate reference
4811
4812             --    ??? It is too early to generate a reference here even if the
4813             --    entity is unambiguous, because the tree is not sufficiently
4814             --    typed at this point for Generate_Reference to determine
4815             --    whether this reference modifies the denoted object (because
4816             --    implicit dereferences cannot be identified prior to full type
4817             --    resolution).
4818
4819             --    The Is_Actual_Parameter routine takes care of one of these
4820             --    cases but there are others probably ???
4821
4822             --    If the entity is the LHS of an assignment, and is a variable
4823             --    (rather than a package prefix), we can mark it as a
4824             --    modification right away, to avoid duplicate references.
4825
4826             else
4827                if not Is_Actual_Parameter then
4828                   if Is_LHS (N)
4829                     and then Ekind (E) /= E_Package
4830                     and then Ekind (E) /= E_Generic_Package
4831                   then
4832                      Generate_Reference (E, N, 'm');
4833                   else
4834                      Generate_Reference (E, N);
4835                   end if;
4836                end if;
4837
4838                Check_Nested_Access (E);
4839             end if;
4840
4841             Set_Entity_Or_Discriminal (N, E);
4842
4843             if Ada_Version >= Ada_2012
4844               and then
4845                 (Nkind (Parent (N)) in N_Subexpr
4846                   or else Nkind (Parent (N)) = N_Object_Declaration)
4847             then
4848                Check_Implicit_Dereference (N, Etype (E));
4849             end if;
4850          end if;
4851       end;
4852    end Find_Direct_Name;
4853
4854    ------------------------
4855    -- Find_Expanded_Name --
4856    ------------------------
4857
4858    --  This routine searches the homonym chain of the entity until it finds
4859    --  an entity declared in the scope denoted by the prefix. If the entity
4860    --  is private, it may nevertheless be immediately visible, if we are in
4861    --  the scope of its declaration.
4862
4863    procedure Find_Expanded_Name (N : Node_Id) is
4864       Selector  : constant Node_Id := Selector_Name (N);
4865       Candidate : Entity_Id        := Empty;
4866       P_Name    : Entity_Id;
4867       O_Name    : Entity_Id;
4868       Id        : Entity_Id;
4869
4870    begin
4871       P_Name := Entity (Prefix (N));
4872       O_Name := P_Name;
4873
4874       --  If the prefix is a renamed package, look for the entity in the
4875       --  original package.
4876
4877       if Ekind (P_Name) = E_Package
4878         and then Present (Renamed_Object (P_Name))
4879       then
4880          P_Name := Renamed_Object (P_Name);
4881
4882          --  Rewrite node with entity field pointing to renamed object
4883
4884          Rewrite (Prefix (N), New_Copy (Prefix (N)));
4885          Set_Entity (Prefix (N), P_Name);
4886
4887       --  If the prefix is an object of a concurrent type, look for
4888       --  the entity in the associated task or protected type.
4889
4890       elsif Is_Concurrent_Type (Etype (P_Name)) then
4891          P_Name := Etype (P_Name);
4892       end if;
4893
4894       Id := Current_Entity (Selector);
4895
4896       declare
4897          Is_New_Candidate : Boolean;
4898
4899       begin
4900          while Present (Id) loop
4901             if Scope (Id) = P_Name then
4902                Candidate        := Id;
4903                Is_New_Candidate := True;
4904
4905             --  Ada 2005 (AI-217): Handle shadow entities associated with types
4906             --  declared in limited-withed nested packages. We don't need to
4907             --  handle E_Incomplete_Subtype entities because the entities in
4908             --  the limited view are always E_Incomplete_Type entities (see
4909             --  Build_Limited_Views). Regarding the expression used to evaluate
4910             --  the scope, it is important to note that the limited view also
4911             --  has shadow entities associated nested packages. For this reason
4912             --  the correct scope of the entity is the scope of the real entity
4913             --  The non-limited view may itself be incomplete, in which case
4914             --  get the full view if available.
4915
4916             elsif From_With_Type (Id)
4917               and then Is_Type (Id)
4918               and then Ekind (Id) = E_Incomplete_Type
4919               and then Present (Non_Limited_View (Id))
4920               and then Scope (Non_Limited_View (Id)) = P_Name
4921             then
4922                Candidate        := Get_Full_View (Non_Limited_View (Id));
4923                Is_New_Candidate := True;
4924
4925             else
4926                Is_New_Candidate := False;
4927             end if;
4928
4929             if Is_New_Candidate then
4930                if Is_Child_Unit (Id) then
4931                   exit when Is_Visible_Child_Unit (Id)
4932                     or else Is_Immediately_Visible (Id);
4933
4934                else
4935                   exit when not Is_Hidden (Id)
4936                     or else Is_Immediately_Visible (Id);
4937                end if;
4938             end if;
4939
4940             Id := Homonym (Id);
4941          end loop;
4942       end;
4943
4944       if No (Id)
4945         and then (Ekind (P_Name) = E_Procedure
4946                     or else
4947                   Ekind (P_Name) = E_Function)
4948         and then Is_Generic_Instance (P_Name)
4949       then
4950          --  Expanded name denotes entity in (instance of) generic subprogram.
4951          --  The entity may be in the subprogram instance, or may denote one of
4952          --  the formals, which is declared in the enclosing wrapper package.
4953
4954          P_Name := Scope (P_Name);
4955
4956          Id := Current_Entity (Selector);
4957          while Present (Id) loop
4958             exit when Scope (Id) = P_Name;
4959             Id := Homonym (Id);
4960          end loop;
4961       end if;
4962
4963       if No (Id) or else Chars (Id) /= Chars (Selector) then
4964          Set_Etype (N, Any_Type);
4965
4966          --  If we are looking for an entity defined in System, try to find it
4967          --  in the child package that may have been provided as an extension
4968          --  to System. The Extend_System pragma will have supplied the name of
4969          --  the extension, which may have to be loaded.
4970
4971          if Chars (P_Name) = Name_System
4972            and then Scope (P_Name) = Standard_Standard
4973            and then Present (System_Extend_Unit)
4974            and then Present_System_Aux (N)
4975          then
4976             Set_Entity (Prefix (N), System_Aux_Id);
4977             Find_Expanded_Name (N);
4978             return;
4979
4980          elsif Nkind (Selector) = N_Operator_Symbol
4981            and then Has_Implicit_Operator (N)
4982          then
4983             --  There is an implicit instance of the predefined operator in
4984             --  the given scope. The operator entity is defined in Standard.
4985             --  Has_Implicit_Operator makes the node into an Expanded_Name.
4986
4987             return;
4988
4989          elsif Nkind (Selector) = N_Character_Literal
4990            and then Has_Implicit_Character_Literal (N)
4991          then
4992             --  If there is no literal defined in the scope denoted by the
4993             --  prefix, the literal may belong to (a type derived from)
4994             --  Standard_Character, for which we have no explicit literals.
4995
4996             return;
4997
4998          else
4999             --  If the prefix is a single concurrent object, use its name in
5000             --  the error message, rather than that of the anonymous type.
5001
5002             if Is_Concurrent_Type (P_Name)
5003               and then Is_Internal_Name (Chars (P_Name))
5004             then
5005                Error_Msg_Node_2 := Entity (Prefix (N));
5006             else
5007                Error_Msg_Node_2 := P_Name;
5008             end if;
5009
5010             if P_Name = System_Aux_Id then
5011                P_Name := Scope (P_Name);
5012                Set_Entity (Prefix (N), P_Name);
5013             end if;
5014
5015             if Present (Candidate) then
5016
5017                --  If we know that the unit is a child unit we can give a more
5018                --  accurate error message.
5019
5020                if Is_Child_Unit (Candidate) then
5021
5022                   --  If the candidate is a private child unit and we are in
5023                   --  the visible part of a public unit, specialize the error
5024                   --  message. There might be a private with_clause for it,
5025                   --  but it is not currently active.
5026
5027                   if Is_Private_Descendant (Candidate)
5028                     and then Ekind (Current_Scope) = E_Package
5029                     and then not In_Private_Part (Current_Scope)
5030                     and then not Is_Private_Descendant (Current_Scope)
5031                   then
5032                      Error_Msg_N ("private child unit& is not visible here",
5033                                   Selector);
5034
5035                   --  Normal case where we have a missing with for a child unit
5036
5037                   else
5038                      Error_Msg_Qual_Level := 99;
5039                      Error_Msg_NE -- CODEFIX
5040                        ("missing `WITH &;`", Selector, Candidate);
5041                      Error_Msg_Qual_Level := 0;
5042                   end if;
5043
5044                   --  Here we don't know that this is a child unit
5045
5046                else
5047                   Error_Msg_NE ("& is not a visible entity of&", N, Selector);
5048                end if;
5049
5050             else
5051                --  Within the instantiation of a child unit, the prefix may
5052                --  denote the parent instance, but the selector has the name
5053                --  of the original child. Find whether we are within the
5054                --  corresponding instance, and get the proper entity, which
5055                --  can only be an enclosing scope.
5056
5057                if O_Name /= P_Name
5058                  and then In_Open_Scopes (P_Name)
5059                  and then Is_Generic_Instance (P_Name)
5060                then
5061                   declare
5062                      S : Entity_Id := Current_Scope;
5063                      P : Entity_Id;
5064
5065                   begin
5066                      for J in reverse 0 .. Scope_Stack.Last loop
5067                         S := Scope_Stack.Table (J).Entity;
5068
5069                         exit when S = Standard_Standard;
5070
5071                         if Ekind_In (S, E_Function,
5072                                         E_Package,
5073                                         E_Procedure)
5074                         then
5075                            P := Generic_Parent (Specification
5076                                   (Unit_Declaration_Node (S)));
5077
5078                            if Present (P)
5079                              and then Chars (Scope (P)) = Chars (O_Name)
5080                              and then Chars (P) = Chars (Selector)
5081                            then
5082                               Id := S;
5083                               goto Found;
5084                            end if;
5085                         end if;
5086
5087                      end loop;
5088                   end;
5089                end if;
5090
5091                --  If this is a selection from Ada, System or Interfaces, then
5092                --  we assume a missing with for the corresponding package.
5093
5094                if Is_Known_Unit (N) then
5095                   if not Error_Posted (N) then
5096                      Error_Msg_Node_2 := Selector;
5097                      Error_Msg_N -- CODEFIX
5098                        ("missing `WITH &.&;`", Prefix (N));
5099                   end if;
5100
5101                --  If this is a selection from a dummy package, then suppress
5102                --  the error message, of course the entity is missing if the
5103                --  package is missing!
5104
5105                elsif Sloc (Error_Msg_Node_2) = No_Location then
5106                   null;
5107
5108                --  Here we have the case of an undefined component
5109
5110                else
5111
5112                   --  The prefix may hide a homonym in the context that
5113                   --  declares the desired entity. This error can use a
5114                   --  specialized message.
5115
5116                   if In_Open_Scopes (P_Name)
5117                     and then Present (Homonym (P_Name))
5118                     and then Is_Compilation_Unit (Homonym (P_Name))
5119                     and then
5120                      (Is_Immediately_Visible (Homonym (P_Name))
5121                         or else Is_Visible_Child_Unit (Homonym (P_Name)))
5122                   then
5123                      declare
5124                         H : constant Entity_Id := Homonym (P_Name);
5125
5126                      begin
5127                         Id := First_Entity (H);
5128                         while Present (Id) loop
5129                            if Chars (Id) = Chars (Selector) then
5130                               Error_Msg_Qual_Level := 99;
5131                               Error_Msg_Name_1 := Chars (Selector);
5132                               Error_Msg_NE
5133                                 ("% not declared in&", N, P_Name);
5134                               Error_Msg_NE
5135                                 ("\use fully qualified name starting with"
5136                                   & " Standard to make& visible", N, H);
5137                               Error_Msg_Qual_Level := 0;
5138                               goto Done;
5139                            end if;
5140
5141                            Next_Entity (Id);
5142                         end loop;
5143
5144                         --  If not found, standard error message
5145
5146                         Error_Msg_NE ("& not declared in&", N, Selector);
5147
5148                         <<Done>> null;
5149                      end;
5150
5151                   else
5152                      Error_Msg_NE ("& not declared in&", N, Selector);
5153                   end if;
5154
5155                   --  Check for misspelling of some entity in prefix
5156
5157                   Id := First_Entity (P_Name);
5158                   while Present (Id) loop
5159                      if Is_Bad_Spelling_Of (Chars (Id), Chars (Selector))
5160                        and then not Is_Internal_Name (Chars (Id))
5161                      then
5162                         Error_Msg_NE -- CODEFIX
5163                           ("possible misspelling of&", Selector, Id);
5164                         exit;
5165                      end if;
5166
5167                      Next_Entity (Id);
5168                   end loop;
5169
5170                   --  Specialize the message if this may be an instantiation
5171                   --  of a child unit that was not mentioned in the context.
5172
5173                   if Nkind (Parent (N)) = N_Package_Instantiation
5174                     and then Is_Generic_Instance (Entity (Prefix (N)))
5175                     and then Is_Compilation_Unit
5176                                (Generic_Parent (Parent (Entity (Prefix (N)))))
5177                   then
5178                      Error_Msg_Node_2 := Selector;
5179                      Error_Msg_N -- CODEFIX
5180                        ("\missing `WITH &.&;`", Prefix (N));
5181                   end if;
5182                end if;
5183             end if;
5184
5185             Id := Any_Id;
5186          end if;
5187       end if;
5188
5189       <<Found>>
5190       if Comes_From_Source (N)
5191         and then Is_Remote_Access_To_Subprogram_Type (Id)
5192         and then Present (Equivalent_Type (Id))
5193       then
5194          --  If we are not actually generating distribution code (i.e. the
5195          --  current PCS is the dummy non-distributed version), then the
5196          --  Equivalent_Type will be missing, and Id should be treated as
5197          --  a regular access-to-subprogram type.
5198
5199          Id := Equivalent_Type (Id);
5200          Set_Chars (Selector, Chars (Id));
5201       end if;
5202
5203       --  Ada 2005 (AI-50217): Check usage of entities in limited withed units
5204
5205       if Ekind (P_Name) = E_Package
5206         and then From_With_Type (P_Name)
5207       then
5208          if From_With_Type (Id)
5209            or else Is_Type (Id)
5210            or else Ekind (Id) = E_Package
5211          then
5212             null;
5213          else
5214             Error_Msg_N
5215               ("limited withed package can only be used to access "
5216                & "incomplete types",
5217                 N);
5218          end if;
5219       end if;
5220
5221       if Is_Task_Type (P_Name)
5222         and then ((Ekind (Id) = E_Entry
5223                      and then Nkind (Parent (N)) /= N_Attribute_Reference)
5224                    or else
5225                     (Ekind (Id) = E_Entry_Family
5226                       and then
5227                         Nkind (Parent (Parent (N))) /= N_Attribute_Reference))
5228       then
5229          --  It is an entry call after all, either to the current task (which
5230          --  will deadlock) or to an enclosing task.
5231
5232          Analyze_Selected_Component (N);
5233          return;
5234       end if;
5235
5236       Change_Selected_Component_To_Expanded_Name (N);
5237
5238       --  Do style check and generate reference, but skip both steps if this
5239       --  entity has homonyms, since we may not have the right homonym set yet.
5240       --  The proper homonym will be set during the resolve phase.
5241
5242       if Has_Homonym (Id) then
5243          Set_Entity (N, Id);
5244       else
5245          Set_Entity_Or_Discriminal (N, Id);
5246
5247          if Is_LHS (N) then
5248             Generate_Reference (Id, N, 'm');
5249          else
5250             Generate_Reference (Id, N);
5251          end if;
5252       end if;
5253
5254       if Is_Type (Id) then
5255          Set_Etype (N, Id);
5256       else
5257          Set_Etype (N, Get_Full_View (Etype (Id)));
5258       end if;
5259
5260       --  Check for violation of No_Wide_Characters
5261
5262       Check_Wide_Character_Restriction (Id, N);
5263
5264       --  If the Ekind of the entity is Void, it means that all homonyms are
5265       --  hidden from all visibility (RM 8.3(5,14-20)).
5266
5267       if Ekind (Id) = E_Void then
5268          Premature_Usage (N);
5269
5270       elsif Is_Overloadable (Id)
5271         and then Present (Homonym (Id))
5272       then
5273          declare
5274             H : Entity_Id := Homonym (Id);
5275
5276          begin
5277             while Present (H) loop
5278                if Scope (H) = Scope (Id)
5279                  and then
5280                    (not Is_Hidden (H)
5281                       or else Is_Immediately_Visible (H))
5282                then
5283                   Collect_Interps (N);
5284                   exit;
5285                end if;
5286
5287                H := Homonym (H);
5288             end loop;
5289
5290             --  If an extension of System is present, collect possible explicit
5291             --  overloadings declared in the extension.
5292
5293             if Chars (P_Name) = Name_System
5294               and then Scope (P_Name) = Standard_Standard
5295               and then Present (System_Extend_Unit)
5296               and then Present_System_Aux (N)
5297             then
5298                H := Current_Entity (Id);
5299
5300                while Present (H) loop
5301                   if Scope (H) = System_Aux_Id then
5302                      Add_One_Interp (N, H, Etype (H));
5303                   end if;
5304
5305                   H := Homonym (H);
5306                end loop;
5307             end if;
5308          end;
5309       end if;
5310
5311       if Nkind (Selector_Name (N)) = N_Operator_Symbol
5312         and then Scope (Id) /= Standard_Standard
5313       then
5314          --  In addition to user-defined operators in the given scope, there
5315          --  may be an implicit instance of the predefined operator. The
5316          --  operator (defined in Standard) is found in Has_Implicit_Operator,
5317          --  and added to the interpretations. Procedure Add_One_Interp will
5318          --  determine which hides which.
5319
5320          if Has_Implicit_Operator (N) then
5321             null;
5322          end if;
5323       end if;
5324    end Find_Expanded_Name;
5325
5326    -------------------------
5327    -- Find_Renamed_Entity --
5328    -------------------------
5329
5330    function Find_Renamed_Entity
5331      (N         : Node_Id;
5332       Nam       : Node_Id;
5333       New_S     : Entity_Id;
5334       Is_Actual : Boolean := False) return Entity_Id
5335    is
5336       Ind   : Interp_Index;
5337       I1    : Interp_Index := 0; -- Suppress junk warnings
5338       It    : Interp;
5339       It1   : Interp;
5340       Old_S : Entity_Id;
5341       Inst  : Entity_Id;
5342
5343       function Enclosing_Instance return Entity_Id;
5344       --  If the renaming determines the entity for the default of a formal
5345       --  subprogram nested within another instance, choose the innermost
5346       --  candidate. This is because if the formal has a box, and we are within
5347       --  an enclosing instance where some candidate interpretations are local
5348       --  to this enclosing instance, we know that the default was properly
5349       --  resolved when analyzing the generic, so we prefer the local
5350       --  candidates to those that are external. This is not always the case
5351       --  but is a reasonable heuristic on the use of nested generics. The
5352       --  proper solution requires a full renaming model.
5353
5354       function Is_Visible_Operation (Op : Entity_Id) return Boolean;
5355       --  If the renamed entity is an implicit operator, check whether it is
5356       --  visible because its operand type is properly visible. This check
5357       --  applies to explicit renamed entities that appear in the source in a
5358       --  renaming declaration or a formal subprogram instance, but not to
5359       --  default generic actuals with a name.
5360
5361       function Report_Overload return Entity_Id;
5362       --  List possible interpretations, and specialize message in the
5363       --  case of a generic actual.
5364
5365       function Within (Inner, Outer : Entity_Id) return Boolean;
5366       --  Determine whether a candidate subprogram is defined within the
5367       --  enclosing instance. If yes, it has precedence over outer candidates.
5368
5369       ------------------------
5370       -- Enclosing_Instance --
5371       ------------------------
5372
5373       function Enclosing_Instance return Entity_Id is
5374          S : Entity_Id;
5375
5376       begin
5377          if not Is_Generic_Instance (Current_Scope)
5378            and then not Is_Actual
5379          then
5380             return Empty;
5381          end if;
5382
5383          S := Scope (Current_Scope);
5384          while S /= Standard_Standard loop
5385             if Is_Generic_Instance (S) then
5386                return S;
5387             end if;
5388
5389             S := Scope (S);
5390          end loop;
5391
5392          return Empty;
5393       end Enclosing_Instance;
5394
5395       --------------------------
5396       -- Is_Visible_Operation --
5397       --------------------------
5398
5399       function Is_Visible_Operation (Op : Entity_Id) return Boolean is
5400          Scop : Entity_Id;
5401          Typ  : Entity_Id;
5402          Btyp : Entity_Id;
5403
5404       begin
5405          if Ekind (Op) /= E_Operator
5406            or else Scope (Op) /= Standard_Standard
5407            or else (In_Instance
5408                       and then
5409                         (not Is_Actual
5410                            or else Present (Enclosing_Instance)))
5411          then
5412             return True;
5413
5414          else
5415             --  For a fixed point type operator, check the resulting type,
5416             --  because it may be a mixed mode integer * fixed operation.
5417
5418             if Present (Next_Formal (First_Formal (New_S)))
5419               and then Is_Fixed_Point_Type (Etype (New_S))
5420             then
5421                Typ := Etype (New_S);
5422             else
5423                Typ := Etype (First_Formal (New_S));
5424             end if;
5425
5426             Btyp := Base_Type (Typ);
5427
5428             if Nkind (Nam) /= N_Expanded_Name then
5429                return (In_Open_Scopes (Scope (Btyp))
5430                         or else Is_Potentially_Use_Visible (Btyp)
5431                         or else In_Use (Btyp)
5432                         or else In_Use (Scope (Btyp)));
5433
5434             else
5435                Scop := Entity (Prefix (Nam));
5436
5437                if Ekind (Scop) = E_Package
5438                  and then Present (Renamed_Object (Scop))
5439                then
5440                   Scop := Renamed_Object (Scop);
5441                end if;
5442
5443                --  Operator is visible if prefix of expanded name denotes
5444                --  scope of type, or else type is defined in System_Aux
5445                --  and the prefix denotes System.
5446
5447                return Scope (Btyp) = Scop
5448                  or else (Scope (Btyp) = System_Aux_Id
5449                            and then Scope (Scope (Btyp)) = Scop);
5450             end if;
5451          end if;
5452       end Is_Visible_Operation;
5453
5454       ------------
5455       -- Within --
5456       ------------
5457
5458       function Within (Inner, Outer : Entity_Id) return Boolean is
5459          Sc : Entity_Id;
5460
5461       begin
5462          Sc := Scope (Inner);
5463          while Sc /= Standard_Standard loop
5464             if Sc = Outer then
5465                return True;
5466             else
5467                Sc := Scope (Sc);
5468             end if;
5469          end loop;
5470
5471          return False;
5472       end Within;
5473
5474       ---------------------
5475       -- Report_Overload --
5476       ---------------------
5477
5478       function Report_Overload return Entity_Id is
5479       begin
5480          if Is_Actual then
5481             Error_Msg_NE -- CODEFIX
5482               ("ambiguous actual subprogram&, " &
5483                  "possible interpretations:", N, Nam);
5484          else
5485             Error_Msg_N -- CODEFIX
5486               ("ambiguous subprogram, " &
5487                  "possible interpretations:", N);
5488          end if;
5489
5490          List_Interps (Nam, N);
5491          return Old_S;
5492       end Report_Overload;
5493
5494    --  Start of processing for Find_Renamed_Entity
5495
5496    begin
5497       Old_S := Any_Id;
5498       Candidate_Renaming := Empty;
5499
5500       if not Is_Overloaded (Nam) then
5501          if Entity_Matches_Spec (Entity (Nam), New_S) then
5502             Candidate_Renaming := New_S;
5503
5504             if Is_Visible_Operation (Entity (Nam)) then
5505                Old_S := Entity (Nam);
5506             end if;
5507
5508          elsif
5509            Present (First_Formal (Entity (Nam)))
5510              and then Present (First_Formal (New_S))
5511              and then (Base_Type (Etype (First_Formal (Entity (Nam))))
5512                         = Base_Type (Etype (First_Formal (New_S))))
5513          then
5514             Candidate_Renaming := Entity (Nam);
5515          end if;
5516
5517       else
5518          Get_First_Interp (Nam, Ind, It);
5519          while Present (It.Nam) loop
5520             if Entity_Matches_Spec (It.Nam, New_S)
5521                and then Is_Visible_Operation (It.Nam)
5522             then
5523                if Old_S /= Any_Id then
5524
5525                   --  Note: The call to Disambiguate only happens if a
5526                   --  previous interpretation was found, in which case I1
5527                   --  has received a value.
5528
5529                   It1 := Disambiguate (Nam, I1, Ind, Etype (Old_S));
5530
5531                   if It1 = No_Interp then
5532                      Inst := Enclosing_Instance;
5533
5534                      if Present (Inst) then
5535                         if Within (It.Nam, Inst) then
5536                            if Within (Old_S, Inst) then
5537
5538                               --  Choose the innermost subprogram, which would
5539                               --  have hidden the outer one in the generic.
5540
5541                               if Scope_Depth (It.Nam) <
5542                                 Scope_Depth (Old_S)
5543                               then
5544                                  return Old_S;
5545                               else
5546                                  return It.Nam;
5547                               end if;
5548                            end if;
5549
5550                         elsif Within (Old_S, Inst) then
5551                            return (Old_S);
5552
5553                         else
5554                            return Report_Overload;
5555                         end if;
5556
5557                      --  If not within an instance, ambiguity is real
5558
5559                      else
5560                         return Report_Overload;
5561                      end if;
5562
5563                   else
5564                      Old_S := It1.Nam;
5565                      exit;
5566                   end if;
5567
5568                else
5569                   I1 := Ind;
5570                   Old_S := It.Nam;
5571                end if;
5572
5573             elsif
5574               Present (First_Formal (It.Nam))
5575                 and then Present (First_Formal (New_S))
5576                 and then  (Base_Type (Etype (First_Formal (It.Nam)))
5577                             = Base_Type (Etype (First_Formal (New_S))))
5578             then
5579                Candidate_Renaming := It.Nam;
5580             end if;
5581
5582             Get_Next_Interp (Ind, It);
5583          end loop;
5584
5585          Set_Entity (Nam, Old_S);
5586
5587          if Old_S /= Any_Id then
5588             Set_Is_Overloaded (Nam, False);
5589          end if;
5590       end if;
5591
5592       return Old_S;
5593    end Find_Renamed_Entity;
5594
5595    -----------------------------
5596    -- Find_Selected_Component --
5597    -----------------------------
5598
5599    procedure Find_Selected_Component (N : Node_Id) is
5600       P : constant Node_Id := Prefix (N);
5601
5602       P_Name : Entity_Id;
5603       --  Entity denoted by prefix
5604
5605       P_Type : Entity_Id;
5606       --  and its type
5607
5608       Nam : Node_Id;
5609
5610    begin
5611       Analyze (P);
5612
5613       if Nkind (P) = N_Error then
5614          return;
5615       end if;
5616
5617       --  Selector name cannot be a character literal or an operator symbol in
5618       --  SPARK, except for the operator symbol in a renaming.
5619
5620       if Restriction_Check_Required (SPARK) then
5621          if Nkind (Selector_Name (N)) = N_Character_Literal then
5622             Check_SPARK_Restriction
5623               ("character literal cannot be prefixed", N);
5624          elsif Nkind (Selector_Name (N)) = N_Operator_Symbol
5625            and then Nkind (Parent (N)) /= N_Subprogram_Renaming_Declaration
5626          then
5627             Check_SPARK_Restriction ("operator symbol cannot be prefixed", N);
5628          end if;
5629       end if;
5630
5631       --  If the selector already has an entity, the node has been constructed
5632       --  in the course of expansion, and is known to be valid. Do not verify
5633       --  that it is defined for the type (it may be a private component used
5634       --  in the expansion of record equality).
5635
5636       if Present (Entity (Selector_Name (N))) then
5637          if No (Etype (N))
5638            or else Etype (N) = Any_Type
5639          then
5640             declare
5641                Sel_Name : constant Node_Id   := Selector_Name (N);
5642                Selector : constant Entity_Id := Entity (Sel_Name);
5643                C_Etype  : Node_Id;
5644
5645             begin
5646                Set_Etype (Sel_Name, Etype (Selector));
5647
5648                if not Is_Entity_Name (P) then
5649                   Resolve (P);
5650                end if;
5651
5652                --  Build an actual subtype except for the first parameter
5653                --  of an init proc, where this actual subtype is by
5654                --  definition incorrect, since the object is uninitialized
5655                --  (and does not even have defined discriminants etc.)
5656
5657                if Is_Entity_Name (P)
5658                  and then Ekind (Entity (P)) = E_Function
5659                then
5660                   Nam := New_Copy (P);
5661
5662                   if Is_Overloaded (P) then
5663                      Save_Interps (P, Nam);
5664                   end if;
5665
5666                   Rewrite (P,
5667                     Make_Function_Call (Sloc (P), Name => Nam));
5668                   Analyze_Call (P);
5669                   Analyze_Selected_Component (N);
5670                   return;
5671
5672                elsif Ekind (Selector) = E_Component
5673                  and then (not Is_Entity_Name (P)
5674                             or else Chars (Entity (P)) /= Name_uInit)
5675                then
5676                   --  Do not build the subtype when referencing components of
5677                   --  dispatch table wrappers. Required to avoid generating
5678                   --  elaboration code with HI runtimes. JVM and .NET use a
5679                   --  modified version of Ada.Tags which does not contain RE_
5680                   --  Dispatch_Table_Wrapper and RE_No_Dispatch_Table_Wrapper.
5681                   --  Avoid raising RE_Not_Available exception in those cases.
5682
5683                   if VM_Target = No_VM
5684                     and then RTU_Loaded (Ada_Tags)
5685                     and then
5686                       ((RTE_Available (RE_Dispatch_Table_Wrapper)
5687                          and then Scope (Selector) =
5688                                      RTE (RE_Dispatch_Table_Wrapper))
5689                           or else
5690                        (RTE_Available (RE_No_Dispatch_Table_Wrapper)
5691                          and then Scope (Selector) =
5692                                      RTE (RE_No_Dispatch_Table_Wrapper)))
5693                   then
5694                      C_Etype := Empty;
5695
5696                   else
5697                      C_Etype :=
5698                        Build_Actual_Subtype_Of_Component
5699                          (Etype (Selector), N);
5700                   end if;
5701
5702                else
5703                   C_Etype := Empty;
5704                end if;
5705
5706                if No (C_Etype) then
5707                   C_Etype := Etype (Selector);
5708                else
5709                   Insert_Action (N, C_Etype);
5710                   C_Etype := Defining_Identifier (C_Etype);
5711                end if;
5712
5713                Set_Etype (N, C_Etype);
5714             end;
5715
5716             --  If this is the name of an entry or protected operation, and
5717             --  the prefix is an access type, insert an explicit dereference,
5718             --  so that entry calls are treated uniformly.
5719
5720             if Is_Access_Type (Etype (P))
5721               and then Is_Concurrent_Type (Designated_Type (Etype (P)))
5722             then
5723                declare
5724                   New_P : constant Node_Id :=
5725                             Make_Explicit_Dereference (Sloc (P),
5726                               Prefix => Relocate_Node (P));
5727                begin
5728                   Rewrite (P, New_P);
5729                   Set_Etype (P, Designated_Type (Etype (Prefix (P))));
5730                end;
5731             end if;
5732
5733          --  If the selected component appears within a default expression
5734          --  and it has an actual subtype, the pre-analysis has not yet
5735          --  completed its analysis, because Insert_Actions is disabled in
5736          --  that context. Within the init proc of the enclosing type we
5737          --  must complete this analysis, if an actual subtype was created.
5738
5739          elsif Inside_Init_Proc then
5740             declare
5741                Typ  : constant Entity_Id := Etype (N);
5742                Decl : constant Node_Id   := Declaration_Node (Typ);
5743             begin
5744                if Nkind (Decl) = N_Subtype_Declaration
5745                  and then not Analyzed (Decl)
5746                  and then Is_List_Member (Decl)
5747                  and then No (Parent (Decl))
5748                then
5749                   Remove (Decl);
5750                   Insert_Action (N, Decl);
5751                end if;
5752             end;
5753          end if;
5754
5755          return;
5756
5757       elsif Is_Entity_Name (P) then
5758          P_Name := Entity (P);
5759
5760          --  The prefix may denote an enclosing type which is the completion
5761          --  of an incomplete type declaration.
5762
5763          if Is_Type (P_Name) then
5764             Set_Entity (P, Get_Full_View (P_Name));
5765             Set_Etype  (P, Entity (P));
5766             P_Name := Entity (P);
5767          end if;
5768
5769          P_Type := Base_Type (Etype (P));
5770
5771          if Debug_Flag_E then
5772             Write_Str ("Found prefix type to be ");
5773             Write_Entity_Info (P_Type, "      "); Write_Eol;
5774          end if;
5775
5776          --  First check for components of a record object (not the
5777          --  result of a call, which is handled below).
5778
5779          if Is_Appropriate_For_Record (P_Type)
5780            and then not Is_Overloadable (P_Name)
5781            and then not Is_Type (P_Name)
5782          then
5783             --  Selected component of record. Type checking will validate
5784             --  name of selector.
5785             --  ??? could we rewrite an implicit dereference into an explicit
5786             --  one here?
5787
5788             Analyze_Selected_Component (N);
5789
5790          --  Reference to type name in predicate/invariant expression
5791
5792          elsif Is_Appropriate_For_Entry_Prefix (P_Type)
5793            and then not In_Open_Scopes (P_Name)
5794            and then (not Is_Concurrent_Type (Etype (P_Name))
5795                        or else not In_Open_Scopes (Etype (P_Name)))
5796          then
5797             --  Call to protected operation or entry. Type checking is
5798             --  needed on the prefix.
5799
5800             Analyze_Selected_Component (N);
5801
5802          elsif (In_Open_Scopes (P_Name)
5803                  and then Ekind (P_Name) /= E_Void
5804                  and then not Is_Overloadable (P_Name))
5805            or else (Is_Concurrent_Type (Etype (P_Name))
5806                      and then In_Open_Scopes (Etype (P_Name)))
5807          then
5808             --  Prefix denotes an enclosing loop, block, or task, i.e. an
5809             --  enclosing construct that is not a subprogram or accept.
5810
5811             Find_Expanded_Name (N);
5812
5813          elsif Ekind (P_Name) = E_Package then
5814             Find_Expanded_Name (N);
5815
5816          elsif Is_Overloadable (P_Name) then
5817
5818             --  The subprogram may be a renaming (of an enclosing scope) as
5819             --  in the case of the name of the generic within an instantiation.
5820
5821             if Ekind_In (P_Name, E_Procedure, E_Function)
5822               and then Present (Alias (P_Name))
5823               and then Is_Generic_Instance (Alias (P_Name))
5824             then
5825                P_Name := Alias (P_Name);
5826             end if;
5827
5828             if Is_Overloaded (P) then
5829
5830                --  The prefix must resolve to a unique enclosing construct
5831
5832                declare
5833                   Found : Boolean := False;
5834                   Ind   : Interp_Index;
5835                   It    : Interp;
5836
5837                begin
5838                   Get_First_Interp (P, Ind, It);
5839                   while Present (It.Nam) loop
5840                      if In_Open_Scopes (It.Nam) then
5841                         if Found then
5842                            Error_Msg_N (
5843                               "prefix must be unique enclosing scope", N);
5844                            Set_Entity (N, Any_Id);
5845                            Set_Etype  (N, Any_Type);
5846                            return;
5847
5848                         else
5849                            Found := True;
5850                            P_Name := It.Nam;
5851                         end if;
5852                      end if;
5853
5854                      Get_Next_Interp (Ind, It);
5855                   end loop;
5856                end;
5857             end if;
5858
5859             if In_Open_Scopes (P_Name) then
5860                Set_Entity (P, P_Name);
5861                Set_Is_Overloaded (P, False);
5862                Find_Expanded_Name (N);
5863
5864             else
5865                --  If no interpretation as an expanded name is possible, it
5866                --  must be a selected component of a record returned by a
5867                --  function call. Reformat prefix as a function call, the rest
5868                --  is done by type resolution. If the prefix is procedure or
5869                --  entry, as is P.X; this is an error.
5870
5871                if Ekind (P_Name) /= E_Function
5872                  and then (not Is_Overloaded (P)
5873                              or else
5874                            Nkind (Parent (N)) = N_Procedure_Call_Statement)
5875                then
5876                   --  Prefix may mention a package that is hidden by a local
5877                   --  declaration: let the user know. Scan the full homonym
5878                   --  chain, the candidate package may be anywhere on it.
5879
5880                   if Present (Homonym (Current_Entity (P_Name))) then
5881
5882                      P_Name := Current_Entity (P_Name);
5883
5884                      while Present (P_Name) loop
5885                         exit when Ekind (P_Name) = E_Package;
5886                         P_Name := Homonym (P_Name);
5887                      end loop;
5888
5889                      if Present (P_Name) then
5890                         Error_Msg_Sloc := Sloc (Entity (Prefix (N)));
5891
5892                         Error_Msg_NE
5893                           ("package& is hidden by declaration#",
5894                             N, P_Name);
5895
5896                         Set_Entity (Prefix (N), P_Name);
5897                         Find_Expanded_Name (N);
5898                         return;
5899                      else
5900                         P_Name := Entity (Prefix (N));
5901                      end if;
5902                   end if;
5903
5904                   Error_Msg_NE
5905                     ("invalid prefix in selected component&", N, P_Name);
5906                   Change_Selected_Component_To_Expanded_Name (N);
5907                   Set_Entity (N, Any_Id);
5908                   Set_Etype (N, Any_Type);
5909
5910                else
5911                   Nam := New_Copy (P);
5912                   Save_Interps (P, Nam);
5913                   Rewrite (P,
5914                     Make_Function_Call (Sloc (P), Name => Nam));
5915                   Analyze_Call (P);
5916                   Analyze_Selected_Component (N);
5917                end if;
5918             end if;
5919
5920          --  Remaining cases generate various error messages
5921
5922          else
5923             --  Format node as expanded name, to avoid cascaded errors
5924
5925             Change_Selected_Component_To_Expanded_Name (N);
5926             Set_Entity  (N, Any_Id);
5927             Set_Etype   (N, Any_Type);
5928
5929             --  Issue error message, but avoid this if error issued already.
5930             --  Use identifier of prefix if one is available.
5931
5932             if P_Name = Any_Id  then
5933                null;
5934
5935             elsif Ekind (P_Name) = E_Void then
5936                Premature_Usage (P);
5937
5938             elsif Nkind (P) /= N_Attribute_Reference then
5939                Error_Msg_N (
5940                 "invalid prefix in selected component&", P);
5941
5942                if Is_Access_Type (P_Type)
5943                  and then Ekind (Designated_Type (P_Type)) = E_Incomplete_Type
5944                then
5945                   Error_Msg_N
5946                     ("\dereference must not be of an incomplete type " &
5947                        "(RM 3.10.1)", P);
5948                end if;
5949
5950             else
5951                Error_Msg_N (
5952                 "invalid prefix in selected component", P);
5953             end if;
5954          end if;
5955
5956          --  Selector name is restricted in SPARK
5957
5958          if Nkind (N) = N_Expanded_Name
5959            and then Restriction_Check_Required (SPARK)
5960          then
5961             if Is_Subprogram (P_Name) then
5962                Check_SPARK_Restriction
5963                  ("prefix of expanded name cannot be a subprogram", P);
5964             elsif Ekind (P_Name) = E_Loop then
5965                Check_SPARK_Restriction
5966                  ("prefix of expanded name cannot be a loop statement", P);
5967             end if;
5968          end if;
5969
5970       else
5971          --  If prefix is not the name of an entity, it must be an expression,
5972          --  whose type is appropriate for a record. This is determined by
5973          --  type resolution.
5974
5975          Analyze_Selected_Component (N);
5976       end if;
5977    end Find_Selected_Component;
5978
5979    ---------------
5980    -- Find_Type --
5981    ---------------
5982
5983    procedure Find_Type (N : Node_Id) is
5984       C      : Entity_Id;
5985       Typ    : Entity_Id;
5986       T      : Entity_Id;
5987       T_Name : Entity_Id;
5988
5989    begin
5990       if N = Error then
5991          return;
5992
5993       elsif Nkind (N) = N_Attribute_Reference then
5994
5995          --  Class attribute. This is not valid in Ada 83 mode, but we do not
5996          --  need to enforce that at this point, since the declaration of the
5997          --  tagged type in the prefix would have been flagged already.
5998
5999          if Attribute_Name (N) = Name_Class then
6000             Check_Restriction (No_Dispatch, N);
6001             Find_Type (Prefix (N));
6002
6003             --  Propagate error from bad prefix
6004
6005             if Etype (Prefix (N)) = Any_Type then
6006                Set_Entity (N, Any_Type);
6007                Set_Etype  (N, Any_Type);
6008                return;
6009             end if;
6010
6011             T := Base_Type (Entity (Prefix (N)));
6012
6013             --  Case where type is not known to be tagged. Its appearance in
6014             --  the prefix of the 'Class attribute indicates that the full view
6015             --  will be tagged.
6016
6017             if not Is_Tagged_Type (T) then
6018                if Ekind (T) = E_Incomplete_Type then
6019
6020                   --  It is legal to denote the class type of an incomplete
6021                   --  type. The full type will have to be tagged, of course.
6022                   --  In Ada 2005 this usage is declared obsolescent, so we
6023                   --  warn accordingly. This usage is only legal if the type
6024                   --  is completed in the current scope, and not for a limited
6025                   --  view of a type.
6026
6027                   if not Is_Tagged_Type (T)
6028                     and then Ada_Version >= Ada_2005
6029                   then
6030                      if From_With_Type (T) then
6031                         Error_Msg_N
6032                           ("prefix of Class attribute must be tagged", N);
6033                         Set_Etype (N, Any_Type);
6034                         Set_Entity (N, Any_Type);
6035                         return;
6036
6037                   --  ??? This test is temporarily disabled (always False)
6038                   --  because it causes an unwanted warning on GNAT sources
6039                   --  (built with -gnatg, which includes Warn_On_Obsolescent_
6040                   --  Feature). Once this issue is cleared in the sources, it
6041                   --  can be enabled.
6042
6043                      elsif Warn_On_Obsolescent_Feature
6044                        and then False
6045                      then
6046                         Error_Msg_N
6047                           ("applying 'Class to an untagged incomplete type"
6048                            & " is an obsolescent feature  (RM J.11)", N);
6049                      end if;
6050                   end if;
6051
6052                   Set_Is_Tagged_Type (T);
6053                   Set_Direct_Primitive_Operations (T, New_Elmt_List);
6054                   Make_Class_Wide_Type (T);
6055                   Set_Entity (N, Class_Wide_Type (T));
6056                   Set_Etype  (N, Class_Wide_Type (T));
6057
6058                elsif Ekind (T) = E_Private_Type
6059                  and then not Is_Generic_Type (T)
6060                  and then In_Private_Part (Scope (T))
6061                then
6062                   --  The Class attribute can be applied to an untagged private
6063                   --  type fulfilled by a tagged type prior to the full type
6064                   --  declaration (but only within the parent package's private
6065                   --  part). Create the class-wide type now and check that the
6066                   --  full type is tagged later during its analysis. Note that
6067                   --  we do not mark the private type as tagged, unlike the
6068                   --  case of incomplete types, because the type must still
6069                   --  appear untagged to outside units.
6070
6071                   if No (Class_Wide_Type (T)) then
6072                      Make_Class_Wide_Type (T);
6073                   end if;
6074
6075                   Set_Entity (N, Class_Wide_Type (T));
6076                   Set_Etype  (N, Class_Wide_Type (T));
6077
6078                else
6079                   --  Should we introduce a type Any_Tagged and use Wrong_Type
6080                   --  here, it would be a bit more consistent???
6081
6082                   Error_Msg_NE
6083                     ("tagged type required, found}",
6084                      Prefix (N), First_Subtype (T));
6085                   Set_Entity (N, Any_Type);
6086                   return;
6087                end if;
6088
6089             --  Case of tagged type
6090
6091             else
6092                if Is_Concurrent_Type (T) then
6093                   if No (Corresponding_Record_Type (Entity (Prefix (N)))) then
6094
6095                      --  Previous error. Use current type, which at least
6096                      --  provides some operations.
6097
6098                      C := Entity (Prefix (N));
6099
6100                   else
6101                      C := Class_Wide_Type
6102                             (Corresponding_Record_Type (Entity (Prefix (N))));
6103                   end if;
6104
6105                else
6106                   C := Class_Wide_Type (Entity (Prefix (N)));
6107                end if;
6108
6109                Set_Entity_With_Style_Check (N, C);
6110                Generate_Reference (C, N);
6111                Set_Etype (N, C);
6112             end if;
6113
6114          --  Base attribute, not allowed in Ada 83
6115
6116          elsif Attribute_Name (N) = Name_Base then
6117             Error_Msg_Name_1 := Name_Base;
6118             Check_SPARK_Restriction
6119               ("attribute% is only allowed as prefix of another attribute", N);
6120
6121             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
6122                Error_Msg_N
6123                  ("(Ada 83) Base attribute not allowed in subtype mark", N);
6124
6125             else
6126                Find_Type (Prefix (N));
6127                Typ := Entity (Prefix (N));
6128
6129                if Ada_Version >= Ada_95
6130                  and then not Is_Scalar_Type (Typ)
6131                  and then not Is_Generic_Type (Typ)
6132                then
6133                   Error_Msg_N
6134                     ("prefix of Base attribute must be scalar type",
6135                       Prefix (N));
6136
6137                elsif Warn_On_Redundant_Constructs
6138                  and then Base_Type (Typ) = Typ
6139                then
6140                   Error_Msg_NE -- CODEFIX
6141                     ("?redundant attribute, & is its own base type", N, Typ);
6142                end if;
6143
6144                T := Base_Type (Typ);
6145
6146                --  Rewrite attribute reference with type itself (see similar
6147                --  processing in Analyze_Attribute, case Base). Preserve prefix
6148                --  if present, for other legality checks.
6149
6150                if Nkind (Prefix (N)) = N_Expanded_Name then
6151                   Rewrite (N,
6152                      Make_Expanded_Name (Sloc (N),
6153                        Chars         => Chars (T),
6154                        Prefix        => New_Copy (Prefix (Prefix (N))),
6155                        Selector_Name => New_Reference_To (T, Sloc (N))));
6156
6157                else
6158                   Rewrite (N, New_Reference_To (T, Sloc (N)));
6159                end if;
6160
6161                Set_Entity (N, T);
6162                Set_Etype (N, T);
6163             end if;
6164
6165          elsif Attribute_Name (N) = Name_Stub_Type then
6166
6167             --  This is handled in Analyze_Attribute
6168
6169             Analyze (N);
6170
6171          --  All other attributes are invalid in a subtype mark
6172
6173          else
6174             Error_Msg_N ("invalid attribute in subtype mark", N);
6175          end if;
6176
6177       else
6178          Analyze (N);
6179
6180          if Is_Entity_Name (N) then
6181             T_Name := Entity (N);
6182          else
6183             Error_Msg_N ("subtype mark required in this context", N);
6184             Set_Etype (N, Any_Type);
6185             return;
6186          end if;
6187
6188          if T_Name  = Any_Id or else Etype (N) = Any_Type then
6189
6190             --  Undefined id. Make it into a valid type
6191
6192             Set_Entity (N, Any_Type);
6193
6194          elsif not Is_Type (T_Name)
6195            and then T_Name /= Standard_Void_Type
6196          then
6197             Error_Msg_Sloc := Sloc (T_Name);
6198             Error_Msg_N ("subtype mark required in this context", N);
6199             Error_Msg_NE ("\\found & declared#", N, T_Name);
6200             Set_Entity (N, Any_Type);
6201
6202          else
6203             --  If the type is an incomplete type created to handle
6204             --  anonymous access components of a record type, then the
6205             --  incomplete type is the visible entity and subsequent
6206             --  references will point to it. Mark the original full
6207             --  type as referenced, to prevent spurious warnings.
6208
6209             if Is_Incomplete_Type (T_Name)
6210               and then Present (Full_View (T_Name))
6211               and then not Comes_From_Source (T_Name)
6212             then
6213                Set_Referenced (Full_View (T_Name));
6214             end if;
6215
6216             T_Name := Get_Full_View (T_Name);
6217
6218             --  Ada 2005 (AI-251, AI-50217): Handle interfaces visible through
6219             --  limited-with clauses
6220
6221             if From_With_Type (T_Name)
6222               and then Ekind (T_Name) in Incomplete_Kind
6223               and then Present (Non_Limited_View (T_Name))
6224               and then Is_Interface (Non_Limited_View (T_Name))
6225             then
6226                T_Name := Non_Limited_View (T_Name);
6227             end if;
6228
6229             if In_Open_Scopes (T_Name) then
6230                if Ekind (Base_Type (T_Name)) = E_Task_Type then
6231
6232                   --  In Ada 2005, a task name can be used in an access
6233                   --  definition within its own body. It cannot be used
6234                   --  in the discriminant part of the task declaration,
6235                   --  nor anywhere else in the declaration because entries
6236                   --  cannot have access parameters.
6237
6238                   if Ada_Version >= Ada_2005
6239                     and then Nkind (Parent (N)) = N_Access_Definition
6240                   then
6241                      Set_Entity (N, T_Name);
6242                      Set_Etype  (N, T_Name);
6243
6244                      if Has_Completion (T_Name) then
6245                         return;
6246
6247                      else
6248                         Error_Msg_N
6249                           ("task type cannot be used as type mark " &
6250                            "within its own declaration", N);
6251                      end if;
6252
6253                   else
6254                      Error_Msg_N
6255                        ("task type cannot be used as type mark " &
6256                         "within its own spec or body", N);
6257                   end if;
6258
6259                elsif Ekind (Base_Type (T_Name)) = E_Protected_Type then
6260
6261                   --  In Ada 2005, a protected name can be used in an access
6262                   --  definition within its own body.
6263
6264                   if Ada_Version >= Ada_2005
6265                     and then Nkind (Parent (N)) = N_Access_Definition
6266                   then
6267                      Set_Entity (N, T_Name);
6268                      Set_Etype  (N, T_Name);
6269                      return;
6270
6271                   else
6272                      Error_Msg_N
6273                        ("protected type cannot be used as type mark " &
6274                         "within its own spec or body", N);
6275                   end if;
6276
6277                else
6278                   Error_Msg_N ("type declaration cannot refer to itself", N);
6279                end if;
6280
6281                Set_Etype (N, Any_Type);
6282                Set_Entity (N, Any_Type);
6283                Set_Error_Posted (T_Name);
6284                return;
6285             end if;
6286
6287             Set_Entity (N, T_Name);
6288             Set_Etype  (N, T_Name);
6289          end if;
6290       end if;
6291
6292       if Present (Etype (N)) and then Comes_From_Source (N) then
6293          if Is_Fixed_Point_Type (Etype (N)) then
6294             Check_Restriction (No_Fixed_Point, N);
6295          elsif Is_Floating_Point_Type (Etype (N)) then
6296             Check_Restriction (No_Floating_Point, N);
6297          end if;
6298       end if;
6299    end Find_Type;
6300
6301    ------------------------------------
6302    -- Has_Implicit_Character_Literal --
6303    ------------------------------------
6304
6305    function Has_Implicit_Character_Literal (N : Node_Id) return Boolean is
6306       Id      : Entity_Id;
6307       Found   : Boolean := False;
6308       P       : constant Entity_Id := Entity (Prefix (N));
6309       Priv_Id : Entity_Id := Empty;
6310
6311    begin
6312       if Ekind (P) = E_Package
6313         and then not In_Open_Scopes (P)
6314       then
6315          Priv_Id := First_Private_Entity (P);
6316       end if;
6317
6318       if P = Standard_Standard then
6319          Change_Selected_Component_To_Expanded_Name (N);
6320          Rewrite (N, Selector_Name (N));
6321          Analyze (N);
6322          Set_Etype (Original_Node (N), Standard_Character);
6323          return True;
6324       end if;
6325
6326       Id := First_Entity (P);
6327       while Present (Id)
6328         and then Id /= Priv_Id
6329       loop
6330          if Is_Standard_Character_Type (Id) and then Is_Base_Type (Id) then
6331
6332             --  We replace the node with the literal itself, resolve as a
6333             --  character, and set the type correctly.
6334
6335             if not Found then
6336                Change_Selected_Component_To_Expanded_Name (N);
6337                Rewrite (N, Selector_Name (N));
6338                Analyze (N);
6339                Set_Etype (N, Id);
6340                Set_Etype (Original_Node (N), Id);
6341                Found := True;
6342
6343             else
6344                --  More than one type derived from Character in given scope.
6345                --  Collect all possible interpretations.
6346
6347                Add_One_Interp (N, Id, Id);
6348             end if;
6349          end if;
6350
6351          Next_Entity (Id);
6352       end loop;
6353
6354       return Found;
6355    end Has_Implicit_Character_Literal;
6356
6357    ----------------------
6358    -- Has_Private_With --
6359    ----------------------
6360
6361    function Has_Private_With (E : Entity_Id) return Boolean is
6362       Comp_Unit : constant Node_Id := Cunit (Current_Sem_Unit);
6363       Item      : Node_Id;
6364
6365    begin
6366       Item := First (Context_Items (Comp_Unit));
6367       while Present (Item) loop
6368          if Nkind (Item) = N_With_Clause
6369            and then Private_Present (Item)
6370            and then Entity (Name (Item)) = E
6371          then
6372             return True;
6373          end if;
6374
6375          Next (Item);
6376       end loop;
6377
6378       return False;
6379    end Has_Private_With;
6380
6381    ---------------------------
6382    -- Has_Implicit_Operator --
6383    ---------------------------
6384
6385    function Has_Implicit_Operator (N : Node_Id) return Boolean is
6386       Op_Id   : constant Name_Id   := Chars (Selector_Name (N));
6387       P       : constant Entity_Id := Entity (Prefix (N));
6388       Id      : Entity_Id;
6389       Priv_Id : Entity_Id := Empty;
6390
6391       procedure Add_Implicit_Operator
6392         (T       : Entity_Id;
6393          Op_Type : Entity_Id := Empty);
6394       --  Add implicit interpretation to node N, using the type for which a
6395       --  predefined operator exists. If the operator yields a boolean type,
6396       --  the Operand_Type is implicitly referenced by the operator, and a
6397       --  reference to it must be generated.
6398
6399       ---------------------------
6400       -- Add_Implicit_Operator --
6401       ---------------------------
6402
6403       procedure Add_Implicit_Operator
6404         (T       : Entity_Id;
6405          Op_Type : Entity_Id := Empty)
6406       is
6407          Predef_Op : Entity_Id;
6408
6409       begin
6410          Predef_Op := Current_Entity (Selector_Name (N));
6411
6412          while Present (Predef_Op)
6413            and then Scope (Predef_Op) /= Standard_Standard
6414          loop
6415             Predef_Op := Homonym (Predef_Op);
6416          end loop;
6417
6418          if Nkind (N) = N_Selected_Component then
6419             Change_Selected_Component_To_Expanded_Name (N);
6420          end if;
6421
6422          --  If the context is an unanalyzed function call, determine whether
6423          --  a binary or unary interpretation is required.
6424
6425          if Nkind (Parent (N)) = N_Indexed_Component then
6426             declare
6427                Is_Binary_Call : constant Boolean :=
6428                                   Present
6429                                     (Next (First (Expressions (Parent (N)))));
6430                Is_Binary_Op   : constant Boolean :=
6431                                   First_Entity
6432                                     (Predef_Op) /= Last_Entity (Predef_Op);
6433                Predef_Op2     : constant Entity_Id := Homonym (Predef_Op);
6434
6435             begin
6436                if Is_Binary_Call then
6437                   if Is_Binary_Op then
6438                      Add_One_Interp (N, Predef_Op, T);
6439                   else
6440                      Add_One_Interp (N, Predef_Op2, T);
6441                   end if;
6442
6443                else
6444                   if not Is_Binary_Op then
6445                      Add_One_Interp (N, Predef_Op, T);
6446                   else
6447                      Add_One_Interp (N, Predef_Op2, T);
6448                   end if;
6449                end if;
6450             end;
6451
6452          else
6453             Add_One_Interp (N, Predef_Op, T);
6454
6455             --  For operators with unary and binary interpretations, if
6456             --  context is not a call, add both
6457
6458             if Present (Homonym (Predef_Op)) then
6459                Add_One_Interp (N, Homonym (Predef_Op), T);
6460             end if;
6461          end if;
6462
6463          --  The node is a reference to a predefined operator, and
6464          --  an implicit reference to the type of its operands.
6465
6466          if Present (Op_Type) then
6467             Generate_Operator_Reference (N, Op_Type);
6468          else
6469             Generate_Operator_Reference (N, T);
6470          end if;
6471       end Add_Implicit_Operator;
6472
6473    --  Start of processing for Has_Implicit_Operator
6474
6475    begin
6476       if Ekind (P) = E_Package
6477         and then not In_Open_Scopes (P)
6478       then
6479          Priv_Id := First_Private_Entity (P);
6480       end if;
6481
6482       Id := First_Entity (P);
6483
6484       case Op_Id is
6485
6486          --  Boolean operators: an implicit declaration exists if the scope
6487          --  contains a declaration for a derived Boolean type, or for an
6488          --  array of Boolean type.
6489
6490          when Name_Op_And | Name_Op_Not | Name_Op_Or  | Name_Op_Xor =>
6491             while Id  /= Priv_Id loop
6492                if Valid_Boolean_Arg (Id) and then Is_Base_Type (Id) then
6493                   Add_Implicit_Operator (Id);
6494                   return True;
6495                end if;
6496
6497                Next_Entity (Id);
6498             end loop;
6499
6500          --  Equality: look for any non-limited type (result is Boolean)
6501
6502          when Name_Op_Eq | Name_Op_Ne =>
6503             while Id  /= Priv_Id loop
6504                if Is_Type (Id)
6505                  and then not Is_Limited_Type (Id)
6506                  and then Is_Base_Type (Id)
6507                then
6508                   Add_Implicit_Operator (Standard_Boolean, Id);
6509                   return True;
6510                end if;
6511
6512                Next_Entity (Id);
6513             end loop;
6514
6515          --  Comparison operators: scalar type, or array of scalar
6516
6517          when Name_Op_Lt | Name_Op_Le | Name_Op_Gt | Name_Op_Ge =>
6518             while Id  /= Priv_Id loop
6519                if (Is_Scalar_Type (Id)
6520                     or else (Is_Array_Type (Id)
6521                               and then Is_Scalar_Type (Component_Type (Id))))
6522                  and then Is_Base_Type (Id)
6523                then
6524                   Add_Implicit_Operator (Standard_Boolean, Id);
6525                   return True;
6526                end if;
6527
6528                Next_Entity (Id);
6529             end loop;
6530
6531          --  Arithmetic operators: any numeric type
6532
6533          when Name_Op_Abs      |
6534               Name_Op_Add      |
6535               Name_Op_Mod      |
6536               Name_Op_Rem      |
6537               Name_Op_Subtract |
6538               Name_Op_Multiply |
6539               Name_Op_Divide   |
6540               Name_Op_Expon    =>
6541             while Id  /= Priv_Id loop
6542                if Is_Numeric_Type (Id) and then Is_Base_Type (Id) then
6543                   Add_Implicit_Operator (Id);
6544                   return True;
6545                end if;
6546
6547                Next_Entity (Id);
6548             end loop;
6549
6550          --  Concatenation: any one-dimensional array type
6551
6552          when Name_Op_Concat =>
6553             while Id  /= Priv_Id loop
6554                if Is_Array_Type (Id)
6555                  and then Number_Dimensions (Id) = 1
6556                  and then Is_Base_Type (Id)
6557                then
6558                   Add_Implicit_Operator (Id);
6559                   return True;
6560                end if;
6561
6562                Next_Entity (Id);
6563             end loop;
6564
6565          --  What is the others condition here? Should we be using a
6566          --  subtype of Name_Id that would restrict to operators ???
6567
6568          when others => null;
6569       end case;
6570
6571       --  If we fall through, then we do not have an implicit operator
6572
6573       return False;
6574
6575    end Has_Implicit_Operator;
6576
6577    -----------------------------------
6578    -- Has_Loop_In_Inner_Open_Scopes --
6579    -----------------------------------
6580
6581    function Has_Loop_In_Inner_Open_Scopes (S : Entity_Id) return Boolean is
6582    begin
6583       --  Several scope stacks are maintained by Scope_Stack. The base of the
6584       --  currently active scope stack is denoted by the Is_Active_Stack_Base
6585       --  flag in the scope stack entry. Note that the scope stacks used to
6586       --  simply be delimited implicitly by the presence of Standard_Standard
6587       --  at their base, but there now are cases where this is not sufficient
6588       --  because Standard_Standard actually may appear in the middle of the
6589       --  active set of scopes.
6590
6591       for J in reverse 0 .. Scope_Stack.Last loop
6592
6593          --  S was reached without seing a loop scope first
6594
6595          if Scope_Stack.Table (J).Entity = S then
6596             return False;
6597
6598          --  S was not yet reached, so it contains at least one inner loop
6599
6600          elsif Ekind (Scope_Stack.Table (J).Entity) = E_Loop then
6601             return True;
6602          end if;
6603
6604          --  Check Is_Active_Stack_Base to tell us when to stop, as there are
6605          --  cases where Standard_Standard appears in the middle of the active
6606          --  set of scopes. This affects the declaration and overriding of
6607          --  private inherited operations in instantiations of generic child
6608          --  units.
6609
6610          pragma Assert (not Scope_Stack.Table (J).Is_Active_Stack_Base);
6611       end loop;
6612
6613       raise Program_Error;    --  unreachable
6614    end Has_Loop_In_Inner_Open_Scopes;
6615
6616    --------------------
6617    -- In_Open_Scopes --
6618    --------------------
6619
6620    function In_Open_Scopes (S : Entity_Id) return Boolean is
6621    begin
6622       --  Several scope stacks are maintained by Scope_Stack. The base of the
6623       --  currently active scope stack is denoted by the Is_Active_Stack_Base
6624       --  flag in the scope stack entry. Note that the scope stacks used to
6625       --  simply be delimited implicitly by the presence of Standard_Standard
6626       --  at their base, but there now are cases where this is not sufficient
6627       --  because Standard_Standard actually may appear in the middle of the
6628       --  active set of scopes.
6629
6630       for J in reverse 0 .. Scope_Stack.Last loop
6631          if Scope_Stack.Table (J).Entity = S then
6632             return True;
6633          end if;
6634
6635          --  Check Is_Active_Stack_Base to tell us when to stop, as there are
6636          --  cases where Standard_Standard appears in the middle of the active
6637          --  set of scopes. This affects the declaration and overriding of
6638          --  private inherited operations in instantiations of generic child
6639          --  units.
6640
6641          exit when Scope_Stack.Table (J).Is_Active_Stack_Base;
6642       end loop;
6643
6644       return False;
6645    end In_Open_Scopes;
6646
6647    -----------------------------
6648    -- Inherit_Renamed_Profile --
6649    -----------------------------
6650
6651    procedure Inherit_Renamed_Profile (New_S : Entity_Id; Old_S : Entity_Id) is
6652       New_F : Entity_Id;
6653       Old_F : Entity_Id;
6654       Old_T : Entity_Id;
6655       New_T : Entity_Id;
6656
6657    begin
6658       if Ekind (Old_S) = E_Operator then
6659          New_F := First_Formal (New_S);
6660
6661          while Present (New_F) loop
6662             Set_Etype (New_F, Base_Type (Etype (New_F)));
6663             Next_Formal (New_F);
6664          end loop;
6665
6666          Set_Etype (New_S, Base_Type (Etype (New_S)));
6667
6668       else
6669          New_F := First_Formal (New_S);
6670          Old_F := First_Formal (Old_S);
6671
6672          while Present (New_F) loop
6673             New_T := Etype (New_F);
6674             Old_T := Etype (Old_F);
6675
6676             --  If the new type is a renaming of the old one, as is the
6677             --  case for actuals in instances, retain its name, to simplify
6678             --  later disambiguation.
6679
6680             if Nkind (Parent (New_T)) = N_Subtype_Declaration
6681               and then Is_Entity_Name (Subtype_Indication (Parent (New_T)))
6682               and then Entity (Subtype_Indication (Parent (New_T))) = Old_T
6683             then
6684                null;
6685             else
6686                Set_Etype (New_F, Old_T);
6687             end if;
6688
6689             Next_Formal (New_F);
6690             Next_Formal (Old_F);
6691          end loop;
6692
6693          if Ekind_In (Old_S, E_Function, E_Enumeration_Literal) then
6694             Set_Etype (New_S, Etype (Old_S));
6695          end if;
6696       end if;
6697    end Inherit_Renamed_Profile;
6698
6699    ----------------
6700    -- Initialize --
6701    ----------------
6702
6703    procedure Initialize is
6704    begin
6705       Urefs.Init;
6706    end Initialize;
6707
6708    -------------------------
6709    -- Install_Use_Clauses --
6710    -------------------------
6711
6712    procedure Install_Use_Clauses
6713      (Clause             : Node_Id;
6714       Force_Installation : Boolean := False)
6715    is
6716       U  : Node_Id;
6717       P  : Node_Id;
6718       Id : Entity_Id;
6719
6720    begin
6721       U := Clause;
6722       while Present (U) loop
6723
6724          --  Case of USE package
6725
6726          if Nkind (U) = N_Use_Package_Clause then
6727             P := First (Names (U));
6728             while Present (P) loop
6729                Id := Entity (P);
6730
6731                if Ekind (Id) = E_Package then
6732                   if In_Use (Id) then
6733                      Note_Redundant_Use (P);
6734
6735                   elsif Present (Renamed_Object (Id))
6736                     and then In_Use (Renamed_Object (Id))
6737                   then
6738                      Note_Redundant_Use (P);
6739
6740                   elsif Force_Installation or else Applicable_Use (P) then
6741                      Use_One_Package (Id, U);
6742
6743                   end if;
6744                end if;
6745
6746                Next (P);
6747             end loop;
6748
6749          --  Case of USE TYPE
6750
6751          else
6752             P := First (Subtype_Marks (U));
6753             while Present (P) loop
6754                if not Is_Entity_Name (P)
6755                  or else No (Entity (P))
6756                then
6757                   null;
6758
6759                elsif Entity (P) /= Any_Type then
6760                   Use_One_Type (P);
6761                end if;
6762
6763                Next (P);
6764             end loop;
6765          end if;
6766
6767          Next_Use_Clause (U);
6768       end loop;
6769    end Install_Use_Clauses;
6770
6771    -------------------------------------
6772    -- Is_Appropriate_For_Entry_Prefix --
6773    -------------------------------------
6774
6775    function Is_Appropriate_For_Entry_Prefix (T : Entity_Id) return Boolean is
6776       P_Type : Entity_Id := T;
6777
6778    begin
6779       if Is_Access_Type (P_Type) then
6780          P_Type := Designated_Type (P_Type);
6781       end if;
6782
6783       return Is_Task_Type (P_Type) or else Is_Protected_Type (P_Type);
6784    end Is_Appropriate_For_Entry_Prefix;
6785
6786    -------------------------------
6787    -- Is_Appropriate_For_Record --
6788    -------------------------------
6789
6790    function Is_Appropriate_For_Record (T : Entity_Id) return Boolean is
6791
6792       function Has_Components (T1 : Entity_Id) return Boolean;
6793       --  Determine if given type has components (i.e. is either a record
6794       --  type or a type that has discriminants).
6795
6796       --------------------
6797       -- Has_Components --
6798       --------------------
6799
6800       function Has_Components (T1 : Entity_Id) return Boolean is
6801       begin
6802          return Is_Record_Type (T1)
6803            or else (Is_Private_Type (T1) and then Has_Discriminants (T1))
6804            or else (Is_Task_Type (T1) and then Has_Discriminants (T1))
6805            or else (Is_Incomplete_Type (T1)
6806                      and then From_With_Type (T1)
6807                      and then Present (Non_Limited_View (T1))
6808                      and then Is_Record_Type
6809                                 (Get_Full_View (Non_Limited_View (T1))));
6810       end Has_Components;
6811
6812    --  Start of processing for Is_Appropriate_For_Record
6813
6814    begin
6815       return
6816         Present (T)
6817           and then (Has_Components (T)
6818                      or else (Is_Access_Type (T)
6819                                and then Has_Components (Designated_Type (T))));
6820    end Is_Appropriate_For_Record;
6821
6822    ------------------------
6823    -- Note_Redundant_Use --
6824    ------------------------
6825
6826    procedure Note_Redundant_Use (Clause : Node_Id) is
6827       Pack_Name : constant Entity_Id := Entity (Clause);
6828       Cur_Use   : constant Node_Id   := Current_Use_Clause (Pack_Name);
6829       Decl      : constant Node_Id   := Parent (Clause);
6830
6831       Prev_Use   : Node_Id := Empty;
6832       Redundant  : Node_Id := Empty;
6833       --  The Use_Clause which is actually redundant. In the simplest case it
6834       --  is Pack itself, but when we compile a body we install its context
6835       --  before that of its spec, in which case it is the use_clause in the
6836       --  spec that will appear to be redundant, and we want the warning to be
6837       --  placed on the body. Similar complications appear when the redundancy
6838       --  is between a child unit and one of its ancestors.
6839
6840    begin
6841       Set_Redundant_Use (Clause, True);
6842
6843       if not Comes_From_Source (Clause)
6844         or else In_Instance
6845         or else not Warn_On_Redundant_Constructs
6846       then
6847          return;
6848       end if;
6849
6850       if not Is_Compilation_Unit (Current_Scope) then
6851
6852          --  If the use_clause is in an inner scope, it is made redundant by
6853          --  some clause in the current context, with one exception: If we're
6854          --  compiling a nested package body, and the use_clause comes from the
6855          --  corresponding spec, the clause is not necessarily fully redundant,
6856          --  so we should not warn. If a warning was warranted, it would have
6857          --  been given when the spec was processed.
6858
6859          if Nkind (Parent (Decl)) = N_Package_Specification then
6860             declare
6861                Package_Spec_Entity : constant Entity_Id :=
6862                                        Defining_Unit_Name (Parent (Decl));
6863             begin
6864                if In_Package_Body (Package_Spec_Entity) then
6865                   return;
6866                end if;
6867             end;
6868          end if;
6869
6870          Redundant := Clause;
6871          Prev_Use  := Cur_Use;
6872
6873       elsif Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Body then
6874          declare
6875             Cur_Unit : constant Unit_Number_Type := Get_Source_Unit (Cur_Use);
6876             New_Unit : constant Unit_Number_Type := Get_Source_Unit (Clause);
6877             Scop     : Entity_Id;
6878
6879          begin
6880             if Cur_Unit = New_Unit then
6881
6882                --  Redundant clause in same body
6883
6884                Redundant := Clause;
6885                Prev_Use  := Cur_Use;
6886
6887             elsif Cur_Unit = Current_Sem_Unit then
6888
6889                --  If the new clause is not in the current unit it has been
6890                --  analyzed first, and it makes the other one redundant.
6891                --  However, if the new clause appears in a subunit, Cur_Unit
6892                --  is still the parent, and in that case the redundant one
6893                --  is the one appearing in the subunit.
6894
6895                if Nkind (Unit (Cunit (New_Unit))) = N_Subunit then
6896                   Redundant := Clause;
6897                   Prev_Use  := Cur_Use;
6898
6899                --  Most common case: redundant clause in body,
6900                --  original clause in spec. Current scope is spec entity.
6901
6902                elsif
6903                  Current_Scope =
6904                    Defining_Entity (
6905                      Unit (Library_Unit (Cunit (Current_Sem_Unit))))
6906                then
6907                   Redundant := Cur_Use;
6908                   Prev_Use  := Clause;
6909
6910                else
6911                   --  The new clause may appear in an unrelated unit, when
6912                   --  the parents of a generic are being installed prior to
6913                   --  instantiation. In this case there must be no warning.
6914                   --  We detect this case by checking whether the current top
6915                   --  of the stack is related to the current compilation.
6916
6917                   Scop := Current_Scope;
6918                   while Present (Scop)
6919                     and then Scop /= Standard_Standard
6920                   loop
6921                      if Is_Compilation_Unit (Scop)
6922                        and then not Is_Child_Unit (Scop)
6923                      then
6924                         return;
6925
6926                      elsif Scop = Cunit_Entity (Current_Sem_Unit) then
6927                         exit;
6928                      end if;
6929
6930                      Scop := Scope (Scop);
6931                   end loop;
6932
6933                   Redundant := Cur_Use;
6934                   Prev_Use  := Clause;
6935                end if;
6936
6937             elsif New_Unit = Current_Sem_Unit then
6938                Redundant := Clause;
6939                Prev_Use  := Cur_Use;
6940
6941             else
6942                --  Neither is the current unit, so they appear in parent or
6943                --  sibling units. Warning will be emitted elsewhere.
6944
6945                return;
6946             end if;
6947          end;
6948
6949       elsif Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Declaration
6950         and then Present (Parent_Spec (Unit (Cunit (Current_Sem_Unit))))
6951       then
6952          --  Use_clause is in child unit of current unit, and the child unit
6953          --  appears in the context of the body of the parent, so it has been
6954          --  installed first, even though it is the redundant one. Depending on
6955          --  their placement in the context, the visible or the private parts
6956          --  of the two units, either might appear as redundant, but the
6957          --  message has to be on the current unit.
6958
6959          if Get_Source_Unit (Cur_Use) = Current_Sem_Unit then
6960             Redundant := Cur_Use;
6961             Prev_Use  := Clause;
6962          else
6963             Redundant := Clause;
6964             Prev_Use  := Cur_Use;
6965          end if;
6966
6967          --  If the new use clause appears in the private part of a parent unit
6968          --  it may appear to be redundant w.r.t. a use clause in a child unit,
6969          --  but the previous use clause was needed in the visible part of the
6970          --  child, and no warning should be emitted.
6971
6972          if Nkind (Parent (Decl)) = N_Package_Specification
6973            and then
6974              List_Containing (Decl) = Private_Declarations (Parent (Decl))
6975          then
6976             declare
6977                Par : constant Entity_Id := Defining_Entity (Parent (Decl));
6978                Spec : constant Node_Id  :=
6979                         Specification (Unit (Cunit (Current_Sem_Unit)));
6980
6981             begin
6982                if Is_Compilation_Unit (Par)
6983                  and then Par /= Cunit_Entity (Current_Sem_Unit)
6984                  and then Parent (Cur_Use) = Spec
6985                  and then
6986                    List_Containing (Cur_Use) = Visible_Declarations (Spec)
6987                then
6988                   return;
6989                end if;
6990             end;
6991          end if;
6992
6993       --  Finally, if the current use clause is in the context then
6994       --  the clause is redundant when it is nested within the unit.
6995
6996       elsif Nkind (Parent (Cur_Use)) = N_Compilation_Unit
6997         and then Nkind (Parent (Parent (Clause))) /= N_Compilation_Unit
6998         and then Get_Source_Unit (Cur_Use) = Get_Source_Unit (Clause)
6999       then
7000          Redundant := Clause;
7001          Prev_Use  := Cur_Use;
7002
7003       else
7004          null;
7005       end if;
7006
7007       if Present (Redundant) then
7008          Error_Msg_Sloc := Sloc (Prev_Use);
7009          Error_Msg_NE -- CODEFIX
7010            ("& is already use-visible through previous use clause #?",
7011             Redundant, Pack_Name);
7012       end if;
7013    end Note_Redundant_Use;
7014
7015    ---------------
7016    -- Pop_Scope --
7017    ---------------
7018
7019    procedure Pop_Scope is
7020       SST : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
7021       S   : constant Entity_Id := SST.Entity;
7022
7023    begin
7024       if Debug_Flag_E then
7025          Write_Info;
7026       end if;
7027
7028       --  Set Default_Storage_Pool field of the library unit if necessary
7029
7030       if Ekind_In (S, E_Package, E_Generic_Package)
7031         and then
7032           Nkind (Parent (Unit_Declaration_Node (S))) = N_Compilation_Unit
7033       then
7034          declare
7035             Aux : constant Node_Id :=
7036                     Aux_Decls_Node (Parent (Unit_Declaration_Node (S)));
7037          begin
7038             if No (Default_Storage_Pool (Aux)) then
7039                Set_Default_Storage_Pool (Aux, Default_Pool);
7040             end if;
7041          end;
7042       end if;
7043
7044       Scope_Suppress           := SST.Save_Scope_Suppress;
7045       Local_Suppress_Stack_Top := SST.Save_Local_Suppress_Stack_Top;
7046       Check_Policy_List        := SST.Save_Check_Policy_List;
7047       Default_Pool             := SST.Save_Default_Storage_Pool;
7048
7049       if Debug_Flag_W then
7050          Write_Str ("<-- exiting scope: ");
7051          Write_Name (Chars (Current_Scope));
7052          Write_Str (", Depth=");
7053          Write_Int (Int (Scope_Stack.Last));
7054          Write_Eol;
7055       end if;
7056
7057       End_Use_Clauses (SST.First_Use_Clause);
7058
7059       --  If the actions to be wrapped are still there they will get lost
7060       --  causing incomplete code to be generated. It is better to abort in
7061       --  this case (and we do the abort even with assertions off since the
7062       --  penalty is incorrect code generation)
7063
7064       if SST.Actions_To_Be_Wrapped_Before /= No_List
7065            or else
7066          SST.Actions_To_Be_Wrapped_After  /= No_List
7067       then
7068          raise Program_Error;
7069       end if;
7070
7071       --  Free last subprogram name if allocated, and pop scope
7072
7073       Free (SST.Last_Subprogram_Name);
7074       Scope_Stack.Decrement_Last;
7075    end Pop_Scope;
7076
7077    ---------------
7078    -- Push_Scope --
7079    ---------------
7080
7081    procedure Push_Scope (S : Entity_Id) is
7082       E : constant Entity_Id := Scope (S);
7083
7084    begin
7085       if Ekind (S) = E_Void then
7086          null;
7087
7088       --  Set scope depth if not a non-concurrent type, and we have not yet set
7089       --  the scope depth. This means that we have the first occurrence of the
7090       --  scope, and this is where the depth is set.
7091
7092       elsif (not Is_Type (S) or else Is_Concurrent_Type (S))
7093         and then not Scope_Depth_Set (S)
7094       then
7095          if S = Standard_Standard then
7096             Set_Scope_Depth_Value (S, Uint_0);
7097
7098          elsif Is_Child_Unit (S) then
7099             Set_Scope_Depth_Value (S, Uint_1);
7100
7101          elsif not Is_Record_Type (Current_Scope) then
7102             if Ekind (S) = E_Loop then
7103                Set_Scope_Depth_Value (S, Scope_Depth (Current_Scope));
7104             else
7105                Set_Scope_Depth_Value (S, Scope_Depth (Current_Scope) + 1);
7106             end if;
7107          end if;
7108       end if;
7109
7110       Scope_Stack.Increment_Last;
7111
7112       declare
7113          SST : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
7114
7115       begin
7116          SST.Entity                        := S;
7117          SST.Save_Scope_Suppress           := Scope_Suppress;
7118          SST.Save_Local_Suppress_Stack_Top := Local_Suppress_Stack_Top;
7119          SST.Save_Check_Policy_List        := Check_Policy_List;
7120          SST.Save_Default_Storage_Pool     := Default_Pool;
7121
7122          if Scope_Stack.Last > Scope_Stack.First then
7123             SST.Component_Alignment_Default := Scope_Stack.Table
7124                                                  (Scope_Stack.Last - 1).
7125                                                    Component_Alignment_Default;
7126          end if;
7127
7128          SST.Last_Subprogram_Name           := null;
7129          SST.Is_Transient                   := False;
7130          SST.Node_To_Be_Wrapped             := Empty;
7131          SST.Pending_Freeze_Actions         := No_List;
7132          SST.Actions_To_Be_Wrapped_Before   := No_List;
7133          SST.Actions_To_Be_Wrapped_After    := No_List;
7134          SST.First_Use_Clause               := Empty;
7135          SST.Is_Active_Stack_Base           := False;
7136          SST.Previous_Visibility            := False;
7137       end;
7138
7139       if Debug_Flag_W then
7140          Write_Str ("--> new scope: ");
7141          Write_Name (Chars (Current_Scope));
7142          Write_Str (", Id=");
7143          Write_Int (Int (Current_Scope));
7144          Write_Str (", Depth=");
7145          Write_Int (Int (Scope_Stack.Last));
7146          Write_Eol;
7147       end if;
7148
7149       --  Deal with copying flags from the previous scope to this one. This is
7150       --  not necessary if either scope is standard, or if the new scope is a
7151       --  child unit.
7152
7153       if S /= Standard_Standard
7154         and then Scope (S) /= Standard_Standard
7155         and then not Is_Child_Unit (S)
7156       then
7157          if Nkind (E) not in N_Entity then
7158             return;
7159          end if;
7160
7161          --  Copy categorization flags from Scope (S) to S, this is not done
7162          --  when Scope (S) is Standard_Standard since propagation is from
7163          --  library unit entity inwards. Copy other relevant attributes as
7164          --  well (Discard_Names in particular).
7165
7166          --  We only propagate inwards for library level entities,
7167          --  inner level subprograms do not inherit the categorization.
7168
7169          if Is_Library_Level_Entity (S) then
7170             Set_Is_Preelaborated  (S, Is_Preelaborated (E));
7171             Set_Is_Shared_Passive (S, Is_Shared_Passive (E));
7172             Set_Discard_Names     (S, Discard_Names (E));
7173             Set_Suppress_Value_Tracking_On_Call
7174                                   (S, Suppress_Value_Tracking_On_Call (E));
7175             Set_Categorization_From_Scope (E => S, Scop => E);
7176          end if;
7177       end if;
7178
7179       if Is_Child_Unit (S)
7180         and then Present (E)
7181         and then Ekind_In (E, E_Package, E_Generic_Package)
7182         and then
7183           Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
7184       then
7185          declare
7186             Aux : constant Node_Id :=
7187                     Aux_Decls_Node (Parent (Unit_Declaration_Node (E)));
7188          begin
7189             if Present (Default_Storage_Pool (Aux)) then
7190                Default_Pool := Default_Storage_Pool (Aux);
7191             end if;
7192          end;
7193       end if;
7194    end Push_Scope;
7195
7196    ---------------------
7197    -- Premature_Usage --
7198    ---------------------
7199
7200    procedure Premature_Usage (N : Node_Id) is
7201       Kind : constant Node_Kind := Nkind (Parent (Entity (N)));
7202       E    : Entity_Id := Entity (N);
7203
7204    begin
7205       --  Within an instance, the analysis of the actual for a formal object
7206       --  does not see the name of the object itself. This is significant only
7207       --  if the object is an aggregate, where its analysis does not do any
7208       --  name resolution on component associations. (see 4717-008). In such a
7209       --  case, look for the visible homonym on the chain.
7210
7211       if In_Instance
7212         and then Present (Homonym (E))
7213       then
7214          E := Homonym (E);
7215
7216          while Present (E)
7217            and then not In_Open_Scopes (Scope (E))
7218          loop
7219             E := Homonym (E);
7220          end loop;
7221
7222          if Present (E) then
7223             Set_Entity (N, E);
7224             Set_Etype (N, Etype (E));
7225             return;
7226          end if;
7227       end if;
7228
7229       if Kind  = N_Component_Declaration then
7230          Error_Msg_N
7231            ("component&! cannot be used before end of record declaration", N);
7232
7233       elsif Kind  = N_Parameter_Specification then
7234          Error_Msg_N
7235            ("formal parameter&! cannot be used before end of specification",
7236             N);
7237
7238       elsif Kind  = N_Discriminant_Specification then
7239          Error_Msg_N
7240            ("discriminant&! cannot be used before end of discriminant part",
7241             N);
7242
7243       elsif Kind  = N_Procedure_Specification
7244         or else Kind = N_Function_Specification
7245       then
7246          Error_Msg_N
7247            ("subprogram&! cannot be used before end of its declaration",
7248             N);
7249
7250       elsif Kind = N_Full_Type_Declaration then
7251          Error_Msg_N
7252            ("type& cannot be used before end of its declaration!", N);
7253
7254       else
7255          Error_Msg_N
7256            ("object& cannot be used before end of its declaration!", N);
7257       end if;
7258    end Premature_Usage;
7259
7260    ------------------------
7261    -- Present_System_Aux --
7262    ------------------------
7263
7264    function Present_System_Aux (N : Node_Id := Empty) return Boolean is
7265       Loc      : Source_Ptr;
7266       Aux_Name : Unit_Name_Type;
7267       Unum     : Unit_Number_Type;
7268       Withn    : Node_Id;
7269       With_Sys : Node_Id;
7270       The_Unit : Node_Id;
7271
7272       function Find_System (C_Unit : Node_Id) return Entity_Id;
7273       --  Scan context clause of compilation unit to find with_clause
7274       --  for System.
7275
7276       -----------------
7277       -- Find_System --
7278       -----------------
7279
7280       function Find_System (C_Unit : Node_Id) return Entity_Id is
7281          With_Clause : Node_Id;
7282
7283       begin
7284          With_Clause := First (Context_Items (C_Unit));
7285          while Present (With_Clause) loop
7286             if (Nkind (With_Clause) = N_With_Clause
7287               and then Chars (Name (With_Clause)) = Name_System)
7288               and then Comes_From_Source (With_Clause)
7289             then
7290                return With_Clause;
7291             end if;
7292
7293             Next (With_Clause);
7294          end loop;
7295
7296          return Empty;
7297       end Find_System;
7298
7299    --  Start of processing for Present_System_Aux
7300
7301    begin
7302       --  The child unit may have been loaded and analyzed already
7303
7304       if Present (System_Aux_Id) then
7305          return True;
7306
7307       --  If no previous pragma for System.Aux, nothing to load
7308
7309       elsif No (System_Extend_Unit) then
7310          return False;
7311
7312       --  Use the unit name given in the pragma to retrieve the unit.
7313       --  Verify that System itself appears in the context clause of the
7314       --  current compilation. If System is not present, an error will
7315       --  have been reported already.
7316
7317       else
7318          With_Sys := Find_System (Cunit (Current_Sem_Unit));
7319
7320          The_Unit := Unit (Cunit (Current_Sem_Unit));
7321
7322          if No (With_Sys)
7323            and then
7324              (Nkind (The_Unit) = N_Package_Body
7325                 or else (Nkind (The_Unit) = N_Subprogram_Body
7326                            and then
7327                              not Acts_As_Spec (Cunit (Current_Sem_Unit))))
7328          then
7329             With_Sys := Find_System (Library_Unit (Cunit (Current_Sem_Unit)));
7330          end if;
7331
7332          if No (With_Sys)
7333            and then Present (N)
7334          then
7335             --  If we are compiling a subunit, we need to examine its
7336             --  context as well (Current_Sem_Unit is the parent unit);
7337
7338             The_Unit := Parent (N);
7339             while Nkind (The_Unit) /= N_Compilation_Unit loop
7340                The_Unit := Parent (The_Unit);
7341             end loop;
7342
7343             if Nkind (Unit (The_Unit)) = N_Subunit then
7344                With_Sys := Find_System (The_Unit);
7345             end if;
7346          end if;
7347
7348          if No (With_Sys) then
7349             return False;
7350          end if;
7351
7352          Loc := Sloc (With_Sys);
7353          Get_Name_String (Chars (Expression (System_Extend_Unit)));
7354          Name_Buffer (8 .. Name_Len + 7) := Name_Buffer (1 .. Name_Len);
7355          Name_Buffer (1 .. 7) := "system.";
7356          Name_Buffer (Name_Len + 8) := '%';
7357          Name_Buffer (Name_Len + 9) := 's';
7358          Name_Len := Name_Len + 9;
7359          Aux_Name := Name_Find;
7360
7361          Unum :=
7362            Load_Unit
7363              (Load_Name  => Aux_Name,
7364               Required   => False,
7365               Subunit    => False,
7366               Error_Node => With_Sys);
7367
7368          if Unum /= No_Unit then
7369             Semantics (Cunit (Unum));
7370             System_Aux_Id :=
7371               Defining_Entity (Specification (Unit (Cunit (Unum))));
7372
7373             Withn :=
7374               Make_With_Clause (Loc,
7375                 Name =>
7376                   Make_Expanded_Name (Loc,
7377                     Chars  => Chars (System_Aux_Id),
7378                     Prefix => New_Reference_To (Scope (System_Aux_Id), Loc),
7379                     Selector_Name => New_Reference_To (System_Aux_Id, Loc)));
7380
7381             Set_Entity (Name (Withn), System_Aux_Id);
7382
7383             Set_Library_Unit       (Withn, Cunit (Unum));
7384             Set_Corresponding_Spec (Withn, System_Aux_Id);
7385             Set_First_Name         (Withn, True);
7386             Set_Implicit_With      (Withn, True);
7387
7388             Insert_After (With_Sys, Withn);
7389             Mark_Rewrite_Insertion (Withn);
7390             Set_Context_Installed (Withn);
7391
7392             return True;
7393
7394          --  Here if unit load failed
7395
7396          else
7397             Error_Msg_Name_1 := Name_System;
7398             Error_Msg_Name_2 := Chars (Expression (System_Extend_Unit));
7399             Error_Msg_N
7400               ("extension package `%.%` does not exist",
7401                Opt.System_Extend_Unit);
7402             return False;
7403          end if;
7404       end if;
7405    end Present_System_Aux;
7406
7407    -------------------------
7408    -- Restore_Scope_Stack --
7409    -------------------------
7410
7411    procedure Restore_Scope_Stack (Handle_Use : Boolean := True) is
7412       E         : Entity_Id;
7413       S         : Entity_Id;
7414       Comp_Unit : Node_Id;
7415       In_Child  : Boolean := False;
7416       Full_Vis  : Boolean := True;
7417       SS_Last   : constant Int := Scope_Stack.Last;
7418
7419    begin
7420       --  Restore visibility of previous scope stack, if any
7421
7422       for J in reverse 0 .. Scope_Stack.Last loop
7423          exit when  Scope_Stack.Table (J).Entity = Standard_Standard
7424             or else No (Scope_Stack.Table (J).Entity);
7425
7426          S := Scope_Stack.Table (J).Entity;
7427
7428          if not Is_Hidden_Open_Scope (S) then
7429
7430             --  If the parent scope is hidden, its entities are hidden as
7431             --  well, unless the entity is the instantiation currently
7432             --  being analyzed.
7433
7434             if not Is_Hidden_Open_Scope (Scope (S))
7435               or else not Analyzed (Parent (S))
7436               or else Scope (S) = Standard_Standard
7437             then
7438                Set_Is_Immediately_Visible (S, True);
7439             end if;
7440
7441             E := First_Entity (S);
7442             while Present (E) loop
7443                if Is_Child_Unit (E) then
7444                   if not From_With_Type (E) then
7445                      Set_Is_Immediately_Visible (E,
7446                        Is_Visible_Child_Unit (E) or else In_Open_Scopes (E));
7447
7448                   else
7449                      pragma Assert
7450                        (Nkind (Parent (E)) = N_Defining_Program_Unit_Name
7451                           and then
7452                         Nkind (Parent (Parent (E))) = N_Package_Specification);
7453                      Set_Is_Immediately_Visible (E,
7454                        Limited_View_Installed (Parent (Parent (E))));
7455                   end if;
7456                else
7457                   Set_Is_Immediately_Visible (E, True);
7458                end if;
7459
7460                Next_Entity (E);
7461
7462                if not Full_Vis
7463                  and then Is_Package_Or_Generic_Package (S)
7464                then
7465                   --  We are in the visible part of the package scope
7466
7467                   exit when E = First_Private_Entity (S);
7468                end if;
7469             end loop;
7470
7471             --  The visibility of child units (siblings of current compilation)
7472             --  must be restored in any case. Their declarations may appear
7473             --  after the private part of the parent.
7474
7475             if not Full_Vis then
7476                while Present (E) loop
7477                   if Is_Child_Unit (E) then
7478                      Set_Is_Immediately_Visible (E,
7479                        Is_Visible_Child_Unit (E) or else In_Open_Scopes (E));
7480                   end if;
7481
7482                   Next_Entity (E);
7483                end loop;
7484             end if;
7485          end if;
7486
7487          if Is_Child_Unit (S)
7488             and not In_Child     --  check only for current unit
7489          then
7490             In_Child := True;
7491
7492             --  Restore visibility of parents according to whether the child
7493             --  is private and whether we are in its visible part.
7494
7495             Comp_Unit := Parent (Unit_Declaration_Node (S));
7496
7497             if Nkind (Comp_Unit) = N_Compilation_Unit
7498               and then Private_Present (Comp_Unit)
7499             then
7500                Full_Vis := True;
7501
7502             elsif Is_Package_Or_Generic_Package (S)
7503               and then (In_Private_Part (S) or else In_Package_Body (S))
7504             then
7505                Full_Vis := True;
7506
7507             --  if S is the scope of some instance (which has already been
7508             --  seen on the stack) it does not affect the visibility of
7509             --  other scopes.
7510
7511             elsif Is_Hidden_Open_Scope (S) then
7512                null;
7513
7514             elsif (Ekind (S) = E_Procedure
7515                     or else Ekind (S) = E_Function)
7516               and then Has_Completion (S)
7517             then
7518                Full_Vis := True;
7519             else
7520                Full_Vis := False;
7521             end if;
7522          else
7523             Full_Vis := True;
7524          end if;
7525       end loop;
7526
7527       if SS_Last >= Scope_Stack.First
7528         and then Scope_Stack.Table (SS_Last).Entity /= Standard_Standard
7529         and then Handle_Use
7530       then
7531          Install_Use_Clauses (Scope_Stack.Table (SS_Last).First_Use_Clause);
7532       end if;
7533    end Restore_Scope_Stack;
7534
7535    ----------------------
7536    -- Save_Scope_Stack --
7537    ----------------------
7538
7539    procedure Save_Scope_Stack (Handle_Use : Boolean := True) is
7540       E       : Entity_Id;
7541       S       : Entity_Id;
7542       SS_Last : constant Int := Scope_Stack.Last;
7543
7544    begin
7545       if SS_Last >= Scope_Stack.First
7546         and then Scope_Stack.Table (SS_Last).Entity /= Standard_Standard
7547       then
7548          if Handle_Use then
7549             End_Use_Clauses (Scope_Stack.Table (SS_Last).First_Use_Clause);
7550          end if;
7551
7552          --  If the call is from within a compilation unit, as when called from
7553          --  Rtsfind, make current entries in scope stack invisible while we
7554          --  analyze the new unit.
7555
7556          for J in reverse 0 .. SS_Last loop
7557             exit when  Scope_Stack.Table (J).Entity = Standard_Standard
7558                or else No (Scope_Stack.Table (J).Entity);
7559
7560             S := Scope_Stack.Table (J).Entity;
7561             Set_Is_Immediately_Visible (S, False);
7562
7563             E := First_Entity (S);
7564             while Present (E) loop
7565                Set_Is_Immediately_Visible (E, False);
7566                Next_Entity (E);
7567             end loop;
7568          end loop;
7569
7570       end if;
7571    end Save_Scope_Stack;
7572
7573    -------------
7574    -- Set_Use --
7575    -------------
7576
7577    procedure Set_Use (L : List_Id) is
7578       Decl      : Node_Id;
7579       Pack_Name : Node_Id;
7580       Pack      : Entity_Id;
7581       Id        : Entity_Id;
7582
7583    begin
7584       if Present (L) then
7585          Decl := First (L);
7586          while Present (Decl) loop
7587             if Nkind (Decl) = N_Use_Package_Clause then
7588                Chain_Use_Clause (Decl);
7589
7590                Pack_Name := First (Names (Decl));
7591                while Present (Pack_Name) loop
7592                   Pack := Entity (Pack_Name);
7593
7594                   if Ekind (Pack) = E_Package
7595                     and then Applicable_Use (Pack_Name)
7596                   then
7597                      Use_One_Package (Pack, Decl);
7598                   end if;
7599
7600                   Next (Pack_Name);
7601                end loop;
7602
7603             elsif Nkind (Decl) = N_Use_Type_Clause  then
7604                Chain_Use_Clause (Decl);
7605
7606                Id := First (Subtype_Marks (Decl));
7607                while Present (Id) loop
7608                   if Entity (Id) /= Any_Type then
7609                      Use_One_Type (Id);
7610                   end if;
7611
7612                   Next (Id);
7613                end loop;
7614             end if;
7615
7616             Next (Decl);
7617          end loop;
7618       end if;
7619    end Set_Use;
7620
7621    ---------------------
7622    -- Use_One_Package --
7623    ---------------------
7624
7625    procedure Use_One_Package (P : Entity_Id; N : Node_Id) is
7626       Id               : Entity_Id;
7627       Prev             : Entity_Id;
7628       Current_Instance : Entity_Id := Empty;
7629       Real_P           : Entity_Id;
7630       Private_With_OK  : Boolean   := False;
7631
7632    begin
7633       if Ekind (P) /= E_Package then
7634          return;
7635       end if;
7636
7637       Set_In_Use (P);
7638       Set_Current_Use_Clause (P, N);
7639
7640       --  Ada 2005 (AI-50217): Check restriction
7641
7642       if From_With_Type (P) then
7643          Error_Msg_N ("limited withed package cannot appear in use clause", N);
7644       end if;
7645
7646       --  Find enclosing instance, if any
7647
7648       if In_Instance then
7649          Current_Instance := Current_Scope;
7650          while not Is_Generic_Instance (Current_Instance) loop
7651             Current_Instance := Scope (Current_Instance);
7652          end loop;
7653
7654          if No (Hidden_By_Use_Clause (N)) then
7655             Set_Hidden_By_Use_Clause (N, New_Elmt_List);
7656          end if;
7657       end if;
7658
7659       --  If unit is a package renaming, indicate that the renamed
7660       --  package is also in use (the flags on both entities must
7661       --  remain consistent, and a subsequent use of either of them
7662       --  should be recognized as redundant).
7663
7664       if Present (Renamed_Object (P)) then
7665          Set_In_Use (Renamed_Object (P));
7666          Set_Current_Use_Clause (Renamed_Object (P), N);
7667          Real_P := Renamed_Object (P);
7668       else
7669          Real_P := P;
7670       end if;
7671
7672       --  Ada 2005 (AI-262): Check the use_clause of a private withed package
7673       --  found in the private part of a package specification
7674
7675       if In_Private_Part (Current_Scope)
7676         and then Has_Private_With (P)
7677         and then Is_Child_Unit (Current_Scope)
7678         and then Is_Child_Unit (P)
7679         and then Is_Ancestor_Package (Scope (Current_Scope), P)
7680       then
7681          Private_With_OK := True;
7682       end if;
7683
7684       --  Loop through entities in one package making them potentially
7685       --  use-visible.
7686
7687       Id := First_Entity (P);
7688       while Present (Id)
7689         and then (Id /= First_Private_Entity (P)
7690                     or else Private_With_OK) -- Ada 2005 (AI-262)
7691       loop
7692          Prev := Current_Entity (Id);
7693          while Present (Prev) loop
7694             if Is_Immediately_Visible (Prev)
7695               and then (not Is_Overloadable (Prev)
7696                          or else not Is_Overloadable (Id)
7697                          or else (Type_Conformant (Id, Prev)))
7698             then
7699                if No (Current_Instance) then
7700
7701                   --  Potentially use-visible entity remains hidden
7702
7703                   goto Next_Usable_Entity;
7704
7705                --  A use clause within an instance hides outer global entities,
7706                --  which are not used to resolve local entities in the
7707                --  instance. Note that the predefined entities in Standard
7708                --  could not have been hidden in the generic by a use clause,
7709                --  and therefore remain visible. Other compilation units whose
7710                --  entities appear in Standard must be hidden in an instance.
7711
7712                --  To determine whether an entity is external to the instance
7713                --  we compare the scope depth of its scope with that of the
7714                --  current instance. However, a generic actual of a subprogram
7715                --  instance is declared in the wrapper package but will not be
7716                --  hidden by a use-visible entity. similarly, an entity that is
7717                --  declared in an enclosing instance will not be hidden by an
7718                --  an entity declared in a generic actual, which can only have
7719                --  been use-visible in the generic and will not have hidden the
7720                --  entity in the generic parent.
7721
7722                --  If Id is called Standard, the predefined package with the
7723                --  same name is in the homonym chain. It has to be ignored
7724                --  because it has no defined scope (being the only entity in
7725                --  the system with this mandated behavior).
7726
7727                elsif not Is_Hidden (Id)
7728                  and then Present (Scope (Prev))
7729                  and then not Is_Wrapper_Package (Scope (Prev))
7730                  and then Scope_Depth (Scope (Prev)) <
7731                           Scope_Depth (Current_Instance)
7732                  and then (Scope (Prev) /= Standard_Standard
7733                             or else Sloc (Prev) > Standard_Location)
7734                then
7735                   if In_Open_Scopes (Scope (Prev))
7736                     and then Is_Generic_Instance (Scope (Prev))
7737                     and then Present (Associated_Formal_Package (P))
7738                   then
7739                      null;
7740
7741                   else
7742                      Set_Is_Potentially_Use_Visible (Id);
7743                      Set_Is_Immediately_Visible (Prev, False);
7744                      Append_Elmt (Prev, Hidden_By_Use_Clause (N));
7745                   end if;
7746                end if;
7747
7748             --  A user-defined operator is not use-visible if the predefined
7749             --  operator for the type is immediately visible, which is the case
7750             --  if the type of the operand is in an open scope. This does not
7751             --  apply to user-defined operators that have operands of different
7752             --  types, because the predefined mixed mode operations (multiply
7753             --  and divide) apply to universal types and do not hide anything.
7754
7755             elsif Ekind (Prev) = E_Operator
7756               and then Operator_Matches_Spec (Prev, Id)
7757               and then In_Open_Scopes
7758                (Scope (Base_Type (Etype (First_Formal (Id)))))
7759               and then (No (Next_Formal (First_Formal (Id)))
7760                          or else Etype (First_Formal (Id))
7761                            = Etype (Next_Formal (First_Formal (Id)))
7762                          or else Chars (Prev) = Name_Op_Expon)
7763             then
7764                goto Next_Usable_Entity;
7765
7766             --  In an instance, two homonyms may become use_visible through the
7767             --  actuals of distinct formal packages. In the generic, only the
7768             --  current one would have been visible, so make the other one
7769             --  not use_visible.
7770
7771             elsif Present (Current_Instance)
7772               and then Is_Potentially_Use_Visible (Prev)
7773               and then not Is_Overloadable (Prev)
7774               and then Scope (Id) /= Scope (Prev)
7775               and then Used_As_Generic_Actual (Scope (Prev))
7776               and then Used_As_Generic_Actual (Scope (Id))
7777               and then not In_Same_List (Current_Use_Clause (Scope (Prev)),
7778                                          Current_Use_Clause (Scope (Id)))
7779             then
7780                Set_Is_Potentially_Use_Visible (Prev, False);
7781                Append_Elmt (Prev, Hidden_By_Use_Clause (N));
7782             end if;
7783
7784             Prev := Homonym (Prev);
7785          end loop;
7786
7787          --  On exit, we know entity is not hidden, unless it is private
7788
7789          if not Is_Hidden (Id)
7790            and then ((not Is_Child_Unit (Id))
7791                        or else Is_Visible_Child_Unit (Id))
7792          then
7793             Set_Is_Potentially_Use_Visible (Id);
7794
7795             if Is_Private_Type (Id)
7796               and then Present (Full_View (Id))
7797             then
7798                Set_Is_Potentially_Use_Visible (Full_View (Id));
7799             end if;
7800          end if;
7801
7802          <<Next_Usable_Entity>>
7803             Next_Entity (Id);
7804       end loop;
7805
7806       --  Child units are also made use-visible by a use clause, but they may
7807       --  appear after all visible declarations in the parent entity list.
7808
7809       while Present (Id) loop
7810          if Is_Child_Unit (Id)
7811            and then Is_Visible_Child_Unit (Id)
7812          then
7813             Set_Is_Potentially_Use_Visible (Id);
7814          end if;
7815
7816          Next_Entity (Id);
7817       end loop;
7818
7819       if Chars (Real_P) = Name_System
7820         and then Scope (Real_P) = Standard_Standard
7821         and then Present_System_Aux (N)
7822       then
7823          Use_One_Package (System_Aux_Id, N);
7824       end if;
7825
7826    end Use_One_Package;
7827
7828    ------------------
7829    -- Use_One_Type --
7830    ------------------
7831
7832    procedure Use_One_Type (Id : Node_Id; Installed : Boolean := False) is
7833       Elmt          : Elmt_Id;
7834       Is_Known_Used : Boolean;
7835       Op_List       : Elist_Id;
7836       T             : Entity_Id;
7837
7838       function Spec_Reloaded_For_Body return Boolean;
7839       --  Determine whether the compilation unit is a package body and the use
7840       --  type clause is in the spec of the same package. Even though the spec
7841       --  was analyzed first, its context is reloaded when analysing the body.
7842
7843       procedure Use_Class_Wide_Operations (Typ : Entity_Id);
7844       --  AI05-150: if the use_type_clause carries the "all" qualifier,
7845       --  class-wide operations of ancestor types are use-visible if the
7846       --  ancestor type is visible.
7847
7848       ----------------------------
7849       -- Spec_Reloaded_For_Body --
7850       ----------------------------
7851
7852       function Spec_Reloaded_For_Body return Boolean is
7853       begin
7854          if Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Body then
7855             declare
7856                Spec : constant Node_Id :=
7857                         Parent (List_Containing (Parent (Id)));
7858             begin
7859                return
7860                  Nkind (Spec) = N_Package_Specification
7861                    and then Corresponding_Body (Parent (Spec)) =
7862                               Cunit_Entity (Current_Sem_Unit);
7863             end;
7864          end if;
7865
7866          return False;
7867       end Spec_Reloaded_For_Body;
7868
7869       -------------------------------
7870       -- Use_Class_Wide_Operations --
7871       -------------------------------
7872
7873       procedure Use_Class_Wide_Operations (Typ : Entity_Id) is
7874          Scop : Entity_Id;
7875          Ent  : Entity_Id;
7876
7877          function Is_Class_Wide_Operation_Of
7878         (Op  : Entity_Id;
7879          T   : Entity_Id) return Boolean;
7880          --  Determine whether a subprogram has a class-wide parameter or
7881          --  result that is T'Class.
7882
7883          ---------------------------------
7884          --  Is_Class_Wide_Operation_Of --
7885          ---------------------------------
7886
7887          function Is_Class_Wide_Operation_Of
7888            (Op  : Entity_Id;
7889             T   : Entity_Id) return Boolean
7890          is
7891             Formal : Entity_Id;
7892
7893          begin
7894             Formal := First_Formal (Op);
7895             while Present (Formal) loop
7896                if Etype (Formal) = Class_Wide_Type (T) then
7897                   return True;
7898                end if;
7899                Next_Formal (Formal);
7900             end loop;
7901
7902             if Etype (Op) = Class_Wide_Type (T) then
7903                return True;
7904             end if;
7905
7906             return False;
7907          end Is_Class_Wide_Operation_Of;
7908
7909       --  Start of processing for Use_Class_Wide_Operations
7910
7911       begin
7912          Scop := Scope (Typ);
7913          if not Is_Hidden (Scop) then
7914             Ent := First_Entity (Scop);
7915             while Present (Ent) loop
7916                if Is_Overloadable (Ent)
7917                  and then Is_Class_Wide_Operation_Of (Ent, Typ)
7918                  and then not Is_Potentially_Use_Visible (Ent)
7919                then
7920                   Set_Is_Potentially_Use_Visible (Ent);
7921                   Append_Elmt (Ent, Used_Operations (Parent (Id)));
7922                end if;
7923
7924                Next_Entity (Ent);
7925             end loop;
7926          end if;
7927
7928          if Is_Derived_Type (Typ) then
7929             Use_Class_Wide_Operations (Etype (Base_Type (Typ)));
7930          end if;
7931       end Use_Class_Wide_Operations;
7932
7933    --  Start of processing for Use_One_Type;
7934
7935    begin
7936       --  It is the type determined by the subtype mark (8.4(8)) whose
7937       --  operations become potentially use-visible.
7938
7939       T := Base_Type (Entity (Id));
7940
7941       --  Either the type itself is used, the package where it is declared
7942       --  is in use or the entity is declared in the current package, thus
7943       --  use-visible.
7944
7945       Is_Known_Used :=
7946         In_Use (T)
7947           or else In_Use (Scope (T))
7948           or else Scope (T) = Current_Scope;
7949
7950       Set_Redundant_Use (Id,
7951         Is_Known_Used or else Is_Potentially_Use_Visible (T));
7952
7953       if Ekind (T) = E_Incomplete_Type then
7954          Error_Msg_N ("premature usage of incomplete type", Id);
7955
7956       elsif In_Open_Scopes (Scope (T)) then
7957          null;
7958
7959       --  A limited view cannot appear in a use_type clause. However, an access
7960       --  type whose designated type is limited has the flag but is not itself
7961       --  a limited view unless we only have a limited view of its enclosing
7962       --  package.
7963
7964       elsif From_With_Type (T)
7965         and then From_With_Type (Scope (T))
7966       then
7967          Error_Msg_N
7968            ("incomplete type from limited view "
7969              & "cannot appear in use clause", Id);
7970
7971       --  If the subtype mark designates a subtype in a different package,
7972       --  we have to check that the parent type is visible, otherwise the
7973       --  use type clause is a noop. Not clear how to do that???
7974
7975       elsif not Redundant_Use (Id) then
7976          Set_In_Use (T);
7977
7978          --  If T is tagged, primitive operators on class-wide operands
7979          --  are also available.
7980
7981          if Is_Tagged_Type (T) then
7982             Set_In_Use (Class_Wide_Type (T));
7983          end if;
7984
7985          Set_Current_Use_Clause (T, Parent (Id));
7986
7987          --  Iterate over primitive operations of the type. If an operation is
7988          --  already use_visible, it is the result of a previous use_clause,
7989          --  and already appears on the corresponding entity chain. If the
7990          --  clause is being reinstalled, operations are already use-visible.
7991
7992          if Installed then
7993             null;
7994
7995          else
7996             Op_List := Collect_Primitive_Operations (T);
7997             Elmt := First_Elmt (Op_List);
7998             while Present (Elmt) loop
7999                if (Nkind (Node (Elmt)) = N_Defining_Operator_Symbol
8000                     or else Chars (Node (Elmt)) in Any_Operator_Name)
8001                  and then not Is_Hidden (Node (Elmt))
8002                  and then not Is_Potentially_Use_Visible (Node (Elmt))
8003                then
8004                   Set_Is_Potentially_Use_Visible (Node (Elmt));
8005                   Append_Elmt (Node (Elmt), Used_Operations (Parent (Id)));
8006
8007                elsif Ada_Version >= Ada_2012
8008                  and then All_Present (Parent (Id))
8009                  and then not Is_Hidden (Node (Elmt))
8010                  and then not Is_Potentially_Use_Visible (Node (Elmt))
8011                then
8012                   Set_Is_Potentially_Use_Visible (Node (Elmt));
8013                   Append_Elmt (Node (Elmt), Used_Operations (Parent (Id)));
8014                end if;
8015
8016                Next_Elmt (Elmt);
8017             end loop;
8018          end if;
8019
8020          if Ada_Version >= Ada_2012
8021            and then All_Present (Parent (Id))
8022            and then Is_Tagged_Type (T)
8023          then
8024             Use_Class_Wide_Operations (T);
8025          end if;
8026       end if;
8027
8028       --  If warning on redundant constructs, check for unnecessary WITH
8029
8030       if Warn_On_Redundant_Constructs
8031         and then Is_Known_Used
8032
8033          --                     with P;         with P; use P;
8034          --    package P is     package X is    package body X is
8035          --       type T ...       use P.T;
8036
8037          --  The compilation unit is the body of X. GNAT first compiles the
8038          --  spec of X, then proceeds to the body. At that point P is marked
8039          --  as use visible. The analysis then reinstalls the spec along with
8040          --  its context. The use clause P.T is now recognized as redundant,
8041          --  but in the wrong context. Do not emit a warning in such cases.
8042          --  Do not emit a warning either if we are in an instance, there is
8043          --  no redundancy between an outer use_clause and one that appears
8044          --  within the generic.
8045
8046         and then not Spec_Reloaded_For_Body
8047         and then not In_Instance
8048       then
8049          --  The type already has a use clause
8050
8051          if In_Use (T) then
8052
8053             --  Case where we know the current use clause for the type
8054
8055             if Present (Current_Use_Clause (T)) then
8056                Use_Clause_Known : declare
8057                   Clause1 : constant Node_Id := Parent (Id);
8058                   Clause2 : constant Node_Id := Current_Use_Clause (T);
8059                   Ent1    : Entity_Id;
8060                   Ent2    : Entity_Id;
8061                   Err_No  : Node_Id;
8062                   Unit1   : Node_Id;
8063                   Unit2   : Node_Id;
8064
8065                   function Entity_Of_Unit (U : Node_Id) return Entity_Id;
8066                   --  Return the appropriate entity for determining which unit
8067                   --  has a deeper scope: the defining entity for U, unless U
8068                   --  is a package instance, in which case we retrieve the
8069                   --  entity of the instance spec.
8070
8071                   --------------------
8072                   -- Entity_Of_Unit --
8073                   --------------------
8074
8075                   function Entity_Of_Unit (U : Node_Id) return Entity_Id is
8076                   begin
8077                      if Nkind (U) =  N_Package_Instantiation
8078                        and then Analyzed (U)
8079                      then
8080                         return Defining_Entity (Instance_Spec (U));
8081                      else
8082                         return Defining_Entity (U);
8083                      end if;
8084                   end Entity_Of_Unit;
8085
8086                --  Start of processing for Use_Clause_Known
8087
8088                begin
8089                   --  If both current use type clause and the use type clause
8090                   --  for the type are at the compilation unit level, one of
8091                   --  the units must be an ancestor of the other, and the
8092                   --  warning belongs on the descendant.
8093
8094                   if Nkind (Parent (Clause1)) = N_Compilation_Unit
8095                        and then
8096                      Nkind (Parent (Clause2)) = N_Compilation_Unit
8097                   then
8098
8099                      --  If the unit is a subprogram body that acts as spec,
8100                      --  the context clause is shared with the constructed
8101                      --  subprogram spec. Clearly there is no redundancy.
8102
8103                      if Clause1 = Clause2 then
8104                         return;
8105                      end if;
8106
8107                      Unit1 := Unit (Parent (Clause1));
8108                      Unit2 := Unit (Parent (Clause2));
8109
8110                      --  If both clauses are on same unit, or one is the body
8111                      --  of the other, or one of them is in a subunit, report
8112                      --  redundancy on the later one.
8113
8114                      if Unit1 = Unit2 then
8115                         Error_Msg_Sloc := Sloc (Current_Use_Clause (T));
8116                         Error_Msg_NE -- CODEFIX
8117                           ("& is already use-visible through previous "
8118                            & "use_type_clause #?", Clause1, T);
8119                         return;
8120
8121                      elsif Nkind (Unit1) = N_Subunit then
8122                         Error_Msg_Sloc := Sloc (Current_Use_Clause (T));
8123                         Error_Msg_NE -- CODEFIX
8124                           ("& is already use-visible through previous "
8125                            & "use_type_clause #?", Clause1, T);
8126                         return;
8127
8128                      elsif Nkind_In (Unit2, N_Package_Body, N_Subprogram_Body)
8129                        and then Nkind (Unit1) /= Nkind (Unit2)
8130                        and then Nkind (Unit1) /= N_Subunit
8131                      then
8132                         Error_Msg_Sloc := Sloc (Clause1);
8133                         Error_Msg_NE -- CODEFIX
8134                           ("& is already use-visible through previous "
8135                            & "use_type_clause #?", Current_Use_Clause (T), T);
8136                         return;
8137                      end if;
8138
8139                      --  There is a redundant use type clause in a child unit.
8140                      --  Determine which of the units is more deeply nested.
8141                      --  If a unit is a package instance, retrieve the entity
8142                      --  and its scope from the instance spec.
8143
8144                      Ent1 := Entity_Of_Unit (Unit1);
8145                      Ent2 := Entity_Of_Unit (Unit2);
8146
8147                      if Scope (Ent2) = Standard_Standard  then
8148                         Error_Msg_Sloc := Sloc (Current_Use_Clause (T));
8149                         Err_No := Clause1;
8150
8151                      elsif Scope (Ent1) = Standard_Standard then
8152                         Error_Msg_Sloc := Sloc (Id);
8153                         Err_No := Clause2;
8154
8155                      --  If both units are child units, we determine which one
8156                      --  is the descendant by the scope distance to the
8157                      --  ultimate parent unit.
8158
8159                      else
8160                         declare
8161                            S1, S2 : Entity_Id;
8162
8163                         begin
8164                            S1 := Scope (Ent1);
8165                            S2 := Scope (Ent2);
8166                            while Present (S1)
8167                              and then Present (S2)
8168                              and then S1 /= Standard_Standard
8169                              and then S2 /= Standard_Standard
8170                            loop
8171                               S1 := Scope (S1);
8172                               S2 := Scope (S2);
8173                            end loop;
8174
8175                            if S1 = Standard_Standard then
8176                               Error_Msg_Sloc := Sloc (Id);
8177                               Err_No := Clause2;
8178                            else
8179                               Error_Msg_Sloc := Sloc (Current_Use_Clause (T));
8180                               Err_No := Clause1;
8181                            end if;
8182                         end;
8183                      end if;
8184
8185                      Error_Msg_NE -- CODEFIX
8186                        ("& is already use-visible through previous "
8187                         & "use_type_clause #?", Err_No, Id);
8188
8189                   --  Case where current use type clause and the use type
8190                   --  clause for the type are not both at the compilation unit
8191                   --  level. In this case we don't have location information.
8192
8193                   else
8194                      Error_Msg_NE -- CODEFIX
8195                        ("& is already use-visible through previous "
8196                         & "use type clause?", Id, T);
8197                   end if;
8198                end Use_Clause_Known;
8199
8200             --  Here if Current_Use_Clause is not set for T, another case
8201             --  where we do not have the location information available.
8202
8203             else
8204                Error_Msg_NE -- CODEFIX
8205                  ("& is already use-visible through previous "
8206                   & "use type clause?", Id, T);
8207             end if;
8208
8209          --  The package where T is declared is already used
8210
8211          elsif In_Use (Scope (T)) then
8212             Error_Msg_Sloc := Sloc (Current_Use_Clause (Scope (T)));
8213             Error_Msg_NE -- CODEFIX
8214               ("& is already use-visible through package use clause #?",
8215                Id, T);
8216
8217          --  The current scope is the package where T is declared
8218
8219          else
8220             Error_Msg_Node_2 := Scope (T);
8221             Error_Msg_NE -- CODEFIX
8222               ("& is already use-visible inside package &?", Id, T);
8223          end if;
8224       end if;
8225    end Use_One_Type;
8226
8227    ----------------
8228    -- Write_Info --
8229    ----------------
8230
8231    procedure Write_Info is
8232       Id : Entity_Id := First_Entity (Current_Scope);
8233
8234    begin
8235       --  No point in dumping standard entities
8236
8237       if Current_Scope = Standard_Standard then
8238          return;
8239       end if;
8240
8241       Write_Str ("========================================================");
8242       Write_Eol;
8243       Write_Str ("        Defined Entities in ");
8244       Write_Name (Chars (Current_Scope));
8245       Write_Eol;
8246       Write_Str ("========================================================");
8247       Write_Eol;
8248
8249       if No (Id) then
8250          Write_Str ("-- none --");
8251          Write_Eol;
8252
8253       else
8254          while Present (Id) loop
8255             Write_Entity_Info (Id, " ");
8256             Next_Entity (Id);
8257          end loop;
8258       end if;
8259
8260       if Scope (Current_Scope) = Standard_Standard then
8261
8262          --  Print information on the current unit itself
8263
8264          Write_Entity_Info (Current_Scope, " ");
8265       end if;
8266
8267       Write_Eol;
8268    end Write_Info;
8269
8270    --------
8271    -- ws --
8272    --------
8273
8274    procedure ws is
8275       S : Entity_Id;
8276    begin
8277       for J in reverse 1 .. Scope_Stack.Last loop
8278          S :=  Scope_Stack.Table (J).Entity;
8279          Write_Int (Int (S));
8280          Write_Str (" === ");
8281          Write_Name (Chars (S));
8282          Write_Eol;
8283       end loop;
8284    end ws;
8285
8286 end Sem_Ch8;