OSDN Git Service

2007-09-26 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch10.adb
index a352efd..18e2076 100644 (file)
@@ -6,18 +6,17 @@
 --                                                                          --
 --                                 B o d y                                  --
 --                                                                          --
---          Copyright (C) 1992-2005 Free Software Foundation, Inc.          --
+--          Copyright (C) 1992-2007, Free Software Foundation, Inc.         --
 --                                                                          --
 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
 -- terms of the  GNU General Public License as published  by the Free Soft- --
--- ware  Foundation;  either version 2,  or (at your option) any later ver- --
+-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
 -- for  more details.  You should have  received  a copy of the GNU General --
--- Public License  distributed with GNAT;  see file COPYING.  If not, write --
--- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
--- Boston, MA 02110-1301, USA.                                              --
+-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
+-- http://www.gnu.org/licenses for a complete copy of the license.          --
 --                                                                          --
 -- GNAT was originally developed  by the GNAT team at  New York University. --
 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
@@ -43,8 +42,10 @@ with Nmake;    use Nmake;
 with Opt;      use Opt;
 with Output;   use Output;
 with Restrict; use Restrict;
+with Rident;   use Rident;
 with Rtsfind;  use Rtsfind;
 with Sem;      use Sem;
+with Sem_Ch3;  use Sem_Ch3;
 with Sem_Ch6;  use Sem_Ch6;
 with Sem_Ch7;  use Sem_Ch7;
 with Sem_Ch8;  use Sem_Ch8;
@@ -60,7 +61,6 @@ with Snames;   use Snames;
 with Style;    use Style;
 with Stylesw;  use Stylesw;
 with Tbuild;   use Tbuild;
-with Ttypes;   use Ttypes;
 with Uname;    use Uname;
 
 package body Sem_Ch10 is
@@ -83,10 +83,6 @@ package body Sem_Ch10 is
    --  Check whether the source for the body of a compilation unit must
    --  be included in a standalone library.
 
-   procedure Check_With_Type_Clauses (N : Node_Id);
-   --  If N is a body, verify that any with_type clauses on the spec, or
-   --  on the spec of any parent, have a matching with_clause.
-
    procedure Check_Private_Child_Unit (N : Node_Id);
    --  If a with_clause mentions a private child unit, the compilation
    --  unit must be a member of the same family, as described in 10.1.2 (8).
@@ -95,7 +91,7 @@ package body Sem_Ch10 is
    --  Verify that a stub is declared immediately within a compilation unit,
    --  and not in an inner frame.
 
-   procedure Expand_With_Clause (Nam : Node_Id; N : Node_Id);
+   procedure Expand_With_Clause (Item : Node_Id; Nam : Node_Id; N : Node_Id);
    --  When a child unit appears in a context clause, the implicit withs on
    --  parents are made explicit, and with clauses are inserted in the context
    --  clause before the one for the child. If a parent in the with_clause
@@ -115,6 +111,10 @@ package body Sem_Ch10 is
    --  If the main unit is a child unit, implicit withs are also added for
    --  all its ancestors.
 
+   function In_Chain (E : Entity_Id) return Boolean;
+   --  Check that the shadow entity is not already in the homonym chain, for
+   --  example through a limited_with clause in a parent unit.
+
    procedure Install_Context_Clauses (N : Node_Id);
    --  Subsidiary to Install_Context and Install_Parents. Process only with_
    --  and use_clauses for current unit and its library unit if any.
@@ -163,11 +163,6 @@ package body Sem_Ch10 is
    --  Lib_Unit can also be a subprogram body that acts as its own spec. If
    --  the Parent_Spec is  non-empty, this is also a child unit.
 
-   procedure Remove_With_Type_Clause (Name : Node_Id);
-   --  Remove imported type and its enclosing package from visibility, and
-   --  remove attributes of imported type so they don't interfere with its
-   --  analysis (should it appear otherwise in the context).
-
    procedure Remove_Context_Clauses (N : Node_Id);
    --  Subsidiary of previous one. Remove use_ and with_clauses
 
@@ -195,6 +190,10 @@ package body Sem_Ch10 is
    --  entity for which the proper body provides a completion. Subprogram
    --  stubs are handled differently because they can be declarations.
 
+   procedure sm;
+   --  A dummy procedure, for debugging use, called just before analyzing the
+   --  main unit (after dealing with any context clauses).
+
    --------------------------
    -- Limited_With_Clauses --
    --------------------------
@@ -230,15 +229,357 @@ package body Sem_Ch10 is
    procedure Analyze_Compilation_Unit (N : Node_Id) is
       Unit_Node     : constant Node_Id := Unit (N);
       Lib_Unit      : Node_Id          := Library_Unit (N);
-      Spec_Id       : Node_Id;
+      Spec_Id       : Entity_Id;
       Main_Cunit    : constant Node_Id := Cunit (Main_Unit);
       Par_Spec_Name : Unit_Name_Type;
       Unum          : Unit_Number_Type;
 
+      procedure Check_Redundant_Withs
+        (Context_Items      : List_Id;
+         Spec_Context_Items : List_Id := No_List);
+      --  Determine whether the context list of a compilation unit contains
+      --  redundant with clauses. When checking body clauses against spec
+      --  clauses, set Context_Items to the context list of the body and
+      --  Spec_Context_Items to that of the spec. Parent packages are not
+      --  examined for documentation purposes.
+
       procedure Generate_Parent_References (N : Node_Id; P_Id : Entity_Id);
       --  Generate cross-reference information for the parents of child units.
       --  N is a defining_program_unit_name, and P_Id is the immediate parent.
 
+      ---------------------------
+      -- Check_Redundant_Withs --
+      ---------------------------
+
+      procedure Check_Redundant_Withs
+        (Context_Items      : List_Id;
+         Spec_Context_Items : List_Id := No_List)
+      is
+         Clause : Node_Id;
+
+         procedure Process_Body_Clauses
+          (Context_List      : List_Id;
+           Clause            : Node_Id;
+           Used              : in out Boolean;
+           Used_Type_Or_Elab : in out Boolean);
+         --  Examine the context clauses of a package body, trying to match
+         --  the name entity of Clause with any list element. If the match
+         --  occurs on a use package clause, set Used to True, for a use
+         --  type clause, pragma Elaborate or pragma Elaborate_All, set
+         --  Used_Type_Or_Elab to True.
+
+         procedure Process_Spec_Clauses
+          (Context_List : List_Id;
+           Clause       : Node_Id;
+           Used         : in out Boolean;
+           Withed       : in out Boolean;
+           Exit_On_Self : Boolean := False);
+         --  Examine the context clauses of a package spec, trying to match
+         --  the name entity of Clause with any list element. If the match
+         --  occurs on a use package clause, set Used to True, for a with
+         --  package clause other than Clause, set Withed to True. Limited
+         --  with clauses, implicitly generated with clauses and withs
+         --  having pragmas Elaborate or Elaborate_All applied to them are
+         --  skipped. Exit_On_Self is used to control the search loop and
+         --  force an exit whenever Clause sees itself in the search.
+
+         --------------------------
+         -- Process_Body_Clauses --
+         --------------------------
+
+         procedure Process_Body_Clauses
+          (Context_List      : List_Id;
+           Clause            : Node_Id;
+           Used              : in out Boolean;
+           Used_Type_Or_Elab : in out Boolean)
+         is
+            Nam_Ent   : constant Entity_Id := Entity (Name (Clause));
+            Cont_Item : Node_Id;
+            Prag_Unit : Node_Id;
+            Subt_Mark : Node_Id;
+            Use_Item  : Node_Id;
+
+            function Same_Unit (N : Node_Id; P : Entity_Id) return Boolean;
+            --  In an expanded name in a use clause, if the prefix is a
+            --  renamed package, the entity is set to the original package
+            --  as a result, when checking whether the package appears in a
+            --  previous with_clause, the renaming has to be taken into
+            --  account, to prevent spurious or incorrect warnings. The
+            --  common case is the use of Text_IO.
+
+            ---------------
+            -- Same_Unit --
+            ---------------
+
+            function Same_Unit (N : Node_Id; P : Entity_Id) return Boolean is
+            begin
+               return Entity (N) = P
+                 or else
+                   (Present (Renamed_Object (P))
+                     and then Entity (N) = Renamed_Object (P));
+            end Same_Unit;
+
+         --  Start of processing for Process_Body_Clauses
+
+         begin
+            Used := False;
+            Used_Type_Or_Elab := False;
+
+            Cont_Item := First (Context_List);
+            while Present (Cont_Item) loop
+
+               --  Package use clause
+
+               if Nkind (Cont_Item) = N_Use_Package_Clause
+                 and then not Used
+               then
+                  --  Search through use clauses
+
+                  Use_Item := First (Names (Cont_Item));
+                  while Present (Use_Item) and then not Used loop
+
+                     --  Case of a direct use of the one we are looking for
+
+                     if Entity (Use_Item) = Nam_Ent then
+                        Used := True;
+
+                     --  Handle nested case, as in "with P; use P.Q.R"
+
+                     else
+                        declare
+                           UE : Node_Id;
+
+                        begin
+                           --  Loop through prefixes looking for match
+
+                           UE := Use_Item;
+                           while Nkind (UE) = N_Expanded_Name loop
+                              if Same_Unit (Prefix (UE), Nam_Ent) then
+                                 Used := True;
+                                 exit;
+                              end if;
+
+                              UE := Prefix (UE);
+                           end loop;
+                        end;
+                     end if;
+
+                     Next (Use_Item);
+                  end loop;
+
+               --  USE TYPE clause
+
+               elsif Nkind (Cont_Item) = N_Use_Type_Clause
+                 and then not Used_Type_Or_Elab
+               then
+                  Subt_Mark := First (Subtype_Marks (Cont_Item));
+                  while Present (Subt_Mark)
+                    and then not Used_Type_Or_Elab
+                  loop
+                     if Same_Unit (Prefix (Subt_Mark), Nam_Ent) then
+                        Used_Type_Or_Elab := True;
+                     end if;
+
+                     Next (Subt_Mark);
+                  end loop;
+
+               --  Pragma Elaborate or Elaborate_All
+
+               elsif Nkind (Cont_Item) = N_Pragma
+                 and then
+                   (Chars (Cont_Item) = Name_Elaborate
+                      or else
+                    Chars (Cont_Item) = Name_Elaborate_All)
+                 and then not Used_Type_Or_Elab
+               then
+                  Prag_Unit :=
+                    First (Pragma_Argument_Associations (Cont_Item));
+                  while Present (Prag_Unit)
+                    and then not Used_Type_Or_Elab
+                  loop
+                     if Entity (Expression (Prag_Unit)) = Nam_Ent then
+                        Used_Type_Or_Elab := True;
+                     end if;
+
+                     Next (Prag_Unit);
+                  end loop;
+               end if;
+
+               Next (Cont_Item);
+            end loop;
+         end Process_Body_Clauses;
+
+         --------------------------
+         -- Process_Spec_Clauses --
+         --------------------------
+
+         procedure Process_Spec_Clauses
+          (Context_List : List_Id;
+           Clause       : Node_Id;
+           Used         : in out Boolean;
+           Withed       : in out Boolean;
+           Exit_On_Self : Boolean := False)
+         is
+            Nam_Ent   : constant Entity_Id := Entity (Name (Clause));
+            Cont_Item : Node_Id;
+            Use_Item  : Node_Id;
+
+         begin
+            Used := False;
+            Withed := False;
+
+            Cont_Item := First (Context_List);
+            while Present (Cont_Item) loop
+
+               --  Stop the search since the context items after Cont_Item
+               --  have already been examined in a previous iteration of
+               --  the reverse loop in Check_Redundant_Withs.
+
+               if Exit_On_Self
+                 and Cont_Item = Clause
+               then
+                  exit;
+               end if;
+
+               --  Package use clause
+
+               if Nkind (Cont_Item) = N_Use_Package_Clause
+                 and then not Used
+               then
+                  Use_Item := First (Names (Cont_Item));
+                  while Present (Use_Item) and then not Used loop
+                     if Entity (Use_Item) = Nam_Ent then
+                        Used := True;
+                     end if;
+
+                     Next (Use_Item);
+                  end loop;
+
+               --  Package with clause. Avoid processing self, implicitly
+               --  generated with clauses or limited with clauses. Note
+               --  that we examine with clauses having pragmas Elaborate
+               --  or Elaborate_All applied to them due to cases such as:
+               --
+               --     with Pack;
+               --     with Pack;
+               --     pragma Elaborate (Pack);
+               --
+               --  In this case, the second with clause is redundant since
+               --  the pragma applies only to the first "with Pack;".
+
+               elsif Nkind (Cont_Item) = N_With_Clause
+                 and then not Implicit_With (Cont_Item)
+                 and then not Limited_Present (Cont_Item)
+                 and then Cont_Item /= Clause
+                 and then Entity (Name (Cont_Item)) = Nam_Ent
+               then
+                  Withed := True;
+               end if;
+
+               Next (Cont_Item);
+            end loop;
+         end Process_Spec_Clauses;
+
+      --  Start of processing for Check_Redundant_Withs
+
+      begin
+         Clause := Last (Context_Items);
+         while Present (Clause) loop
+
+            --  Avoid checking implicitly generated with clauses, limited
+            --  with clauses or withs that have pragma Elaborate or
+            --  Elaborate_All apllied.
+
+            if Nkind (Clause) = N_With_Clause
+              and then not Implicit_With (Clause)
+              and then not Limited_Present (Clause)
+              and then not Elaborate_Present (Clause)
+            then
+               --  Package body-to-spec check
+
+               if Present (Spec_Context_Items) then
+                  declare
+                     Used_In_Body      : Boolean := False;
+                     Used_In_Spec      : Boolean := False;
+                     Used_Type_Or_Elab : Boolean := False;
+                     Withed_In_Spec    : Boolean := False;
+
+                  begin
+                     Process_Spec_Clauses
+                      (Context_List => Spec_Context_Items,
+                       Clause       => Clause,
+                       Used         => Used_In_Spec,
+                       Withed       => Withed_In_Spec);
+
+                     Process_Body_Clauses
+                      (Context_List      => Context_Items,
+                       Clause            => Clause,
+                       Used              => Used_In_Body,
+                       Used_Type_Or_Elab => Used_Type_Or_Elab);
+
+                     --  "Type Elab" refers to the presence of either a use
+                     --  type clause, pragmas Elaborate or Elaborate_All.
+
+                     --  +---------------+---------------------------+------+
+                     --  | Spec          | Body                      | Warn |
+                     --  +--------+------+--------+------+-----------+------+
+                     --  | Withed | Used | Withed | Used | Type Elab |      |
+                     --  |   X    |      |   X    |      |           |  X   |
+                     --  |   X    |      |   X    |  X   |           |      |
+                     --  |   X    |      |   X    |      |     X     |      |
+                     --  |   X    |      |   X    |  X   |     X     |      |
+                     --  |   X    |  X   |   X    |      |           |  X   |
+                     --  |   X    |  X   |   X    |      |     X     |      |
+                     --  |   X    |  X   |   X    |  X   |           |  X   |
+                     --  |   X    |  X   |   X    |  X   |     X     |      |
+                     --  +--------+------+--------+------+-----------+------+
+
+                     if (Withed_In_Spec
+                           and then not Used_Type_Or_Elab)
+                             and then
+                               ((not Used_In_Spec
+                                   and then not Used_In_Body)
+                                     or else
+                                       Used_In_Spec)
+                     then
+                        Error_Msg_N ("?redundant with clause in body", Clause);
+                     end if;
+
+                     Used_In_Body := False;
+                     Used_In_Spec := False;
+                     Used_Type_Or_Elab := False;
+                     Withed_In_Spec := False;
+                  end;
+
+               --  Standalone package spec or body check
+
+               else
+                  declare
+                     Dont_Care : Boolean := False;
+                     Withed    : Boolean := False;
+
+                  begin
+                     --  The mechanism for examining the context clauses of a
+                     --  package spec can be applied to package body clauses.
+
+                     Process_Spec_Clauses
+                      (Context_List => Context_Items,
+                       Clause       => Clause,
+                       Used         => Dont_Care,
+                       Withed       => Withed,
+                       Exit_On_Self => True);
+
+                     if Withed then
+                        Error_Msg_N ("?redundant with clause", Clause);
+                     end if;
+                  end;
+               end if;
+            end if;
+
+            Prev (Clause);
+         end loop;
+      end Check_Redundant_Withs;
+
       --------------------------------
       -- Generate_Parent_References --
       --------------------------------
@@ -248,7 +589,7 @@ package body Sem_Ch10 is
          P_Name : Entity_Id := P_Id;
 
       begin
-         Pref   := Name (Parent (Defining_Entity (N)));
+         Pref := Name (Parent (Defining_Entity (N)));
 
          if Nkind (Pref) = N_Expanded_Name then
 
@@ -365,16 +706,16 @@ package body Sem_Ch10 is
             --  If the subprogram body is a child unit, we must create a
             --  declaration for it, in order to properly load the parent(s).
             --  After this, the original unit does not acts as a spec, because
-            --  there is an explicit one. If this  unit appears in a context
+            --  there is an explicit one. If this unit appears in a context
             --  clause, then an implicit with on the parent will be added when
             --  installing the context. If this is the main unit, there is no
-            --  Unit_Table entry for the declaration, (It has the unit number
+            --  Unit_Table entry for the declaration (it has the unit number
             --  of the main unit) and code generation is unaffected.
 
             Unum := Get_Cunit_Unit_Number (N);
             Par_Spec_Name := Get_Parent_Spec_Name (Unit_Name (Unum));
 
-            if Par_Spec_Name /= No_Name then
+            if Par_Spec_Name /= No_Unit_Name then
                Unum :=
                  Load_Unit
                    (Load_Name  => Par_Spec_Name,
@@ -387,7 +728,10 @@ package body Sem_Ch10 is
                   --  Build subprogram declaration and attach parent unit to it
                   --  This subprogram declaration does not come from source,
                   --  Nevertheless the backend must generate debugging info for
-                  --  it, and this must be indicated explicitly.
+                  --  it, and this must be indicated explicitly. We also mark
+                  --  the body entity as a child unit now, to prevent a
+                  --  cascaded error if the spec entity cannot be entered
+                  --  in its scope.
 
                   declare
                      Loc : constant Source_Ptr := Sloc (N);
@@ -410,7 +754,12 @@ package body Sem_Ch10 is
                      Set_Library_Unit (N, Lib_Unit);
                      Set_Parent_Spec (Unit (Lib_Unit), Cunit (Unum));
                      Semantics (Lib_Unit);
+
+                     --  Now that a separate declaration exists, the body
+                     --  of the child unit does not act as spec any longer.
+
                      Set_Acts_As_Spec (N, False);
+                     Set_Is_Child_Unit (Defining_Entity (Unit_Node));
                      Set_Needs_Debug_Info (Defining_Entity (Unit (Lib_Unit)));
                      Set_Comes_From_Source_Default (SCS);
                   end;
@@ -459,9 +808,9 @@ package body Sem_Ch10 is
       end if;
 
       --  With the analysis done, install the context. Note that we can't
-      --  install the context from the with clauses as we analyze them,
-      --  because each with clause must be analyzed in a clean visibility
-      --  context, so we have to wait and install them all at once.
+      --  install the context from the with clauses as we analyze them, because
+      --  each with clause must be analyzed in a clean visibility context, so
+      --  we have to wait and install them all at once.
 
       Install_Context (N);
 
@@ -474,13 +823,30 @@ package body Sem_Ch10 is
       end if;
 
       --  All components of the context: with-clauses, library unit, ancestors
-      --  if any, (and their context)  are analyzed and installed. Now analyze
-      --  the unit itself, which is either a package, subprogram spec or body.
+      --  if any, (and their context)  are analyzed and installed.
+
+      --  Call special debug routine sm if this is the main unit
+
+      if Current_Sem_Unit = Main_Unit then
+         sm;
+      end if;
+
+      --  Now analyze the unit (package, subprogram spec, body) itself
 
       Analyze (Unit_Node);
 
-      --  The above call might have made Unit_Node an N_Subprogram_Body
-      --  from something else, so propagate any Acts_As_Spec flag.
+      if Warn_On_Redundant_Constructs then
+         Check_Redundant_Withs (Context_Items (N));
+
+         if Nkind (Unit_Node) = N_Package_Body then
+            Check_Redundant_Withs
+              (Context_Items      => Context_Items (N),
+               Spec_Context_Items => Context_Items (Lib_Unit));
+         end if;
+      end if;
+
+      --  The above call might have made Unit_Node an N_Subprogram_Body from
+      --  something else, so propagate any Acts_As_Spec flag.
 
       if Nkind (Unit_Node) = N_Subprogram_Body
         and then Acts_As_Spec (Unit_Node)
@@ -503,7 +869,6 @@ package body Sem_Ch10 is
       if Present (Pragmas_After (Aux_Decls_Node (N))) then
          declare
             Prag_Node : Node_Id := First (Pragmas_After (Aux_Decls_Node (N)));
-
          begin
             while Present (Prag_Node) loop
                Analyze (Prag_Node);
@@ -549,18 +914,27 @@ package body Sem_Ch10 is
 
       end if;
 
+      --  Remove unit from visibility, so that environment is clean for
+      --  the next compilation, which is either the main unit or some
+      --  other unit in the context.
+
       if Nkind (Unit_Node) = N_Package_Declaration
         or else Nkind (Unit_Node) in N_Generic_Declaration
         or else Nkind (Unit_Node) = N_Package_Renaming_Declaration
         or else Nkind (Unit_Node) = N_Subprogram_Declaration
+        or else
+          (Nkind (Unit_Node) = N_Subprogram_Body
+            and then Acts_As_Spec (Unit_Node))
       then
          Remove_Unit_From_Visibility (Defining_Entity (Unit_Node));
 
-      --  If the unit is an instantiation whose body will be elaborated
-      --  for inlining purposes, use the the proper entity of the instance.
+      --  If the unit is an instantiation whose body will be elaborated for
+      --  inlining purposes, use the the proper entity of the instance. The
+      --  entity may be missing if the instantiation was illegal.
 
       elsif Nkind (Unit_Node) = N_Package_Instantiation
         and then not Error_Posted (Unit_Node)
+        and then Present (Instance_Spec (Unit_Node))
       then
          Remove_Unit_From_Visibility
            (Defining_Entity (Instance_Spec (Unit_Node)));
@@ -569,41 +943,41 @@ package body Sem_Ch10 is
         or else (Nkind (Unit_Node) = N_Subprogram_Body
                   and then not Acts_As_Spec (Unit_Node))
       then
-         --  Bodies that are not the main unit are compiled if they
-         --  are generic or contain generic or inlined units. Their
-         --  analysis brings in the context of the corresponding spec
-         --  (unit declaration) which must be removed as well, to
-         --  return the compilation environment to its proper state.
+         --  Bodies that are not the main unit are compiled if they are generic
+         --  or contain generic or inlined units. Their analysis brings in the
+         --  context of the corresponding spec (unit declaration) which must be
+         --  removed as well, to return the compilation environment to its
+         --  proper state.
 
          Remove_Context (Lib_Unit);
          Set_Is_Immediately_Visible (Defining_Entity (Unit (Lib_Unit)), False);
       end if;
 
-      --  Last step is to deinstall the context we just installed
-      --  as well as the unit just compiled.
+      --  Last step is to deinstall the context we just installed as well as
+      --  the unit just compiled.
 
       Remove_Context (N);
 
-      --  If this is the main unit and we are generating code, we must
-      --  check that all generic units in the context have a body if they
-      --  need it, even if they have not been instantiated. In the absence
-      --  of .ali files for generic units, we must force the load of the body,
-      --  just to produce the proper error if the body is absent. We skip this
+      --  If this is the main unit and we are generating code, we must check
+      --  that all generic units in the context have a body if they need it,
+      --  even if they have not been instantiated. In the absence of .ali files
+      --  for generic units, we must force the load of the body, just to
+      --  produce the proper error if the body is absent. We skip this
       --  verification if the main unit itself is generic.
 
       if Get_Cunit_Unit_Number (N) = Main_Unit
         and then Operating_Mode = Generate_Code
         and then Expander_Active
       then
-         --  Check whether the source for the body of the unit must be
-         --  included in a standalone library.
+         --  Check whether the source for the body of the unit must be included
+         --  in a standalone library.
 
          Check_Body_Needed_For_SAL (Cunit_Entity (Main_Unit));
 
          --  Indicate that the main unit is now analyzed, to catch possible
-         --  circularities between it and generic bodies. Remove main unit
-         --  from visibility. This might seem superfluous, but the main unit
-         --  must not be visible in the generic body expansions that follow.
+         --  circularities between it and generic bodies. Remove main unit from
+         --  visibility. This might seem superfluous, but the main unit must
+         --  not be visible in the generic body expansions that follow.
 
          Set_Analyzed (N, True);
          Set_Is_Immediately_Visible (Cunit_Entity (Main_Unit), False);
@@ -621,11 +995,14 @@ package body Sem_Ch10 is
             Item := First (Context_Items (N));
             while Present (Item) loop
 
-               --  Ada 2005 (AI-50217): Do not consider limited-withed units
+               --  Check for explicit with clause
 
                if Nkind (Item) = N_With_Clause
-                  and then not Implicit_With (Item)
-                  and then not Limited_Present (Item)
+                 and then not Implicit_With (Item)
+
+                  --  Ada 2005 (AI-50217): Ignore limited-withed units
+
+                 and then not Limited_Present (Item)
                then
                   Nam := Entity (Name (Item));
 
@@ -687,23 +1064,28 @@ package body Sem_Ch10 is
 
       if Comes_From_Source (N)
         and then
-          (Nkind (Unit (N)) =  N_Package_Declaration         or else
-           Nkind (Unit (N)) =  N_Generic_Package_Declaration or else
-           Nkind (Unit (N)) =  N_Subprogram_Declaration      or else
-           Nkind (Unit (N)) =  N_Generic_Subprogram_Declaration)
+          (Nkind (Unit_Node) = N_Package_Declaration         or else
+           Nkind (Unit_Node) = N_Generic_Package_Declaration or else
+           Nkind (Unit_Node) = N_Subprogram_Declaration      or else
+           Nkind (Unit_Node) = N_Generic_Subprogram_Declaration)
       then
          declare
             Loc  : constant Source_Ptr := Sloc (N);
             Unum : constant Unit_Number_Type := Get_Source_Unit (Loc);
 
          begin
-            Spec_Id := Defining_Entity (Unit (N));
+            Spec_Id := Defining_Entity (Unit_Node);
             Generate_Definition (Spec_Id);
 
-            --  See if an elaboration entity is required for possible
-            --  access before elaboration checking. Note that we must
-            --  allow for this even if -gnatE is not set, since a client
-            --  may be compiled in -gnatE mode and reference the entity.
+            --  See if an elaboration entity is required for possible access
+            --  before elaboration checking. Note that we must allow for this
+            --  even if -gnatE is not set, since a client may be compiled in
+            --  -gnatE mode and reference the entity.
+
+            --  These entities are also used by the binder to prevent multiple
+            --  attempts to execute the elaboration code for the library case
+            --  where the elaboration routine might otherwise be called more
+            --  than once.
 
             --  Case of units which do not require elaboration checks
 
@@ -748,16 +1130,15 @@ package body Sem_Ch10 is
          end;
       end if;
 
-      --  Finally, freeze the compilation unit entity. This for sure is needed
-      --  because of some warnings that can be output (see Freeze_Subprogram),
-      --  but may in general be required. If freezing actions result, place
-      --  them in the compilation unit actions list, and analyze them.
+      --  Freeze the compilation unit entity. This for sure is needed because
+      --  of some warnings that can be output (see Freeze_Subprogram), but may
+      --  in general be required. If freezing actions result, place them in the
+      --  compilation unit actions list, and analyze them.
 
       declare
          Loc : constant Source_Ptr := Sloc (N);
          L   : constant List_Id :=
                  Freeze_Entity (Cunit_Entity (Current_Sem_Unit), Loc);
-
       begin
          while Is_Non_Empty_List (L) loop
             Insert_Library_Level_Action (Remove_Head (L));
@@ -773,7 +1154,7 @@ package body Sem_Ch10 is
          declare
             Save_Style_Check : constant Boolean := Style_Check;
             Save_Warning     : constant Warning_Mode_Type := Warning_Mode;
-            Options : Style_Check_Options;
+            Options          : Style_Check_Options;
 
          begin
             Save_Style_Check_Options (Options);
@@ -787,6 +1168,56 @@ package body Sem_Ch10 is
             Warning_Mode := Save_Warning;
          end;
       end if;
+
+      --  If we are generating obsolescent warnings, then here is where we
+      --  generate them for the with'ed items. The reason for this special
+      --  processing is that the normal mechanism of generating the warnings
+      --  for referenced entities does not work for context clause references.
+      --  That's because when we first analyze the context, it is too early to
+      --  know if the with'ing unit is itself obsolescent (which suppresses
+      --  the warnings).
+
+      if not GNAT_Mode and then Warn_On_Obsolescent_Feature then
+
+         --  Push current compilation unit as scope, so that the test for
+         --  being within an obsolescent unit will work correctly.
+
+         Push_Scope (Defining_Entity (Unit_Node));
+
+         --  Loop through context items to deal with with clauses
+
+         declare
+            Item : Node_Id;
+            Nam  : Node_Id;
+            Ent  : Entity_Id;
+
+         begin
+            Item := First (Context_Items (N));
+            while Present (Item) loop
+               if Nkind (Item) = N_With_Clause
+
+                  --  Suppress this check in limited-withed units. Further work
+                  --  needed here if we decide to incorporate this check on
+                  --  limited-withed units.
+
+                 and then not Limited_Present (Item)
+               then
+                  Nam := Name (Item);
+                  Ent := Entity (Nam);
+
+                  if Is_Obsolescent (Ent) then
+                     Output_Obsolescent_Entity_Warnings (Nam, Ent);
+                  end if;
+               end if;
+
+               Next (Item);
+            end loop;
+         end;
+
+         --  Remove temporary install of current unit as scope
+
+         Pop_Scope;
+      end if;
    end Analyze_Compilation_Unit;
 
    ---------------------
@@ -798,11 +1229,30 @@ package body Sem_Ch10 is
       Item  : Node_Id;
 
    begin
-      --  Loop through context items. This is done in two:
-      --  a) The first  pass analyzes non-limited with-clauses
-      --  b) The second pass analyzes limited_with clauses (Ada 2005: AI-50217)
+      --  First process all configuration pragmas at the start of the context
+      --  items. Strictly these are not part of the context clause, but that
+      --  is where the parser puts them. In any case for sure we must analyze
+      --  these before analyzing the actual context items, since they can have
+      --  an effect on that analysis (e.g. pragma Ada_2005 may allow a unit to
+      --  be with'ed as a result of changing categorizations in Ada 2005).
 
       Item := First (Context_Items (N));
+      while Present (Item)
+        and then Nkind (Item) = N_Pragma
+        and then Chars (Item) in Configuration_Pragma_Names
+      loop
+         Analyze (Item);
+         Next (Item);
+      end loop;
+
+      --  Loop through actual context items. This is done in two passes:
+
+      --  a) The first pass analyzes non-limited with-clauses and also any
+      --     configuration pragmas (we need to get the latter analyzed right
+      --     away, since they can affect processing of subsequent items.
+
+      --  b) The second pass analyzes limited_with clauses (Ada 2005: AI-50217)
+
       while Present (Item) loop
 
          --  For with clause, analyze the with clause, and then update
@@ -811,7 +1261,6 @@ package body Sem_Ch10 is
          if Nkind (Item) = N_With_Clause
            and then not Limited_Present (Item)
          then
-
             --  Skip analyzing with clause if no unit, nothing to do (this
             --  happens for a with that references a non-existant unit)
 
@@ -823,12 +1272,16 @@ package body Sem_Ch10 is
                Version_Update (N, Library_Unit (Item));
             end if;
 
-         --  But skip use clauses at this stage, since we don't want to do
-         --  any installing of potentially use visible entities until we
-         --  we actually install the complete context (in Install_Context).
+         --  Skip pragmas. Configuration pragmas at the start were handled in
+         --  the loop above, and remaining pragmas are not processed until we
+         --  actually install the context (see Install_Context). We delay the
+         --  analysis of these pragmas to make sure that we have installed all
+         --  the implicit with's on parent units.
+
+         --  Skip use clauses at this stage, since we don't want to do any
+         --  installing of potentially use visible entities until we we
+         --  actually install the complete context (in Install_Context).
          --  Otherwise things can get installed in the wrong context.
-         --  Similarly, pragmas are analyzed in Install_Context, after all
-         --  the implicit with's on parent units are generated.
 
          else
             null;
@@ -837,7 +1290,8 @@ package body Sem_Ch10 is
          Next (Item);
       end loop;
 
-      --  Second pass: examine all limited_with clauses
+      --  Second pass: examine all limited_with clauses. All other context
+      --  items are ignored in this pass.
 
       Item := First (Context_Items (N));
       while Present (Item) loop
@@ -853,14 +1307,11 @@ package body Sem_Ch10 is
 
                if Ukind /= N_Package_Declaration
                  and then Ukind /= N_Subprogram_Declaration
-                 and then Ukind /= N_Subprogram_Renaming_Declaration
-                 and then Ukind /= N_Generic_Package_Declaration
-                 and then Ukind /= N_Generic_Package_Renaming_Declaration
-                 and then Ukind /= N_Generic_Subprogram_Declaration
-                 and then Ukind /= N_Generic_Procedure_Renaming_Declaration
-                 and then Ukind /= N_Package_Instantiation
                  and then Ukind /= N_Package_Renaming_Declaration
-                 and then Ukind /= N_Procedure_Instantiation
+                 and then Ukind /= N_Subprogram_Renaming_Declaration
+                 and then Ukind not in N_Generic_Declaration
+                 and then Ukind not in N_Generic_Renaming_Declaration
+                 and then Ukind not in N_Generic_Instantiation
                then
                   Error_Msg_N ("limited with_clause not allowed here", Item);
 
@@ -938,14 +1389,14 @@ package body Sem_Ch10 is
                                                       Unit_Name)
                               then
                                  Error_Msg_Sloc := Sloc (It);
+                                 Error_Msg_N
+                                   ("simultaneous visibility of limited "
+                                    & "and unlimited views not allowed",
+                                    Item);
                                  Error_Msg_NE
-                                   ("unlimited view visible through the"
-                                    & " context clause found #",
+                                   ("\unlimited view visible through "
+                                    & "context clause #",
                                     Item, It);
-                                 Error_Msg_N
-                                   ("simultaneous visibility of the limited"
-                                    & " and unlimited views not allowed"
-                                    , Item);
                                  exit;
 
                               elsif Nkind (Unit_Name) = N_Identifier then
@@ -978,6 +1429,12 @@ package body Sem_Ch10 is
             if not Implicit_With (Item) then
                Version_Update (N, Library_Unit (Item));
             end if;
+
+            --  Pragmas and use clauses and with clauses other than limited
+            --  with's are ignored in this pass through the context items.
+
+         else
+            null;
          end if;
 
          Next (Item);
@@ -998,7 +1455,7 @@ package body Sem_Ch10 is
       Check_Stub_Level (N);
       Nam := Current_Entity_In_Scope (Id);
 
-      if No (Nam) or else not Is_Package (Nam) then
+      if No (Nam) or else not Is_Package_Or_Generic_Package (Nam) then
          Error_Msg_N ("missing specification for package stub", N);
 
       elsif Has_Completion (Nam)
@@ -1211,11 +1668,11 @@ package body Sem_Ch10 is
             if Original_Operating_Mode = Generate_Code
               and then Unum = No_Unit
             then
-               Error_Msg_Name_1 := Subunit_Name;
-               Error_Msg_Name_2 :=
+               Error_Msg_Unit_1 := Subunit_Name;
+               Error_Msg_File_1 :=
                  Get_File_Name (Subunit_Name, Subunit => True);
                Error_Msg_N
-                 ("subunit% in file{ not found!?", N);
+                 ("subunit$$ in file{ not found?", N);
                Subunits_Missing := True;
             end if;
 
@@ -1225,9 +1682,7 @@ package body Sem_Ch10 is
 
             Compiler_State := Analyzing;
 
-            if Unum /= No_Unit
-              and then (not Fatal_Error (Unum) or else Try_Semantics)
-            then
+            if Unum /= No_Unit then
                if Debug_Flag_L then
                   Write_Str ("*** Loaded subunit from stub. Analyze");
                   Write_Eol;
@@ -1244,12 +1699,21 @@ package body Sem_Ch10 is
                        ("expected SEPARATE subunit, found child unit",
                         Cunit_Entity (Unum));
 
-                  --  OK, we have a subunit, so go ahead and analyze it,
-                  --  and set Scope of entity in stub, for ASIS use.
+                  --  OK, we have a subunit
 
                   else
+                     --  Set corresponding stub (even if errors)
+
                      Set_Corresponding_Stub (Unit (Comp_Unit), N);
-                     Analyze_Subunit (Comp_Unit);
+
+                     --  Analyze the unit if semantics active
+
+                     if not Fatal_Error (Unum) or else Try_Semantics then
+                        Analyze_Subunit (Comp_Unit);
+                     end if;
+
+                     --  Set the library unit pointer in any case
+
                      Set_Library_Unit (N, Comp_Unit);
 
                      --  We update the version. Although we are not technically
@@ -1329,7 +1793,6 @@ package body Sem_Ch10 is
         or else Nkind (Parent (N)) = N_Subprogram_Body
       then
          Decl := First (Declarations (Parent (N)));
-
          while Present (Decl)
            and then Decl /= N
          loop
@@ -1417,34 +1880,36 @@ package body Sem_Ch10 is
 
       begin
          Analyze_Context (N);
-         Item := First (Context_Items (N));
 
-         --  make withed units immediately visible. If child unit, make the
+         --  Make withed units immediately visible. If child unit, make the
          --  ultimate parent immediately visible.
 
+         Item := First (Context_Items (N));
          while Present (Item) loop
-
             if Nkind (Item) = N_With_Clause then
-               --  Protect the frontend against previous errors
-               --  in context clauses
+
+               --  Protect frontend against previous errors in context clauses
 
                if Nkind (Name (Item)) /= N_Selected_Component then
-                  Unit_Name := Entity (Name (Item));
+                  if Error_Posted (Item) then
+                     null;
 
-                  while Is_Child_Unit (Unit_Name) loop
-                     Set_Is_Visible_Child_Unit (Unit_Name);
-                     Unit_Name := Scope (Unit_Name);
-                  end loop;
+                  else
+                     Unit_Name := Entity (Name (Item));
+                     while Is_Child_Unit (Unit_Name) loop
+                        Set_Is_Visible_Child_Unit (Unit_Name);
+                        Unit_Name := Scope (Unit_Name);
+                     end loop;
 
-                  if not Is_Immediately_Visible (Unit_Name) then
-                     Set_Is_Immediately_Visible (Unit_Name);
-                     Set_Context_Installed (Item);
+                     if not Is_Immediately_Visible (Unit_Name) then
+                        Set_Is_Immediately_Visible (Unit_Name);
+                        Set_Context_Installed (Item);
+                     end if;
                   end if;
                end if;
 
             elsif Nkind (Item) = N_Use_Package_Clause then
                Nam := First (Names (Item));
-
                while Present (Nam) loop
                   Analyze (Nam);
                   Next (Nam);
@@ -1452,7 +1917,6 @@ package body Sem_Ch10 is
 
             elsif Nkind (Item) = N_Use_Type_Clause then
                Nam := First (Subtype_Marks (Item));
-
                while Present (Nam) loop
                   Analyze (Nam);
                   Next (Nam);
@@ -1462,22 +1926,19 @@ package body Sem_Ch10 is
             Next (Item);
          end loop;
 
-         Item := First (Context_Items (N));
-
-         --  reset visibility of withed units. They will be made visible
+         --  Reset visibility of withed units. They will be made visible
          --  again when we install the subunit context.
 
+         Item := First (Context_Items (N));
          while Present (Item) loop
-
             if Nkind (Item) = N_With_Clause
 
-               --  Protect the frontend against previous errors in context
-               --  clauses
+               --  Protect frontend against previous errors in context clauses
 
               and then Nkind (Name (Item)) /= N_Selected_Component
+              and then not Error_Posted (Item)
             then
                Unit_Name := Entity (Name (Item));
-
                while Is_Child_Unit (Unit_Name) loop
                   Set_Is_Visible_Child_Unit (Unit_Name, False);
                   Unit_Name := Scope (Unit_Name);
@@ -1491,7 +1952,6 @@ package body Sem_Ch10 is
 
             Next (Item);
          end loop;
-
       end Analyze_Subunit_Context;
 
       ------------------------
@@ -1515,17 +1975,16 @@ package body Sem_Ch10 is
             Install_Siblings (Enclosing_Child, L);
          end if;
 
-         New_Scope (Scop);
+         Push_Scope (Scop);
 
          if Scop /= Par_Unit then
             Set_Is_Immediately_Visible (Scop);
          end if;
 
-         E := First_Entity (Current_Scope);
-
          --  Make entities in scope visible again. For child units, restore
          --  visibility only if they are actually in context.
 
+         E := First_Entity (Current_Scope);
          while Present (E) loop
             if not Is_Child_Unit (E)
               or else Is_Visible_Child_Unit (E)
@@ -1540,7 +1999,9 @@ package body Sem_Ch10 is
          --  all the parents are bodies. Restore full visibility of their
          --  private entities.
 
-         if Ekind (Scop) = E_Package then
+         if Ekind (Scop) = E_Package
+           or else Ekind (Scop) = E_Generic_Package
+         then
             Set_In_Package_Body (Scop);
             Install_Private_Declarations (Scop);
          end if;
@@ -1552,7 +2013,6 @@ package body Sem_Ch10 is
 
       procedure Re_Install_Use_Clauses is
          U  : Node_Id;
-
       begin
          for J in reverse 1 .. Num_Scopes loop
             U := Use_Clauses (J);
@@ -1571,9 +2031,9 @@ package body Sem_Ch10 is
       begin
          Num_Scopes := Num_Scopes + 1;
          Use_Clauses (Num_Scopes) :=
-               Scope_Stack.Table (Scope_Stack.Last).First_Use_Clause;
-         E := First_Entity (Current_Scope);
+           Scope_Stack.Table (Scope_Stack.Last).First_Use_Clause;
 
+         E := First_Entity (Current_Scope);
          while Present (E) loop
             Set_Is_Immediately_Visible (E, False);
             Next_Entity (E);
@@ -1631,7 +2091,9 @@ package body Sem_Ch10 is
          --  context includes another subunit of the same parent which in
          --  turn includes a child unit in its context.
 
-         if Ekind (Par_Unit) = E_Package then
+         if Ekind (Par_Unit) = E_Package
+           or else Ekind (Par_Unit) = E_Generic_Package
+         then
             if not Is_Immediately_Visible (Par_Unit)
               or else (Present (First_Entity (Par_Unit))
                         and then not Is_Immediately_Visible
@@ -1662,6 +2124,26 @@ package body Sem_Ch10 is
 
       Analyze (Proper_Body (Unit (N)));
       Remove_Context (N);
+
+      --  The subunit may contain a with_clause on a sibling of some
+      --  ancestor. Removing the context will remove from visibility those
+      --  ancestor child units, which must be restored to the visibility
+      --  they have in the enclosing body.
+
+      if Present (Enclosing_Child) then
+         declare
+            C : Entity_Id;
+         begin
+            C := Current_Scope;
+            while Present (C)
+              and then Is_Child_Unit (C)
+            loop
+               Set_Is_Immediately_Visible (C);
+               Set_Is_Visible_Child_Unit (C);
+               C := Scope (C);
+            end loop;
+         end;
+      end if;
    end Analyze_Subunit;
 
    ----------------------------
@@ -1726,7 +2208,7 @@ package body Sem_Ch10 is
 
       Unit_Kind : constant Node_Kind :=
                     Nkind (Original_Node (Unit (Library_Unit (N))));
-
+      Nam       : constant Node_Id := Name (N);
       E_Name    : Entity_Id;
       Par_Name  : Entity_Id;
       Pref      : Node_Id;
@@ -1741,8 +2223,9 @@ package body Sem_Ch10 is
 
    begin
       if Limited_Present (N) then
+
          --  Ada 2005 (AI-50217): Build visibility structures but do not
-         --  analyze unit
+         --  analyze the unit.
 
          Build_Limited_Views (N);
          return;
@@ -1775,27 +2258,42 @@ package body Sem_Ch10 is
       end if;
 
       U := Unit (Library_Unit (N));
-      Check_Restriction_No_Dependence (Name (N), N);
       Intunit := Is_Internal_File_Name (Unit_File_Name (Current_Sem_Unit));
 
-      --  Following checks are skipped for dummy packages (those supplied
-      --  for with's where no matching file could be found). Such packages
-      --  are identified by the Sloc value being set to No_Location
+      --  Following checks are skipped for dummy packages (those supplied for
+      --  with's where no matching file could be found). Such packages are
+      --  identified by the Sloc value being set to No_Location
 
       if Sloc (U) /= No_Location then
 
-         --  Check restrictions, except that we skip the check if this
-         --  is an internal unit unless we are compiling the internal
-         --  unit as the main unit. We also skip this for dummy packages.
+         --  Check restrictions, except that we skip the check if this is an
+         --  internal unit unless we are compiling the internal unit as the
+         --  main unit. We also skip this for dummy packages.
+
+         Check_Restriction_No_Dependence (Nam, N);
 
          if not Intunit or else Current_Sem_Unit = Main_Unit then
             Check_Restricted_Unit (Unit_Name (Get_Source_Unit (U)), N);
          end if;
 
-         --  Check for inappropriate with of internal implementation unit
-         --  if we are currently compiling the main unit and the main unit
-         --  is itself not an internal unit. We do not issue this message
-         --  for implicit with's generated by the compiler itself.
+         --  Deal with special case of GNAT.Current_Exceptions which interacts
+         --  with the optimization of local raise statements into gotos.
+
+         if Nkind (Nam) = N_Selected_Component
+           and then Nkind (Prefix (Nam)) = N_Identifier
+           and then Chars (Prefix (Nam)) = Name_Gnat
+           and then (Chars (Selector_Name (Nam)) = Name_Most_Recent_Exception
+                       or else
+                     Chars (Selector_Name (Nam)) = Name_Exception_Traces)
+         then
+            Check_Restriction (No_Exception_Propagation, N);
+            Special_Exception_Package_Used := True;
+         end if;
+
+         --  Check for inappropriate with of internal implementation unit if we
+         --  are currently compiling the main unit and the main unit is itself
+         --  not an internal unit. We do not issue this message for implicit
+         --  with's generated by the compiler itself.
 
          if Implementation_Unit_Warnings
            and then Current_Sem_Unit = Main_Unit
@@ -1809,8 +2307,8 @@ package body Sem_Ch10 is
 
             begin
                if U_Kind = Implementation_Unit then
-                  Error_Msg_N ("& is an internal 'G'N'A'T unit?", Name (N));
-                  Error_Msg_N
+                  Error_Msg_F ("& is an internal 'G'N'A'T unit?", Name (N));
+                  Error_Msg_F
                     ("\use of this unit is non-portable " &
                      "and version-dependent?",
                      Name (N));
@@ -1832,11 +2330,11 @@ package body Sem_Ch10 is
       if Unit_Kind in N_Generic_Declaration then
          E_Name := Defining_Entity (U);
 
-      --  Note: in the following test, Unit_Kind is the original Nkind, but
-      --  in the case of an instantiation, semantic analysis above will
-      --  have replaced the unit by its instantiated version. If the instance
-      --  body has been generated, the instance now denotes the body entity.
-      --  For visibility purposes we need the entity of its spec.
+      --  Note: in the following test, Unit_Kind is the original Nkind, but in
+      --  the case of an instantiation, semantic analysis above will have
+      --  replaced the unit by its instantiated version. If the instance body
+      --  has been generated, the instance now denotes the body entity. For
+      --  visibility purposes we need the entity of its spec.
 
       elsif (Unit_Kind = N_Package_Instantiation
               or else Nkind (Original_Node (Unit (Library_Unit (N)))) =
@@ -1854,20 +2352,13 @@ package body Sem_Ch10 is
 
          E_Name := Defining_Entity (Specification (Instance_Spec (U)));
 
-      elsif Unit_Kind = N_Procedure_Instantiation
-        or else Unit_Kind = N_Function_Instantiation
-      then
-         --  Instantiation node is replaced with a package that contains
-         --  renaming declarations and instance itself. The subprogram
-         --  Instance is declared in the visible part of the wrapper package.
+      elsif Unit_Kind in N_Subprogram_Instantiation then
 
-         E_Name := First_Entity (Defining_Entity (U));
+         --  Instantiation node is replaced with a wrapper package. Retrieve
+         --  the visible subprogram created by the instance from corresponding
+         --  attribute of the wrapper.
 
-         while Present (E_Name) loop
-            exit when Is_Subprogram (E_Name)
-              and then Is_Generic_Instance (E_Name);
-            E_Name := Next_Entity (E_Name);
-         end loop;
+         E_Name := Related_Instance (Defining_Entity (U));
 
       elsif Unit_Kind = N_Package_Renaming_Declaration
         or else Unit_Kind in N_Generic_Renaming_Declaration
@@ -1899,9 +2390,9 @@ package body Sem_Ch10 is
       Style_Check := Save_Style_Check;
       Cunit_Boolean_Restrictions_Restore (Save_C_Restrict);
 
-      --  Record the reference, but do NOT set the unit as referenced, we
-      --  want to consider the unit as unreferenced if this is the only
-      --  reference that occurs.
+      --  Record the reference, but do NOT set the unit as referenced, we want
+      --  to consider the unit as unreferenced if this is the only reference
+      --  that occurs.
 
       Set_Entity_With_Style_Check (Name (N), E_Name);
       Generate_Reference (E_Name, Name (N), 'w', Set_Ref => False);
@@ -1909,7 +2400,6 @@ package body Sem_Ch10 is
       if Is_Child_Unit (E_Name) then
          Pref     := Prefix (Name (N));
          Par_Name := Scope (E_Name);
-
          while Nkind (Pref) = N_Selected_Component loop
             Change_Selected_Component_To_Expanded_Name (Pref);
             Set_Entity_With_Style_Check (Pref, Par_Name);
@@ -1917,9 +2407,9 @@ package body Sem_Ch10 is
             Generate_Reference (Par_Name, Pref);
             Pref := Prefix (Pref);
 
-            --  If E_Name is the dummy entity for a nonexistent unit,
-            --  its scope is set to Standard_Standard, and no attempt
-            --  should be made to further unwind scopes.
+            --  If E_Name is the dummy entity for a nonexistent unit, its scope
+            --  is set to Standard_Standard, and no attempt should be made to
+            --  further unwind scopes.
 
             if Par_Name /= Standard_Standard then
                Par_Name := Scope (Par_Name);
@@ -1929,12 +2419,12 @@ package body Sem_Ch10 is
          if Present (Entity (Pref))
            and then not Analyzed (Parent (Parent (Entity (Pref))))
          then
-            --  If the entity is set without its unit being compiled,
-            --  the original parent is a renaming, and Par_Name is the
-            --  renamed entity. For visibility purposes, we need the
-            --  original entity, which must be analyzed now, because
-            --  Load_Unit retrieves directly the renamed unit, and the
-            --  renaming declaration itself has not been analyzed.
+            --  If the entity is set without its unit being compiled, the
+            --  original parent is a renaming, and Par_Name is the renamed
+            --  entity. For visibility purposes, we need the original entity,
+            --  which must be analyzed now because Load_Unit directly retrieves
+            --  the renamed unit, and the renaming declaration itself has not
+            --  been analyzed.
 
             Analyze (Parent (Parent (Entity (Pref))));
             pragma Assert (Renamed_Object (Entity (Pref)) = Par_Name);
@@ -1946,8 +2436,8 @@ package body Sem_Ch10 is
       end if;
 
       --  If the withed unit is System, and a system extension pragma is
-      --  present, compile the extension now, rather than waiting for
-      --  visibility check on a specific entity.
+      --  present, compile the extension now, rather than waiting for a
+      --  visibility check on a specific entity.
 
       if Chars (E_Name) = Name_System
         and then Scope (E_Name) = Standard_Standard
@@ -1969,386 +2459,42 @@ package body Sem_Ch10 is
    end Analyze_With_Clause;
 
    ------------------------------
-   -- Analyze_With_Type_Clause --
+   -- Check_Private_Child_Unit --
    ------------------------------
 
-   procedure Analyze_With_Type_Clause (N : Node_Id) is
-      Loc  : constant Source_Ptr := Sloc (N);
-      Nam  : constant Node_Id    := Name (N);
-      Pack : Node_Id;
-      Decl : Node_Id;
-      P    : Entity_Id;
-      Unum : Unit_Number_Type;
-      Sel  : Node_Id;
-
-      procedure Decorate_Tagged_Type (T : Entity_Id);
-      --  Set basic attributes of type, including its class_wide type
-
-      function In_Chain (E : Entity_Id) return Boolean;
-      --  Check that the imported type is not already in the homonym chain,
-      --  for example through a with_type clause in a parent unit.
+   procedure Check_Private_Child_Unit (N : Node_Id) is
+      Lib_Unit   : constant Node_Id := Unit (N);
+      Item       : Node_Id;
+      Curr_Unit  : Entity_Id;
+      Sub_Parent : Node_Id;
+      Priv_Child : Entity_Id;
+      Par_Lib    : Entity_Id;
+      Par_Spec   : Node_Id;
 
-      --------------------------
-      -- Decorate_Tagged_Type --
-      --------------------------
+      function Is_Private_Library_Unit (Unit : Entity_Id) return Boolean;
+      --  Returns true if and only if the library unit is declared with
+      --  an explicit designation of private.
 
-      procedure Decorate_Tagged_Type (T : Entity_Id) is
-         CW : Entity_Id;
+      function Is_Private_Library_Unit (Unit : Entity_Id) return Boolean is
+         Comp_Unit : constant Node_Id := Parent (Unit_Declaration_Node (Unit));
 
       begin
-         Set_Ekind (T, E_Record_Type);
-         Set_Is_Tagged_Type (T);
-         Set_Etype (T, T);
-         Set_From_With_Type (T);
-         Set_Scope (T, P);
+         return Private_Present (Comp_Unit);
+      end Is_Private_Library_Unit;
 
-         if not In_Chain (T) then
-            Set_Homonym (T, Current_Entity (T));
-            Set_Current_Entity (T);
-         end if;
+   --  Start of processing for Check_Private_Child_Unit
 
-         --  Build bogus class_wide type, if not previously done
+   begin
+      if Nkind (Lib_Unit) = N_Package_Body
+        or else Nkind (Lib_Unit) = N_Subprogram_Body
+      then
+         Curr_Unit := Defining_Entity (Unit (Library_Unit (N)));
+         Par_Lib   := Curr_Unit;
 
-         if No (Class_Wide_Type (T)) then
-            CW := Make_Defining_Identifier (Loc,  New_Internal_Name ('S'));
+      elsif Nkind (Lib_Unit) = N_Subunit then
 
-            Set_Ekind            (CW, E_Class_Wide_Type);
-            Set_Etype            (CW, T);
-            Set_Scope            (CW, P);
-            Set_Is_Tagged_Type   (CW);
-            Set_Is_First_Subtype (CW, True);
-            Init_Size_Align      (CW);
-            Set_Has_Unknown_Discriminants
-                                 (CW, True);
-            Set_Class_Wide_Type  (CW, CW);
-            Set_Equivalent_Type  (CW, Empty);
-            Set_From_With_Type   (CW);
-
-            Set_Class_Wide_Type (T, CW);
-         end if;
-      end Decorate_Tagged_Type;
-
-      --------------
-      -- In_Chain --
-      --------------
-
-      function In_Chain (E : Entity_Id) return Boolean is
-         H : Entity_Id := Current_Entity (E);
-
-      begin
-         while Present (H) loop
-
-            if H = E then
-               return True;
-            else
-               H := Homonym (H);
-            end if;
-         end loop;
-
-         return False;
-      end In_Chain;
-
-   --  Start of processing for Analyze_With_Type_Clause
-
-   begin
-      if Nkind (Nam) = N_Selected_Component then
-         Pack := New_Copy_Tree (Prefix (Nam));
-         Sel  := Selector_Name (Nam);
-
-      else
-         Error_Msg_N ("illegal name for imported type", Nam);
-         return;
-      end if;
-
-      Decl :=
-        Make_Package_Declaration (Loc,
-          Specification =>
-             (Make_Package_Specification (Loc,
-               Defining_Unit_Name   => Pack,
-               Visible_Declarations => New_List,
-               End_Label            => Empty)));
-
-      Unum :=
-        Load_Unit
-          (Load_Name  => Get_Unit_Name (Decl),
-           Required   => True,
-           Subunit    => False,
-           Error_Node => Nam);
-
-      if Unum = No_Unit
-         or else Nkind (Unit (Cunit (Unum))) /= N_Package_Declaration
-      then
-         Error_Msg_N ("imported type must be declared in package", Nam);
-         return;
-
-      elsif Unum = Current_Sem_Unit then
-
-         --  If type is defined in unit being analyzed, then the clause
-         --  is redundant.
-
-         return;
-
-      else
-         P := Cunit_Entity (Unum);
-      end if;
-
-      --  Find declaration for imported type, and set its basic attributes
-      --  if it has not been analyzed (which will be the case if there is
-      --  circular dependence).
-
-      declare
-         Decl : Node_Id;
-         Typ  : Entity_Id;
-
-      begin
-         if not Analyzed (Cunit (Unum))
-           and then not From_With_Type (P)
-         then
-            Set_Ekind (P, E_Package);
-            Set_Etype (P, Standard_Void_Type);
-            Set_From_With_Type (P);
-            Set_Scope (P, Standard_Standard);
-            Set_Homonym (P, Current_Entity (P));
-            Set_Current_Entity (P);
-
-         elsif Analyzed (Cunit (Unum))
-           and then Is_Child_Unit (P)
-         then
-            --  If the child unit is already in scope, indicate that it is
-            --  visible, and remains so after intervening calls to rtsfind.
-
-            Set_Is_Visible_Child_Unit (P);
-         end if;
-
-         if Nkind (Parent (P)) = N_Defining_Program_Unit_Name then
-
-            --  Make parent packages visible
-
-            declare
-               Parent_Comp : Node_Id;
-               Parent_Id   : Entity_Id;
-               Child       : Entity_Id;
-
-            begin
-               Child   := P;
-               Parent_Comp := Parent_Spec (Unit (Cunit (Unum)));
-
-               loop
-                  Parent_Id := Defining_Entity (Unit (Parent_Comp));
-                  Set_Scope (Child, Parent_Id);
-
-                  --  The type may be imported from a child unit, in which
-                  --  case the current compilation appears in the name. Do
-                  --  not change its visibility here because it will conflict
-                  --  with the subsequent normal processing.
-
-                  if not Analyzed (Unit_Declaration_Node (Parent_Id))
-                    and then Parent_Id /= Cunit_Entity (Current_Sem_Unit)
-                  then
-                     Set_Ekind (Parent_Id, E_Package);
-                     Set_Etype (Parent_Id, Standard_Void_Type);
-
-                     --  The same package may appear is several with_type
-                     --  clauses.
-
-                     if not From_With_Type (Parent_Id) then
-                        Set_Homonym (Parent_Id, Current_Entity (Parent_Id));
-                        Set_Current_Entity (Parent_Id);
-                        Set_From_With_Type (Parent_Id);
-                     end if;
-                  end if;
-
-                  Set_Is_Immediately_Visible (Parent_Id);
-
-                  Child := Parent_Id;
-                  Parent_Comp := Parent_Spec (Unit (Parent_Comp));
-                  exit when No (Parent_Comp);
-               end loop;
-
-               Set_Scope (Parent_Id, Standard_Standard);
-            end;
-         end if;
-
-         --  Even if analyzed, the package may not be currently visible. It
-         --  must be while the with_type clause is active.
-
-         Set_Is_Immediately_Visible (P);
-
-         Decl :=
-           First (Visible_Declarations (Specification (Unit (Cunit (Unum)))));
-
-         while Present (Decl) loop
-
-            if Nkind (Decl) = N_Full_Type_Declaration
-              and then Chars (Defining_Identifier (Decl)) = Chars (Sel)
-            then
-               Typ := Defining_Identifier (Decl);
-
-               if Tagged_Present (N) then
-
-                  --  The declaration must indicate that this is a tagged
-                  --  type or a type extension.
-
-                  if (Nkind (Type_Definition (Decl)) = N_Record_Definition
-                       and then Tagged_Present (Type_Definition (Decl)))
-                    or else
-                      (Nkind (Type_Definition (Decl))
-                          = N_Derived_Type_Definition
-                         and then Present
-                           (Record_Extension_Part (Type_Definition (Decl))))
-                  then
-                     null;
-                  else
-                     Error_Msg_N ("imported type is not a tagged type", Nam);
-                     return;
-                  end if;
-
-                  if not Analyzed (Decl) then
-
-                     --  Unit is not currently visible. Add basic attributes
-                     --  to type and build its class-wide type.
-
-                     Init_Size_Align (Typ);
-                     Decorate_Tagged_Type (Typ);
-                  end if;
-
-               else
-                  if Nkind (Type_Definition (Decl))
-                     /= N_Access_To_Object_Definition
-                  then
-                     Error_Msg_N
-                      ("imported type is not an access type", Nam);
-
-                  elsif not Analyzed (Decl) then
-                     Set_Ekind                    (Typ, E_Access_Type);
-                     Set_Etype                    (Typ, Typ);
-                     Set_Scope                    (Typ, P);
-                     Init_Size                    (Typ, System_Address_Size);
-                     Init_Alignment               (Typ);
-                     Set_Directly_Designated_Type (Typ, Standard_Integer);
-                     Set_From_With_Type           (Typ);
-
-                     if not In_Chain (Typ) then
-                        Set_Homonym               (Typ, Current_Entity (Typ));
-                        Set_Current_Entity        (Typ);
-                     end if;
-                  end if;
-               end if;
-
-               Set_Entity (Sel, Typ);
-               return;
-
-            elsif ((Nkind (Decl) = N_Private_Type_Declaration
-                      and then Tagged_Present (Decl))
-                or else (Nkind (Decl) = N_Private_Extension_Declaration))
-              and then Chars (Defining_Identifier (Decl)) = Chars (Sel)
-            then
-               Typ := Defining_Identifier (Decl);
-
-               if not Tagged_Present (N) then
-                  Error_Msg_N ("type must be declared tagged", N);
-
-               elsif not Analyzed (Decl) then
-                  Decorate_Tagged_Type (Typ);
-               end if;
-
-               Set_Entity (Sel, Typ);
-               Set_From_With_Type (Typ);
-               return;
-            end if;
-
-            Decl := Next (Decl);
-         end loop;
-
-         Error_Msg_NE ("not a visible access or tagged type in&", Nam, P);
-      end;
-   end Analyze_With_Type_Clause;
-
-   -----------------------------
-   -- Check_With_Type_Clauses --
-   -----------------------------
-
-   procedure Check_With_Type_Clauses (N : Node_Id) is
-      Lib_Unit : constant Node_Id := Unit (N);
-
-      procedure Check_Parent_Context (U : Node_Id);
-      --  Examine context items of parent unit to locate with_type clauses
-
-      --------------------------
-      -- Check_Parent_Context --
-      --------------------------
-
-      procedure Check_Parent_Context (U : Node_Id) is
-         Item : Node_Id;
-
-      begin
-         Item := First (Context_Items (U));
-         while Present (Item) loop
-            if Nkind (Item) = N_With_Type_Clause
-              and then not Error_Posted (Item)
-              and then
-                From_With_Type (Scope (Entity (Selector_Name (Name (Item)))))
-            then
-               Error_Msg_Sloc := Sloc (Item);
-               Error_Msg_N ("missing With_Clause for With_Type_Clause#", N);
-            end if;
-
-            Next (Item);
-         end loop;
-      end Check_Parent_Context;
-
-   --  Start of processing for Check_With_Type_Clauses
-
-   begin
-      if Extensions_Allowed
-        and then (Nkind (Lib_Unit) = N_Package_Body
-                   or else Nkind (Lib_Unit) = N_Subprogram_Body)
-      then
-         Check_Parent_Context (Library_Unit (N));
-
-         if Is_Child_Spec (Unit (Library_Unit (N))) then
-            Check_Parent_Context (Parent_Spec (Unit (Library_Unit (N))));
-         end if;
-      end if;
-   end Check_With_Type_Clauses;
-
-   ------------------------------
-   -- Check_Private_Child_Unit --
-   ------------------------------
-
-   procedure Check_Private_Child_Unit (N : Node_Id) is
-      Lib_Unit   : constant Node_Id := Unit (N);
-      Item       : Node_Id;
-      Curr_Unit  : Entity_Id;
-      Sub_Parent : Node_Id;
-      Priv_Child : Entity_Id;
-      Par_Lib    : Entity_Id;
-      Par_Spec   : Node_Id;
-
-      function Is_Private_Library_Unit (Unit : Entity_Id) return Boolean;
-      --  Returns true if and only if the library unit is declared with
-      --  an explicit designation of private.
-
-      function Is_Private_Library_Unit (Unit : Entity_Id) return Boolean is
-         Comp_Unit : constant Node_Id := Parent (Unit_Declaration_Node (Unit));
-
-      begin
-         return Private_Present (Comp_Unit);
-      end Is_Private_Library_Unit;
-
-   --  Start of processing for Check_Private_Child_Unit
-
-   begin
-      if Nkind (Lib_Unit) = N_Package_Body
-        or else Nkind (Lib_Unit) = N_Subprogram_Body
-      then
-         Curr_Unit := Defining_Entity (Unit (Library_Unit (N)));
-         Par_Lib   := Curr_Unit;
-
-      elsif Nkind (Lib_Unit) = N_Subunit then
-
-         --  The parent is itself a body. The parent entity is to be found
-         --  in the corresponding spec.
+         --  The parent is itself a body. The parent entity is to be found in
+         --  the corresponding spec.
 
          Sub_Parent := Library_Unit (N);
          Curr_Unit  := Defining_Entity (Unit (Library_Unit (Sub_Parent)));
@@ -2386,7 +2532,6 @@ package body Sem_Ch10 is
 
          if Nkind (Item) = N_With_Clause
             and then not Implicit_With (Item)
-            and then not Private_Present (Item)
             and then Is_Private_Descendant (Entity (Name (Item)))
          then
             Priv_Child := Entity (Name (Item));
@@ -2398,9 +2543,9 @@ package body Sem_Ch10 is
                Curr_Private : Boolean   := Is_Private_Library_Unit (Curr_Unit);
 
             begin
-               --  If the child unit is a public child then locate
-               --  the nearest private ancestor; Child_Parent will
-               --  then be set to the parent of that ancestor.
+               --  If the child unit is a public child then locate the nearest
+               --  private ancestor. Child_Parent will then be set to the
+               --  parent of that ancestor.
 
                if not Is_Private_Library_Unit (Priv_Child) then
                   while Present (Prv_Ancestor)
@@ -2423,12 +2568,11 @@ package body Sem_Ch10 is
                   Curr_Parent := Scope (Curr_Parent);
                end loop;
 
-               if not Present (Curr_Parent) then
+               if No (Curr_Parent) then
                   Curr_Parent := Standard_Standard;
                end if;
 
                if Curr_Parent /= Child_Parent then
-
                   if Ekind (Priv_Child) = E_Generic_Package
                     and then Chars (Priv_Child) in Text_IO_Package_Name
                     and then Chars (Scope (Scope (Priv_Child))) = Name_Ada
@@ -2441,11 +2585,12 @@ package body Sem_Ch10 is
                      Error_Msg_N
                        ("unit in with clause is private child unit!", Item);
                      Error_Msg_NE
-                       ("current unit must also have parent&!",
+                       ("\current unit must also have parent&!",
                         Item, Child_Parent);
                   end if;
 
                elsif not Curr_Private
+                 and then not Private_Present (Item)
                  and then Nkind (Lib_Unit) /= N_Package_Body
                  and then Nkind (Lib_Unit) /= N_Subprogram_Body
                  and then Nkind (Lib_Unit) /= N_Subunit
@@ -2475,9 +2620,8 @@ package body Sem_Ch10 is
            or else Kind = N_Subprogram_Body
            or else Kind = N_Task_Body
            or else Kind = N_Protected_Body)
-
         and then (Nkind (Parent (Par)) = N_Compilation_Unit
-                   or else Nkind (Parent (Par)) = N_Subunit)
+                    or else Nkind (Parent (Par)) = N_Subunit)
       then
          null;
 
@@ -2496,13 +2640,18 @@ package body Sem_Ch10 is
    -- Expand_With_Clause --
    ------------------------
 
-   procedure Expand_With_Clause (Nam : Node_Id; N : Node_Id) is
+   procedure Expand_With_Clause (Item : Node_Id; Nam : Node_Id; N : Node_Id) is
       Loc   : constant Source_Ptr := Sloc (Nam);
       Ent   : constant Entity_Id := Entity (Nam);
       Withn : Node_Id;
       P     : Node_Id;
 
       function Build_Unit_Name (Nam : Node_Id) return Node_Id;
+      --  Comment requireed here ???
+
+      ---------------------
+      -- Build_Unit_Name --
+      ---------------------
 
       function Build_Unit_Name (Nam : Node_Id) return Node_Id is
          Result : Node_Id;
@@ -2522,6 +2671,8 @@ package body Sem_Ch10 is
          end if;
       end Build_Unit_Name;
 
+   --  Start of processing for Expand_With_Clause
+
    begin
       New_Nodes_OK := New_Nodes_OK + 1;
       Withn :=
@@ -2533,12 +2684,20 @@ package body Sem_Ch10 is
       Set_First_Name            (Withn, True);
       Set_Implicit_With         (Withn, True);
 
+      --  If the unit is a package declaration, a private_with_clause on a
+      --  child unit implies that the implicit with on the parent is also
+      --  private.
+
+      if Nkind (Unit (N)) = N_Package_Declaration then
+         Set_Private_Present       (Withn, Private_Present (Item));
+      end if;
+
       Prepend (Withn, Context_Items (N));
       Mark_Rewrite_Insertion (Withn);
       Install_Withed_Unit (Withn);
 
       if Nkind (Nam) = N_Expanded_Name then
-         Expand_With_Clause (Prefix (Nam), N);
+         Expand_With_Clause (Item, Prefix (Nam), N);
       end if;
 
       New_Nodes_OK := New_Nodes_OK - 1;
@@ -2575,9 +2734,7 @@ package body Sem_Ch10 is
    is
       Loc    : constant Source_Ptr := Sloc (N);
       P      : constant Node_Id    := Parent_Spec (Child_Unit);
-
-      P_Unit : Node_Id    := Unit (P);
-
+      P_Unit : Node_Id             := Unit (P);
       P_Name : constant Entity_Id  := Get_Parent_Entity (P_Unit);
       Withn  : Node_Id;
 
@@ -2585,8 +2742,7 @@ package body Sem_Ch10 is
       --  Build prefix of child unit name. Recurse if needed
 
       function Build_Unit_Name return Node_Id;
-      --  If the unit is a child unit, build qualified name with all
-      --  ancestors.
+      --  If the unit is a child unit, build qualified name with all ancestors
 
       -------------------------
       -- Build_Ancestor_Name --
@@ -2640,9 +2796,9 @@ package body Sem_Ch10 is
    --  Start of processing for Implicit_With_On_Parent
 
    begin
-      --  The unit of the current compilation may be a package body
-      --  that replaces an instance node. In this case we need the
-      --  original instance node to construct the proper parent name.
+      --  The unit of the current compilation may be a package body that
+      --  replaces an instance node. In this case we need the original instance
+      --  node to construct the proper parent name.
 
       if Nkind (P_Unit) = N_Package_Body
         and then Nkind (Original_Node (P_Unit)) = N_Package_Instantiation
@@ -2650,6 +2806,16 @@ package body Sem_Ch10 is
          P_Unit := Original_Node (P_Unit);
       end if;
 
+      --  We add the implicit with if the child unit is the current unit being
+      --  compiled. If the current unit is a body, we do not want to add an
+      --  implicit_with a second time to the corresponding spec.
+
+      if Nkind (Child_Unit) = N_Package_Declaration
+        and then Child_Unit /= Unit (Cunit (Current_Sem_Unit))
+      then
+         return;
+      end if;
+
       New_Nodes_OK := New_Nodes_OK + 1;
       Withn := Make_With_Clause (Loc, Name => Build_Unit_Name);
 
@@ -2672,6 +2838,26 @@ package body Sem_Ch10 is
       New_Nodes_OK := New_Nodes_OK - 1;
    end Implicit_With_On_Parent;
 
+   --------------
+   -- In_Chain --
+   --------------
+
+   function In_Chain (E : Entity_Id) return Boolean is
+      H : Entity_Id;
+
+   begin
+      H := Current_Entity (E);
+      while Present (H) loop
+         if H = E then
+            return True;
+         else
+            H := Homonym (H);
+         end if;
+      end loop;
+
+      return False;
+   end In_Chain;
+
    ---------------------
    -- Install_Context --
    ---------------------
@@ -2688,7 +2874,6 @@ package body Sem_Ch10 is
 
       Install_Limited_Context_Clauses (N);
 
-      Check_With_Type_Clauses (N);
    end Install_Context;
 
    -----------------------------
@@ -2704,11 +2889,22 @@ package body Sem_Ch10 is
       Lib_Parent    : Entity_Id;
 
    begin
-      --  Loop through context clauses to find the with/use clauses.
-      --  This is done twice, first for everything except limited_with
-      --  clauses, and then for those, if any are present.
+      --  First skip configuration pragmas at the start of the context. They
+      --  are not technically part of the context clause, but that's where the
+      --  parser puts them. Note they were analyzed in Analyze_Context.
 
       Item := First (Context_Items (N));
+      while Present (Item)
+        and then Nkind (Item) = N_Pragma
+        and then Chars (Item) in Configuration_Pragma_Names
+      loop
+         Next (Item);
+      end loop;
+
+      --  Loop through the actual context clause items. We process everything
+      --  except Limited_With clauses in this routine. Limited_With clauses
+      --  are separately installed (see Install_Limited_Context_Clauses).
+
       while Present (Item) loop
 
          --  Case of explicit WITH clause
@@ -2743,8 +2939,8 @@ package body Sem_Ch10 is
 
             Decl_Node := Unit_Declaration_Node (Uname_Node);
 
-            --  If the unit is a subprogram instance, it appears nested
-            --  within a package that carries the parent information.
+            --  If the unit is a subprogram instance, it appears nested within
+            --  a package that carries the parent information.
 
             if Is_Generic_Instance (Uname_Node)
               and then Ekind (Uname_Node) /= E_Package
@@ -2754,7 +2950,7 @@ package body Sem_Ch10 is
 
             if Is_Child_Spec (Decl_Node) then
                if Nkind (Name (Item)) = N_Expanded_Name then
-                  Expand_With_Clause (Prefix (Name (Item)), N);
+                  Expand_With_Clause (Item, Prefix (Name (Item)), N);
                else
                   --  if not an expanded name, the child unit must be a
                   --  renaming, nothing to do.
@@ -2774,10 +2970,12 @@ package body Sem_Ch10 is
 
             if Sloc (Library_Unit (Item)) /= No_Location then
                License_Check : declare
+
+                  Withu : constant Unit_Number_Type :=
+                            Get_Source_Unit (Library_Unit (Item));
+
                   Withl : constant License_Type :=
-                            License (Source_Index
-                                       (Get_Source_Unit
-                                         (Library_Unit (Item))));
+                            License (Source_Index (Withu));
 
                   Unitl : constant License_Type :=
                            License (Source_Index (Current_Sem_Unit));
@@ -2792,35 +2990,44 @@ package body Sem_Ch10 is
                   procedure License_Error is
                   begin
                      Error_Msg_N
-                       ("?license of with'ed unit & is incompatible",
+                       ("?license of with'ed unit & may be inconsistent",
                         Name (Item));
                   end License_Error;
 
                --  Start of processing for License_Check
 
                begin
-                  case Unitl is
-                     when Unknown =>
-                        null;
+                  --  Exclude license check if withed unit is an internal unit.
+                  --  This situation arises e.g. with the GPL version of GNAT.
 
-                     when Restricted =>
-                        if Withl = GPL then
-                           License_Error;
-                        end if;
+                  if Is_Internal_File_Name (Unit_File_Name (Withu)) then
+                     null;
 
-                     when GPL =>
-                        if Withl = Restricted then
-                           License_Error;
-                        end if;
+                     --  Otherwise check various cases
+                  else
+                     case Unitl is
+                        when Unknown =>
+                           null;
 
-                     when Modified_GPL =>
-                        if Withl = Restricted or else Withl = GPL then
-                           License_Error;
-                        end if;
+                        when Restricted =>
+                           if Withl = GPL then
+                              License_Error;
+                           end if;
 
-                     when Unrestricted =>
-                        null;
-                  end case;
+                        when GPL =>
+                           if Withl = Restricted then
+                              License_Error;
+                           end if;
+
+                        when Modified_GPL =>
+                           if Withl = Restricted or else Withl = GPL then
+                              License_Error;
+                           end if;
+
+                        when Unrestricted =>
+                           null;
+                     end case;
+                  end if;
                end License_Check;
             end if;
 
@@ -2834,15 +3041,6 @@ package body Sem_Ch10 is
          elsif Nkind (Item) = N_Use_Type_Clause then
             Analyze_Use_Type (Item);
 
-         --  Case of WITH TYPE clause
-
-         --  A With_Type_Clause is processed when installing the context,
-         --  because it is a visibility mechanism and does not create a
-         --  semantic dependence on other units, as a With_Clause does.
-
-         elsif Nkind (Item) = N_With_Type_Clause then
-            Analyze_With_Type_Clause (Item);
-
          --  case of PRAGMA
 
          elsif Nkind (Item) = N_Pragma then
@@ -2869,7 +3067,7 @@ package body Sem_Ch10 is
 
       if Nkind (Lib_Unit) = N_Package_Body
         or else (Nkind (Lib_Unit) = N_Subprogram_Body
-                  and then not Acts_As_Spec (N))
+                   and then not Acts_As_Spec (N))
       then
          Install_Context (Library_Unit (N));
 
@@ -2884,16 +3082,19 @@ package body Sem_Ch10 is
             --  context clause of the body are directly visible.
 
             declare
-               Lib_Spec : Node_Id := Unit (Library_Unit (N));
+               Lib_Spec : Node_Id;
                P        : Node_Id;
                P_Name   : Entity_Id;
 
             begin
+               Lib_Spec := Unit (Library_Unit (N));
                while Is_Child_Spec (Lib_Spec) loop
-                  P := Unit (Parent_Spec (Lib_Spec));
+                  P      := Unit (Parent_Spec (Lib_Spec));
+                  P_Name := Defining_Entity (P);
 
-                  if not (Private_Present (Parent (Lib_Spec))) then
-                     P_Name := Defining_Entity (P);
+                  if not (Private_Present (Parent (Lib_Spec)))
+                    and then not In_Private_Part (P_Name)
+                  then
                      Install_Private_Declarations (P_Name);
                      Install_Private_With_Clauses (P_Name);
                      Set_Use (Private_Declarations (Specification (P)));
@@ -2944,14 +3145,16 @@ package body Sem_Ch10 is
       --  Check that the unlimited view of a given compilation_unit is not
       --  already visible through "use + renamings".
 
-      procedure Check_Private_Limited_Withed_Unit (N : Node_Id);
+      procedure Check_Private_Limited_Withed_Unit (Item : Node_Id);
       --  Check that if a limited_with clause of a given compilation_unit
-      --  mentions a private child of some library unit, then the given
-      --  compilation_unit shall be the declaration of a private descendant
-      --  of that library unit.
+      --  mentions a descendant of a private child of some library unit,
+      --  then the given compilation_unit shall be the declaration of a
+      --  private descendant of that library unit.
 
       procedure Expand_Limited_With_Clause
-        (Comp_Unit : Node_Id; Nam : Node_Id; N : Node_Id);
+        (Comp_Unit : Node_Id;
+         Nam       : Node_Id;
+         N         : Node_Id);
       --  If a child unit appears in a limited_with clause, there are implicit
       --  limited_with clauses on all parents that are not already visible
       --  through a regular with clause. This procedure creates the implicit
@@ -2995,23 +3198,26 @@ package body Sem_Ch10 is
          Item := First (Visible_Declarations (Spec));
          while Present (Item) loop
 
+            --  Look only at use package clauses
+
             if Nkind (Item) = N_Use_Package_Clause then
 
                --  Traverse the list of packages
 
                Nam := First (Names (Item));
-
                while Present (Nam) loop
                   E := Entity (Nam);
 
                   pragma Assert (Present (Parent (E)));
 
-                  if Nkind (Parent (E))
-                    = N_Package_Renaming_Declaration
+                  if Nkind (Parent (E)) = N_Package_Renaming_Declaration
                     and then Renamed_Entity (E) = WEnt
                   then
-                     Error_Msg_N ("unlimited view visible through "
-                                  & "use_clause + renamings", W);
+                     --  The unlimited view is visible through use clause and
+                     --  renamings. There is not need to generate the error
+                     --  message here because Is_Visible_Through_Renamings
+                     --  takes care of generating the precise error message.
+
                      return;
 
                   elsif Nkind (Parent (E)) = N_Package_Specification then
@@ -3021,20 +3227,20 @@ package body Sem_Ch10 is
 
                      E2 := E;
                      while E2 /= Standard_Standard
-                       and then E2 /= WEnt loop
+                       and then E2 /= WEnt
+                     loop
                         E2 := Scope (E2);
                      end loop;
 
                      if E2 = WEnt then
-                        Error_Msg_N ("unlimited view visible through "
-                                     & "use_clause ", W);
+                        Error_Msg_N
+                          ("unlimited view visible through use clause ", W);
                         return;
                      end if;
-
                   end if;
+
                   Next (Nam);
                end loop;
-
             end if;
 
             Next (Item);
@@ -3051,40 +3257,59 @@ package body Sem_Ch10 is
       -- Check_Private_Limited_Withed_Unit --
       ---------------------------------------
 
-      procedure Check_Private_Limited_Withed_Unit (N : Node_Id) is
-         C     : Node_Id;
-         P     : Node_Id;
-         Found : Boolean := False;
+      procedure Check_Private_Limited_Withed_Unit (Item : Node_Id) is
+         Curr_Parent  : Node_Id;
+         Child_Parent : Node_Id;
 
       begin
-         --  If the current compilation unit is not private we don't
-         --  need to check anything else.
-
-         if not Private_Present (Parent (N)) then
-            Found := False;
+         --  Compilation unit of the parent of the withed library unit
 
-         else
-            --  Compilation unit of the parent of the withed library unit
+         Child_Parent := Parent_Spec (Unit (Library_Unit (Item)));
 
-            P := Parent_Spec (Unit (Library_Unit (N)));
+         --  If the child unit is a public child, then locate its nearest
+         --  private ancestor, if any; Child_Parent will then be set to
+         --  the parent of that ancestor.
 
-            --  Traverse all the ancestors of the current compilation
-            --  unit to check if it is a descendant of named library unit.
+         if not Private_Present (Library_Unit (Item)) then
+            while Present (Child_Parent)
+              and then not Private_Present (Child_Parent)
+            loop
+               Child_Parent := Parent_Spec (Unit (Child_Parent));
+            end loop;
 
-            C := Parent (N);
-            while Present (Parent_Spec (Unit (C))) loop
-               C := Parent_Spec (Unit (C));
+            if No (Child_Parent) then
+               return;
+            end if;
 
-               if C = P then
-                  Found := True;
-                  exit;
-               end if;
-            end loop;
+            Child_Parent := Parent_Spec (Unit (Child_Parent));
          end if;
 
-         if not Found then
-            Error_Msg_N ("current unit is not a private descendant"
-                         & " of the withed unit ('R'M 10.1.2(8)", N);
+         --  Traverse all the ancestors of the current compilation
+         --  unit to check if it is a descendant of named library unit.
+
+         Curr_Parent := Parent (Item);
+         while Present (Parent_Spec (Unit (Curr_Parent)))
+           and then Curr_Parent /= Child_Parent
+         loop
+            Curr_Parent := Parent_Spec (Unit (Curr_Parent));
+         end loop;
+
+         if Curr_Parent /= Child_Parent then
+            Error_Msg_N
+              ("unit in with clause is private child unit!", Item);
+            Error_Msg_NE
+              ("\current unit must also have parent&!",
+               Item, Defining_Unit_Name (Specification (Unit (Child_Parent))));
+
+         elsif not Private_Present (Parent (Item))
+           and then not Private_Present (Item)
+           and then Nkind (Unit (Parent (Item))) /= N_Package_Body
+           and then Nkind (Unit (Parent (Item))) /= N_Subprogram_Body
+           and then Nkind (Unit (Parent (Item))) /= N_Subunit
+         then
+            Error_Msg_NE
+              ("current unit must also be private descendant of&",
+               Item, Defining_Unit_Name (Specification (Unit (Child_Parent))));
          end if;
       end Check_Private_Limited_Withed_Unit;
 
@@ -3116,7 +3341,7 @@ package body Sem_Ch10 is
             Item : Node_Id;
 
          begin
-            --  A limited with_clause can not appear in the same context_clause
+            --  A limited with_clause cannot appear in the same context_clause
             --  as a nonlimited with_clause which mentions the same library.
 
             Item := First (Context_Items (Comp_Unit));
@@ -3139,13 +3364,19 @@ package body Sem_Ch10 is
          New_Nodes_OK := New_Nodes_OK + 1;
 
          if Nkind (Nam) = N_Identifier then
-            Withn := Make_With_Clause (Loc, Nam);
+
+            --  Create node for name of withed unit
+
+            Withn :=
+              Make_With_Clause (Loc,
+                Name => New_Copy (Nam));
 
          else pragma Assert (Nkind (Nam) = N_Selected_Component);
-            Withn := Make_With_Clause (Loc,
-                       Make_Selected_Component (Loc,
-                          Prefix        => Prefix (Nam),
-                          Selector_Name => Selector_Name (Nam)));
+            Withn :=
+              Make_With_Clause (Loc,
+                Name => Make_Selected_Component (Loc,
+                  Prefix        => New_Copy_Tree (Prefix (Nam)),
+                  Selector_Name => New_Copy (Selector_Name (Nam))));
             Set_Parent (Withn, Parent (N));
          end if;
 
@@ -3160,31 +3391,32 @@ package body Sem_Ch10 is
               Subunit    => False,
               Error_Node => Nam);
 
-         if not Analyzed (Cunit (Unum)) then
-            --  Do not generate a limited_with_clause on the current unit.
-            --  This path is taken when a unit has a limited_with clause on
-            --  one of its child units.
+         --  Do not generate a limited_with_clause on the current unit.
+         --  This path is taken when a unit has a limited_with clause on
+         --  one of its child units.
 
-            if Unum = Current_Sem_Unit then
-               return;
-            end if;
+         if Unum = Current_Sem_Unit then
+            return;
+         end if;
 
-            Set_Library_Unit (Withn, Cunit (Unum));
-            Set_Corresponding_Spec
-              (Withn, Specification (Unit (Cunit (Unum))));
+         Set_Library_Unit (Withn, Cunit (Unum));
+         Set_Corresponding_Spec
+           (Withn, Specification (Unit (Cunit (Unum))));
 
-            if not Previous_Withed_Unit (Withn) then
-               Prepend (Withn, Context_Items (Parent (N)));
-               Mark_Rewrite_Insertion (Withn);
+         if not Previous_Withed_Unit (Withn) then
+            Prepend (Withn, Context_Items (Parent (N)));
+            Mark_Rewrite_Insertion (Withn);
 
-               --  Add implicit limited_with_clauses for parents of child units
-               --  mentioned in limited_with clauses
+            --  Add implicit limited_with_clauses for parents of child units
+            --  mentioned in limited_with clauses.
 
-               if Nkind (Nam) = N_Selected_Component then
-                  Expand_Limited_With_Clause (Comp_Unit, Prefix (Nam), N);
-               end if;
+            if Nkind (Nam) = N_Selected_Component then
+               Expand_Limited_With_Clause (Comp_Unit, Prefix (Nam), N);
+            end if;
 
-               Analyze (Withn);
+            Analyze (Withn);
+
+            if not Limited_View_Installed (Withn) then
                Install_Limited_Withed_Unit (Withn);
             end if;
          end if;
@@ -3205,9 +3437,7 @@ package body Sem_Ch10 is
                  (Comp_Unit => N, Nam => Prefix (Name (Item)), N => Item);
             end if;
 
-            if Private_Present (Library_Unit (Item)) then
-               Check_Private_Limited_Withed_Unit (Item);
-            end if;
+            Check_Private_Limited_Withed_Unit (Item);
 
             if not Implicit_With (Item)
               and then Is_Child_Spec (Unit (N))
@@ -3215,18 +3445,96 @@ package body Sem_Ch10 is
                Check_Renamings (Parent_Spec (Unit (N)), Item);
             end if;
 
-            --  A unit may have a limited with on itself if it has a
-            --  limited with_clause on one of its child units. In that
-            --  case it is already being compiled and it makes no sense
-            --  to install its limited view.
+            --  A unit may have a limited with on itself if it has a limited
+            --  with_clause on one of its child units. In that case it is
+            --  already being compiled and it makes no sense to install its
+            --  limited view.
+
+            --  If the item is a limited_private_with_clause, install it if the
+            --  current unit is a body or if it is a private child. Otherwise
+            --  the private clause is installed before analyzing the private
+            --  part of the current unit.
 
-            if Library_Unit (Item) /= Cunit (Current_Sem_Unit) then
-               Install_Limited_Withed_Unit (Item);
+            if Library_Unit (Item) /= Cunit (Current_Sem_Unit)
+              and then not Limited_View_Installed (Item)
+            then
+               if not Private_Present (Item)
+                 or else Private_Present (N)
+                 or else Nkind (Unit (N)) = N_Package_Body
+                 or else Nkind (Unit (N)) = N_Subprogram_Body
+                 or else Nkind (Unit (N)) = N_Subunit
+               then
+                  Install_Limited_Withed_Unit (Item);
+               end if;
             end if;
+
+         --  All items other than Limited_With clauses are ignored (they were
+         --  installed separately early on by Install_Context_Clause).
+
+         else
+            null;
          end if;
 
          Next (Item);
       end loop;
+
+      --  Ada 2005 (AI-412): Examine the visible declarations of a package
+      --  spec, looking for incomplete subtype declarations of incomplete
+      --  types visible through a limited with clause.
+
+      if Ada_Version >= Ada_05
+        and then Analyzed (N)
+        and then Nkind (Unit (N)) = N_Package_Declaration
+      then
+         declare
+            Decl         : Node_Id;
+            Def_Id       : Entity_Id;
+            Non_Lim_View : Entity_Id;
+
+         begin
+            Decl := First (Visible_Declarations (Specification (Unit (N))));
+            while Present (Decl) loop
+               if Nkind (Decl) = N_Subtype_Declaration
+                 and then
+                   Ekind (Defining_Identifier (Decl)) = E_Incomplete_Subtype
+                 and then
+                   From_With_Type (Defining_Identifier (Decl))
+               then
+                  Def_Id := Defining_Identifier (Decl);
+                  Non_Lim_View := Non_Limited_View (Def_Id);
+
+                  if not Is_Incomplete_Type (Non_Lim_View) then
+
+                     --  Convert an incomplete subtype declaration into a
+                     --  corresponding non-limited view subtype declaration.
+                     --  This is usually the case when analyzing a body that
+                     --  has regular with-clauses, when the spec has limited
+                     --  ones.
+
+                     --  If the non-limited view is still incomplete, it is
+                     --  the dummy entry already created, and the declaration
+                     --  cannot be reanalyzed. This is the case when installing
+                     --  a parent unit that has limited with-clauses.
+
+                     Set_Subtype_Indication (Decl,
+                       New_Reference_To (Non_Lim_View, Sloc (Def_Id)));
+                     Set_Etype (Def_Id, Non_Lim_View);
+                     Set_Ekind (Def_Id, Subtype_Kind (Ekind (Non_Lim_View)));
+                     Set_Analyzed (Decl, False);
+
+                     --  Reanalyze the declaration, suppressing the call to
+                     --  Enter_Name to avoid duplicate names.
+
+                     Analyze_Subtype_Declaration
+                      (N    => Decl,
+                       Skip => True);
+                  end if;
+               end if;
+
+               Next (Decl);
+            end loop;
+         end;
+      end if;
    end Install_Limited_Context_Clauses;
 
    ---------------------
@@ -3255,7 +3563,7 @@ package body Sem_Ch10 is
          Error_Msg_N
            ("child of a generic package must be a generic unit", Lib_Unit);
 
-      elsif not Is_Package (P_Name) then
+      elsif not Is_Package_Or_Generic_Package (P_Name) then
          Error_Msg_N
            ("parent unit must be package or generic package", Lib_Unit);
          raise Unrecoverable_Error;
@@ -3264,12 +3572,12 @@ package body Sem_Ch10 is
          Error_Msg_N ("parent unit cannot be a renaming", Lib_Unit);
          raise Unrecoverable_Error;
 
-      --  Verify that a child of an instance is itself an instance, or
-      --  the renaming of one. Given that an instance that is a unit is
-      --  replaced with a package declaration, check against the original
-      --  node. The parent may be currently being instantiated, in which
-      --  case it appears as a declaration, but the generic_parent is
-      --  already established indicating that we deal with an instance.
+      --  Verify that a child of an instance is itself an instance, or the
+      --  renaming of one. Given that an instance that is a unit is replaced
+      --  with a package declaration, check against the original node. The
+      --  parent may be currently being instantiated, in which case it appears
+      --  as a declaration, but the generic_parent is already established
+      --  indicating that we deal with an instance.
 
       elsif Nkind (Original_Node (P)) = N_Package_Instantiation then
 
@@ -3277,7 +3585,7 @@ package body Sem_Ch10 is
            or else Nkind (Original_Node (Lib_Unit)) in N_Generic_Instantiation
            or else
              (Nkind (Lib_Unit) = N_Package_Declaration
-               and then Present (Generic_Parent (Specification (Lib_Unit))))
+                and then Present (Generic_Parent (Specification (Lib_Unit))))
          then
             null;
          else
@@ -3297,15 +3605,16 @@ package body Sem_Ch10 is
       --  Now we can install the context for this parent
 
       Install_Context_Clauses (Parent_Spec (Lib_Unit));
+      Install_Limited_Context_Clauses (Parent_Spec (Lib_Unit));
       Install_Siblings (P_Name, Parent (Lib_Unit));
 
-      --  The child unit is in the declarative region of the parent. The
-      --  parent must therefore appear in the scope stack and be visible,
-      --  as when compiling the corresponding body. If the child unit is
-      --  private or it is a package body, private declarations must be
-      --  accessible as well. Use declarations in the parent must also
-      --  be installed. Finally, other child units of the same parent that
-      --  are in the context are immediately visible.
+      --  The child unit is in the declarative region of the parent. The parent
+      --  must therefore appear in the scope stack and be visible, as when
+      --  compiling the corresponding body. If the child unit is private or it
+      --  is a package body, private declarations must be accessible as well.
+      --  Use declarations in the parent must also be installed. Finally, other
+      --  child units of the same parent that are in the context are
+      --  immediately visible.
 
       --  Find entity for compilation unit, and set its private descendant
       --  status as needed.
@@ -3319,7 +3628,7 @@ package body Sem_Ch10 is
            or else Private_Present (Parent (Lib_Unit)));
 
       P_Spec := Specification (Unit_Declaration_Node (P_Name));
-      New_Scope (P_Name);
+      Push_Scope (P_Name);
 
       --  Save current visibility of unit
 
@@ -3329,8 +3638,8 @@ package body Sem_Ch10 is
       Install_Visible_Declarations (P_Name);
       Set_Use (Visible_Declarations (P_Spec));
 
-      --  If the parent is a generic unit, its formal part may contain
-      --  formal packages and use clauses for them.
+      --  If the parent is a generic unit, its formal part may contain formal
+      --  packages and use clauses for them.
 
       if Ekind (P_Name) = E_Generic_Package then
          Set_Use (Generic_Formal_Declarations (Parent (P_Spec)));
@@ -3362,13 +3671,14 @@ package body Sem_Ch10 is
 
       if Nkind (Parent (Decl)) = N_Compilation_Unit then
          Item := First (Context_Items (Parent (Decl)));
-
          while Present (Item) loop
             if Nkind (Item) = N_With_Clause
               and then Private_Present (Item)
             then
                if Limited_Present (Item) then
-                  Install_Limited_Withed_Unit (Item);
+                  if not Limited_View_Installed (Item) then
+                     Install_Limited_Withed_Unit (Item);
+                  end if;
                else
                   Install_Withed_Unit (Item, Private_With_OK => True);
                end if;
@@ -3388,22 +3698,23 @@ package body Sem_Ch10 is
       Id   : Entity_Id;
       Prev : Entity_Id;
    begin
-      --  Iterate over explicit with clauses, and check whether the
-      --  scope of each entity is an ancestor of the current unit.
+      --  Iterate over explicit with clauses, and check whether the scope of
+      --  each entity is an ancestor of the current unit, in which case it is
+      --  immediately visible.
 
       Item := First (Context_Items (N));
+      while Present (Item) loop
 
-      --  Do not install private_with_clauses if the unit is a package
-      --  declaration, unless it is itself a private child unit.
+         --  Do not install private_with_clauses if the unit is a package
+         --  declaration, unless it is itself a private child unit.
 
-      while Present (Item) loop
          if Nkind (Item) = N_With_Clause
            and then not Implicit_With (Item)
            and then not Limited_Present (Item)
            and then
               (not Private_Present (Item)
-                or else Nkind (Unit (N)) /= N_Package_Declaration
-                or else Private_Present (N))
+                 or else Nkind (Unit (N)) /= N_Package_Declaration
+                 or else Private_Present (N))
          then
             Id := Entity (Name (Item));
 
@@ -3426,7 +3737,6 @@ package body Sem_Ch10 is
 
                   begin
                      Clause := First (Context_Items (N));
-
                      while Present (Clause) loop
                         if Nkind (Clause) = N_With_Clause
                           and then Entity (Name (Clause)) = Prev
@@ -3443,13 +3753,27 @@ package body Sem_Ch10 is
                   end;
                end if;
 
-            --  the With_Clause may be on a grand-child, which makes
-            --  the child immediately visible.
+            --  The With_Clause may be on a grand-child or one of its further
+            --  descendants, which makes a child immediately visible. Examine
+            --  ancestry to determine whether such a child exists. For example,
+            --  if current unit is A.C, and with_clause is on A.X.Y.Z, then X
+            --  is immediately visible.
 
-            elsif Is_Child_Unit (Scope (Id))
-              and then Is_Ancestor_Package (Scope (Scope (Id)), U_Name)
-            then
-               Set_Is_Immediately_Visible (Scope (Id));
+            elsif Is_Child_Unit (Id) then
+               declare
+                  Par : Entity_Id;
+
+               begin
+                  Par := Scope (Id);
+                  while Is_Child_Unit (Par) loop
+                     if Is_Ancestor_Package (Scope (Par), U_Name) then
+                        Set_Is_Immediately_Visible (Par);
+                        exit;
+                     end if;
+
+                     Par := Scope (Par);
+                  end loop;
+               end;
             end if;
          end if;
 
@@ -3462,48 +3786,125 @@ package body Sem_Ch10 is
    -------------------------------
 
    procedure Install_Limited_Withed_Unit (N : Node_Id) is
-      Unum             : constant Unit_Number_Type :=
-                           Get_Source_Unit (Library_Unit (N));
       P_Unit           : constant Entity_Id := Unit (Library_Unit (N));
+      E                : Entity_Id;
       P                : Entity_Id;
       Is_Child_Package : Boolean := False;
-
       Lim_Header       : Entity_Id;
       Lim_Typ          : Entity_Id;
 
-      function In_Chain (E : Entity_Id) return Boolean;
-      --  Check that the shadow entity is not already in the homonym
-      --  chain, for example through a limited_with clause in a parent unit.
+      function Has_Limited_With_Clause
+        (C_Unit : Entity_Id;
+         Pack   : Entity_Id) return Boolean;
+      --  Determine whether any package in the ancestor chain starting with
+      --  C_Unit has a limited with clause for package Pack.
+
+      function Has_With_Clause
+        (C_Unit     : Node_Id;
+         Pack       : Entity_Id;
+         Is_Limited : Boolean := False) return Boolean;
+      --  Determine whether compilation unit C_Unit contains a with clause
+      --  for package Pack. Use flag Is_Limited to designate desired clause
+      --  kind. This is a subsidiary routine to Has_Limited_With_Clause.
 
       function Is_Visible_Through_Renamings (P : Entity_Id) return Boolean;
       --  Check if some package installed though normal with-clauses has a
       --  renaming declaration of package P. AARM 10.1.2(21/2).
 
-      --------------
-      -- In_Chain --
-      --------------
+      -----------------------------
+      -- Has_Limited_With_Clause --
+      -----------------------------
+
+      function Has_Limited_With_Clause
+        (C_Unit : Entity_Id;
+         Pack   : Entity_Id) return Boolean
+      is
+         Par      : Entity_Id;
+         Par_Unit : Node_Id;
+
+      begin
+         Par := C_Unit;
+         while Present (Par) loop
+            if Ekind (Par) /= E_Package then
+               exit;
+            end if;
+
+            --  Retrieve the Compilation_Unit node for Par and determine if
+            --  its context clauses contain a limited with for Pack.
+
+            Par_Unit := Parent (Parent (Parent (Par)));
+
+            if Nkind (Par_Unit) = N_Package_Declaration then
+               Par_Unit := Parent (Par_Unit);
+            end if;
+
+            if Has_With_Clause (Par_Unit, Pack, True) then
+               return True;
+            end if;
+
+            --  If there are more ancestors, climb up the tree, otherwise
+            --  we are done.
+
+            if Is_Child_Unit (Par) then
+               Par := Scope (Par);
+            else
+               exit;
+            end if;
+         end loop;
+
+         return False;
+      end Has_Limited_With_Clause;
+
+      ---------------------
+      -- Has_With_Clause --
+      ---------------------
+
+      function Has_With_Clause
+        (C_Unit     : Node_Id;
+         Pack       : Entity_Id;
+         Is_Limited : Boolean := False) return Boolean
+      is
+         Item : Node_Id;
+         Nam  : Entity_Id;
+
+      begin
+         if Present (Context_Items (C_Unit)) then
+            Item := First (Context_Items (C_Unit));
+            while Present (Item) loop
+               if Nkind (Item) = N_With_Clause then
+
+                  --  Retrieve the entity of the imported compilation unit
+
+                  if Nkind (Name (Item)) = N_Selected_Component then
+                     Nam := Entity (Selector_Name (Name (Item)));
+                  else
+                     Nam := Entity (Name (Item));
+                  end if;
 
-      function In_Chain (E : Entity_Id) return Boolean is
-         H : Entity_Id := Current_Entity (E);
+                  if Nam = Pack
+                    and then
+                      ((Is_Limited and then Limited_Present (Item))
+                          or else
+                       (not Is_Limited and then not Limited_Present (Item)))
+                  then
+                     return True;
+                  end if;
+               end if;
 
-      begin
-         while Present (H) loop
-            if H = E then
-               return True;
-            else
-               H := Homonym (H);
-            end if;
-         end loop;
+               Next (Item);
+            end loop;
+         end if;
 
          return False;
-      end In_Chain;
+      end Has_With_Clause;
 
       ----------------------------------
       -- Is_Visible_Through_Renamings --
       ----------------------------------
 
       function Is_Visible_Through_Renamings (P : Entity_Id) return Boolean is
-         Kind : constant Node_Kind := Nkind (Unit (Cunit (Current_Sem_Unit)));
+         Kind     : constant Node_Kind :=
+                      Nkind (Unit (Cunit (Current_Sem_Unit)));
          Aux_Unit : Node_Id;
          Item     : Node_Id;
          Decl     : Entity_Id;
@@ -3527,6 +3928,7 @@ package body Sem_Ch10 is
          --  package R.C is ...
 
          Aux_Unit := Cunit (Current_Sem_Unit);
+
          loop
             Item := First (Context_Items (Aux_Unit));
             while Present (Item) loop
@@ -3549,19 +3951,15 @@ package body Sem_Ch10 is
                         --  installed.
 
                         if Kind = N_Package_Declaration then
+                           Error_Msg_N
+                             ("simultaneous visibility of the limited and " &
+                              "unlimited views not allowed", N);
                            Error_Msg_Sloc := Sloc (Item);
                            Error_Msg_NE
-                             ("unlimited view of & visible through the context"
-                              & " clause found #", N, P);
-
+                             ("\\  unlimited view of & visible through the " &
+                              "context clause #", N, P);
                            Error_Msg_Sloc := Sloc (Decl);
-                           Error_Msg_NE
-                             ("unlimited view of & visible through the"
-                              & " renaming found #", N, P);
-
-                           Error_Msg_N
-                             ("simultaneous visibility of the limited and"
-                              & " unlimited views not allowed", N);
+                           Error_Msg_NE ("\\  and the renaming #", N, P);
                         end if;
 
                         return True;
@@ -3575,12 +3973,21 @@ package body Sem_Ch10 is
             end loop;
 
             if Present (Library_Unit (Aux_Unit)) then
-               Aux_Unit := Library_Unit (Aux_Unit);
+               if Aux_Unit = Library_Unit (Aux_Unit) then
+
+                  --  Aux_Unit is a body that acts as a spec. Clause has
+                  --  already been flagged as illegal.
+
+                  return False;
+
+               else
+                  Aux_Unit := Library_Unit (Aux_Unit);
+               end if;
             else
                Aux_Unit := Parent_Spec (Unit (Aux_Unit));
             end if;
 
-            exit when not Present (Aux_Unit);
+            exit when No (Aux_Unit);
          end loop;
 
          return False;
@@ -3589,6 +3996,8 @@ package body Sem_Ch10 is
    --  Start of processing for Install_Limited_Withed_Unit
 
    begin
+      pragma Assert (not Limited_View_Installed (N));
+
       --  In case of limited with_clause on subprograms, generics, instances,
       --  or renamings, the corresponding error was previously posted and we
       --  have nothing to do here.
@@ -3599,21 +4008,68 @@ package body Sem_Ch10 is
 
       P := Defining_Unit_Name (Specification (P_Unit));
 
-      if Nkind (P) = N_Defining_Program_Unit_Name then
-
-         --  Retrieve entity of child package
+      --  Handle child packages
 
+      if Nkind (P) = N_Defining_Program_Unit_Name then
          Is_Child_Package := True;
          P := Defining_Identifier (P);
       end if;
 
       --  Do not install the limited-view if the full-view is already visible
-      --  through some renaming declaration
+      --  through renaming declarations.
 
       if Is_Visible_Through_Renamings (P) then
          return;
       end if;
 
+      --  Do not install the limited view if this is the unit being analyzed.
+      --  This unusual case will happen when a unit has a limited_with clause
+      --  on one of its children. The compilation of the child forces the
+      --  load of the parent which tries to install the limited view of the
+      --  child again. Installing the limited view must also be disabled
+      --  when compiling the body of the child unit.
+
+      if P = Cunit_Entity (Current_Sem_Unit)
+        or else
+         (Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Body
+            and then P = Main_Unit_Entity)
+      then
+         return;
+      end if;
+
+      --  This scenario is similar to the one above, the difference is that
+      --  the compilation of sibling Par.Sib forces the load of parent Par
+      --  which tries to install the limited view of Lim_Pack [1]. However
+      --  Par.Sib has a with clause for Lim_Pack [2] in its body, and thus
+      --  needs the non-limited views of all entities from Lim_Pack.
+
+      --     limited with Lim_Pack;   --  [1]
+      --     package Par is ...           package Lim_Pack is ...
+
+      --                                  with Lim_Pack;  --  [2]
+      --     package Par.Sib is ...       package body Par.Sib is ...
+
+      --  In this case Main_Unit_Entity is the spec of Par.Sib and Current_
+      --  Sem_Unit is the body of Par.Sib.
+
+      if Ekind (P) = E_Package
+        and then Ekind (Main_Unit_Entity) = E_Package
+        and then Is_Child_Unit (Main_Unit_Entity)
+
+         --  The body has a regular with clause
+
+        and then Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Body
+        and then Has_With_Clause (Cunit (Current_Sem_Unit), P)
+
+         --  One of the ancestors has a limited with clause
+
+        and then Nkind (Parent (Parent (Main_Unit_Entity))) =
+                   N_Package_Specification
+        and then Has_Limited_With_Clause (Scope (Main_Unit_Entity), P)
+      then
+         return;
+      end if;
+
       --  A common use of the limited-with is to have a limited-with
       --  in the package spec, and a normal with in its package body.
       --  For example:
@@ -3624,19 +4080,17 @@ package body Sem_Ch10 is
       --       with X;          -- [2]
       --       package body A is ...
 
-      --  The compilation of A's body installs the entities of its
-      --  withed packages (the context clauses found at [2]) and
-      --  then the context clauses of its specification (found at [1]).
-
-      --  As a consequence, at point [1] the specification of X has been
-      --  analyzed and it is immediately visible. According to the semantics
-      --  of the limited-with context clauses we don't install the limited
-      --  view because the full view of X supersedes its limited view.
+      --  The compilation of A's body installs the context clauses found at [2]
+      --  and then the context clauses of its specification (found at [1]). As
+      --  a consequence, at [1] the specification of X has been analyzed and it
+      --  is immediately visible. According to the semantics of limited-with
+      --  context clauses we don't install the limited view because the full
+      --  view of X supersedes its limited view.
 
-      if Analyzed (Cunit (Unum))
+      if Analyzed (P_Unit)
         and then (Is_Immediately_Visible (P)
-                   or else (Is_Child_Package
-                             and then Is_Visible_Child_Unit (P)))
+                    or else (Is_Child_Package
+                               and then Is_Visible_Child_Unit (P)))
       then
          --  Ada 2005 (AI-262): Install the private declarations of P
 
@@ -3645,9 +4099,9 @@ package body Sem_Ch10 is
          then
             declare
                Id : Entity_Id;
+
             begin
                Id := First_Private_Entity (P);
-
                while Present (Id) loop
                   if not Is_Internal (Id)
                     and then not Is_Child_Unit (Id)
@@ -3676,14 +4130,26 @@ package body Sem_Ch10 is
          Write_Eol;
       end if;
 
-      if not Analyzed (Cunit (Unum)) then
-         Set_Ekind (P, E_Package);
-         Set_Etype (P, Standard_Void_Type);
-         Set_Scope (P, Standard_Standard);
+      --  If the unit has not been analyzed and the limited view has not been
+      --  already installed then we install it.
 
-         --  Place entity on visibility structure
+      if not Analyzed (P_Unit) then
+         if not In_Chain (P) then
+
+            --  Minimum decoration
+
+            Set_Ekind (P, E_Package);
+            Set_Etype (P, Standard_Void_Type);
+            Set_Scope (P, Standard_Standard);
+
+            if Is_Child_Package then
+               Set_Is_Child_Unit (P);
+               Set_Is_Visible_Child_Unit (P);
+               Set_Scope (P, Defining_Entity (Unit (Parent_Spec (P_Unit))));
+            end if;
+
+            --  Place entity on visibility structure
 
-         if Current_Entity (P) /= P then
             Set_Homonym (P, Current_Entity (P));
             Set_Current_Entity (P);
 
@@ -3693,76 +4159,163 @@ package body Sem_Ch10 is
                Write_Eol;
             end if;
 
-         end if;
+            --  Install the incomplete view. The first element of the limited
+            --  view is a header (an E_Package entity) used to reference the
+            --  first shadow entity in the private part of the package.
 
-         if Is_Child_Package then
-            Set_Is_Child_Unit (P);
-            Set_Is_Visible_Child_Unit (P);
+            Lim_Header := Limited_View (P);
+            Lim_Typ    := First_Entity (Lim_Header);
 
-            declare
-               Parent_Comp : Node_Id;
-               Parent_Id   : Entity_Id;
+            while Present (Lim_Typ)
+              and then Lim_Typ /= First_Private_Entity (Lim_Header)
+            loop
+               Set_Homonym (Lim_Typ, Current_Entity (Lim_Typ));
+               Set_Current_Entity (Lim_Typ);
 
-            begin
-               Parent_Comp := Parent_Spec (Unit (Cunit (Unum)));
-               Parent_Id   := Defining_Entity (Unit (Parent_Comp));
+               if Debug_Flag_I then
+                  Write_Str ("   (homonym) chain ");
+                  Write_Name (Chars (Lim_Typ));
+                  Write_Eol;
+               end if;
 
-               Set_Scope (P, Parent_Id);
-            end;
+               Next_Entity (Lim_Typ);
+            end loop;
          end if;
+
+      --  If the unit appears in a previous regular with_clause, the regular
+      --  entities of the public part of the withed package must be replaced
+      --  by the shadow ones.
+
+      --  This code must be kept synchronized with the code that replaces the
+      --  shadow entities by the real entities (see body of Remove_Limited
+      --  With_Clause); otherwise the contents of the homonym chains are not
+      --  consistent.
+
       else
+         --  Hide all the type entities of the public part of the package to
+         --  avoid its usage. This is needed to cover all the subtype decla-
+         --  rations because we do not remove them from the homonym chain.
+
+         E := First_Entity (P);
+         while Present (E) and then E /= First_Private_Entity (P) loop
+            if Is_Type (E) then
+               Set_Was_Hidden (E, Is_Hidden (E));
+               Set_Is_Hidden (E);
+            end if;
 
-         --  If the unit appears in a previous regular with_clause, the
-         --  regular entities must be unchained before the shadow ones
-         --  are made accessible.
+            Next_Entity (E);
+         end loop;
 
-         declare
-            Ent : Entity_Id;
-         begin
-            Ent := First_Entity (P);
+         --  Replace the real entities by the shadow entities of the limited
+         --  view. The first element of the limited view is a header that is
+         --  used to reference the first shadow entity in the private part
+         --  of the package. Successive elements are the limited views of the
+         --  type (including regular incomplete types) declared in the package.
 
-            while Present (Ent) loop
-               Unchain (Ent);
-               Next_Entity (Ent);
-            end loop;
-         end;
+         Lim_Header := Limited_View (P);
+
+         Lim_Typ := First_Entity (Lim_Header);
+         while Present (Lim_Typ)
+           and then Lim_Typ /= First_Private_Entity (Lim_Header)
+         loop
+            pragma Assert (not In_Chain (Lim_Typ));
+
+            --  Do not unchain nested packages and child units
+
+            if Ekind (Lim_Typ) /= E_Package
+              and then not Is_Child_Unit (Lim_Typ)
+            then
+               declare
+                  Prev : Entity_Id;
+
+               begin
+                  Prev := Current_Entity (Lim_Typ);
+                  E := Prev;
+
+                  --  Replace E in the homonyms list, so that the limited
+                  --  view becomes available.
+
+                  if E = Non_Limited_View (Lim_Typ) then
+                     Set_Homonym (Lim_Typ, Homonym (Prev));
+                     Set_Current_Entity (Lim_Typ);
+
+                  else
+                     loop
+                        E := Homonym (Prev);
+
+                        --  E may have been removed when installing a
+                        --  previous limited_with_clause.
+
+                        exit when No (E);
+
+                        exit when E = Non_Limited_View (Lim_Typ);
+
+                        Prev := Homonym (Prev);
+                     end loop;
+
+                     if Present (E) then
+                        Set_Homonym (Lim_Typ, Homonym (Homonym (Prev)));
+                        Set_Homonym (Prev, Lim_Typ);
+                     end if;
+                  end if;
+               end;
+
+               if Debug_Flag_I then
+                  Write_Str ("   (homonym) chain ");
+                  Write_Name (Chars (Lim_Typ));
+                  Write_Eol;
+               end if;
+            end if;
+
+            Next_Entity (Lim_Typ);
+         end loop;
       end if;
 
-      --  The package must be visible while the limited-with clause is active,
+      --  The package must be visible while the limited-with clause is active
       --  because references to the type P.T must resolve in the usual way.
+      --  In addition, we remember that the limited-view has been installed to
+      --  uninstall it at the point of context removal.
 
       Set_Is_Immediately_Visible (P);
+      Set_Limited_View_Installed (N);
 
-      --  Install each incomplete view. The first element of the limited view
-      --  is a header (an E_Package entity) that is used to reference the first
-      --  shadow entity in the private part of the package
+      --  If the package in the limited_with clause is a child unit, the
+      --  clause is unanalyzed and appears as a selected component. Recast
+      --  it as an expanded name so that the entity can be properly set. Use
+      --  entity of parent, if available, for higher ancestors in the name.
 
-      Lim_Header := Limited_View (P);
-      Lim_Typ    := First_Entity (Lim_Header);
+      if Nkind (Name (N)) = N_Selected_Component then
+         declare
+            Nam : Node_Id;
+            Ent : Entity_Id;
 
-      while Present (Lim_Typ) loop
+         begin
+            Nam := Name (N);
+            Ent := P;
+            while Nkind (Nam) = N_Selected_Component
+              and then Present (Ent)
+            loop
+               Change_Selected_Component_To_Expanded_Name (Nam);
 
-         exit when not Private_Present (N)
-                        and then Lim_Typ = First_Private_Entity (Lim_Header);
+               --  Set entity of parent identifiers if the unit is a child
+               --  unit. This ensures that the tree is properly formed from
+               --  semantic point of view (e.g. for ASIS queries).
 
-         if not In_Chain (Lim_Typ) then
-            Set_Homonym (Lim_Typ, Current_Entity (Lim_Typ));
-            Set_Current_Entity (Lim_Typ);
+               Set_Entity (Nam, Ent);
 
-            if Debug_Flag_I then
-               Write_Str ("   (homonym) chain ");
-               Write_Name (Chars (Lim_Typ));
-               Write_Eol;
-            end if;
-         end if;
+               Nam := Prefix (Nam);
+               Ent := Scope (Ent);
 
-         Next_Entity (Lim_Typ);
-      end loop;
+               --  Set entity of last ancestor
 
-      --  The context clause has installed a limited-view, mark it
-      --  accordingly, to uninstall it when the context is removed.
+               if Nkind (Nam) = N_Identifier then
+                  Set_Entity (Nam, Ent);
+               end if;
+            end loop;
+         end;
+      end if;
 
-      Set_Limited_View_Installed (N);
+      Set_Entity (Name (N), P);
       Set_From_With_Type (P);
    end Install_Limited_Withed_Unit;
 
@@ -3815,10 +4368,10 @@ package body Sem_Ch10 is
 
       if P /= Standard_Standard then
 
-         --  If the unit is not analyzed after analysis of the with clause,
-         --  and it is an instantiation, then it awaits a body and is the main
-         --  unit. Its appearance in the context of some other unit indicates
-         --  circular dependency (DEC suite perversity).
+         --  If the unit is not analyzed after analysis of the with clause and
+         --  it is an instantiation then it awaits a body and is the main unit.
+         --  Its appearance in the context of some other unit indicates a
+         --  circular dependency (DEC suite perversity).
 
          if not Analyzed (Uname)
            and then Nkind (Parent (Uname)) = N_Package_Instantiation
@@ -3829,8 +4382,8 @@ package body Sem_Ch10 is
          elsif not Is_Visible_Child_Unit (Uname) then
             Set_Is_Visible_Child_Unit (Uname);
 
-            --  If the child unit appears in the context of its parent, it
-            --  is immediately visible.
+            --  If the child unit appears in the context of its parent, it is
+            --  immediately visible.
 
             if In_Open_Scopes (Scope (Uname)) then
                Set_Is_Immediately_Visible (Uname);
@@ -3847,8 +4400,8 @@ package body Sem_Ch10 is
                    (Defining_Entity (Unit (Library_Unit (With_Clause)))));
             end if;
 
-            --  The parent unit may have been installed already, and
-            --  may have appeared in a use clause.
+            --  The parent unit may have been installed already, and may have
+            --  appeared in a use clause.
 
             if In_Use (Scope (Uname)) then
                Set_Is_Potentially_Use_Visible (Uname);
@@ -3896,7 +4449,7 @@ package body Sem_Ch10 is
          begin
             U2 := Homonym (Uname);
             while Present (U2)
-              and U2 /= Standard_Standard
+              and then U2 /= Standard_Standard
            loop
                P2 := Scope (U2);
                Decl2  := Unit_Declaration_Node (P2);
@@ -3911,7 +4464,7 @@ package body Sem_Ch10 is
                      Error_Msg_N ("illegal with_clause", With_Clause);
                      Error_Msg_N
                        ("\child unit has visible homograph" &
-                           " ('R'M 8.3(26), 10.1.1(19))",
+                           " (RM 8.3(26), 10.1.1(19))",
                          With_Clause);
                      exit;
 
@@ -3936,7 +4489,7 @@ package body Sem_Ch10 is
                         Error_Msg_N ("illegal with_clause", Prev_Clause);
                         Error_Msg_N
                           ("\child unit has visible homograph" &
-                              " ('R'M 8.3(26), 10.1.1(19))",
+                              " (RM 8.3(26), 10.1.1(19))",
                             Prev_Clause);
                         exit;
                      end;
@@ -3971,15 +4524,14 @@ package body Sem_Ch10 is
    -- Load_Needed_Body --
    -----------------------
 
-   --  N is a generic unit named in a with clause, or else it is
-   --  a unit that contains a generic unit or an inlined function.
-   --  In order to perform an instantiation, the body of the unit
-   --  must be present. If the unit itself is generic, we assume
-   --  that an instantiation follows, and  load and analyze the body
-   --  unconditionally. This forces analysis of the spec as well.
+   --  N is a generic unit named in a with clause, or else it is a unit that
+   --  contains a generic unit or an inlined function. In order to perform an
+   --  instantiation, the body of the unit must be present. If the unit itself
+   --  is generic, we assume that an instantiation follows, and load & analyze
+   --  the body unconditionally. This forces analysis of the spec as well.
 
-   --  If the unit is not generic, but contains a generic unit, it
-   --  is loaded on demand, at the point of instantiation (see ch12).
+   --  If the unit is not generic, but contains a generic unit, it is loaded on
+   --  demand, at the point of instantiation (see ch12).
 
    procedure Load_Needed_Body (N : Node_Id; OK : out Boolean) is
       Body_Name : Unit_Name_Type;
@@ -4105,6 +4657,9 @@ package body Sem_Ch10 is
 
          --  Build corresponding class_wide type, if not previously done
 
+         --  Warning: The class-wide entity is shared by the limited-view
+         --  and the full-view.
+
          if No (Class_Wide_Type (T)) then
             CW := Make_Defining_Identifier (Loc,  New_Internal_Name ('S'));
 
@@ -4135,9 +4690,9 @@ package body Sem_Ch10 is
          Set_Etype (P, Standard_Void_Type);
       end Decorate_Package_Specification;
 
-      -------------------------
-      -- New_Internal_Entity --
-      -------------------------
+      --------------------------------
+      -- New_Internal_Shadow_Entity --
+      --------------------------------
 
       function New_Internal_Shadow_Entity
         (Kind       : Entity_Kind;
@@ -4175,27 +4730,35 @@ package body Sem_Ch10 is
 
       begin
          Decl := First_Decl;
-
          while Present (Decl) loop
 
             --  For each library_package_declaration in the environment, there
             --  is an implicit declaration of a *limited view* of that library
             --  package. The limited view of a package contains:
-            --
+
             --   * For each nested package_declaration, a declaration of the
             --     limited view of that package, with the same defining-
             --     program-unit name.
-            --
+
             --   * For each type_declaration in the visible part, an incomplete
             --     type-declaration with the same defining_identifier, whose
             --     completion is the type_declaration. If the type_declaration
             --     is tagged, then the incomplete_type_declaration is tagged
             --     incomplete.
 
+            --     The partial view is tagged if the declaration has the
+            --     explicit keyword, or else if it is a type extension, both
+            --     of which can be ascertained syntactically.
+
             if Nkind (Decl) = N_Full_Type_Declaration then
                Is_Tagged :=
-                  Nkind (Type_Definition (Decl)) = N_Record_Definition
-                  and then Tagged_Present (Type_Definition (Decl));
+                  (Nkind (Type_Definition (Decl)) = N_Record_Definition
+                    and then Tagged_Present (Type_Definition (Decl)))
+                 or else
+                   (Nkind (Type_Definition (Decl)) = N_Derived_Type_Definition
+                     and then
+                       Present
+                         (Record_Extension_Part (Type_Definition (Decl))));
 
                Comp_Typ := Defining_Identifier (Decl);
 
@@ -4226,7 +4789,9 @@ package body Sem_Ch10 is
 
                Set_Non_Limited_View (Lim_Typ, Comp_Typ);
 
-            elsif Nkind (Decl) = N_Private_Type_Declaration then
+            elsif Nkind (Decl) = N_Private_Type_Declaration
+              or else Nkind (Decl) = N_Incomplete_Type_Declaration
+            then
                Comp_Typ := Defining_Identifier (Decl);
 
                if not Analyzed_Unit then
@@ -4320,8 +4885,8 @@ package body Sem_Ch10 is
    begin
       pragma Assert (Limited_Present (N));
 
-      --  A library_item mentioned in a limited_with_clause shall be
-      --  a package_declaration, not a subprogram_declaration,
+      --  A library_item mentioned in a limited_with_clause shall
+      --  be a package_declaration, not a subprogram_declaration,
       --  generic_declaration, generic_instantiation, or
       --  package_renaming_declaration
 
@@ -4341,16 +4906,12 @@ package body Sem_Ch10 is
                          & "limited with_clauses", N);
             return;
 
-         when N_Package_Instantiation |
-              N_Function_Instantiation |
-              N_Procedure_Instantiation =>
+         when N_Generic_Instantiation =>
             Error_Msg_N ("generic instantiations not allowed in "
                          & "limited with_clauses", N);
             return;
 
-         when N_Generic_Package_Renaming_Declaration |
-              N_Generic_Procedure_Renaming_Declaration |
-              N_Generic_Function_Renaming_Declaration =>
+         when N_Generic_Renaming_Declaration =>
             Error_Msg_N ("generic renamings not allowed in "
                          & "limited with_clauses", N);
             return;
@@ -4387,8 +4948,8 @@ package body Sem_Ch10 is
       Set_Is_Internal (Lim_Header);
       Set_Limited_View (P, Lim_Header);
 
-      --  Create the auxiliary chain. All the shadow entities are appended
-      --  to the list of entities of the limited-view header
+      --  Create the auxiliary chain. All the shadow entities are appended to
+      --  the list of entities of the limited-view header
 
       Build_Chain
         (Scope      => P,
@@ -4423,9 +4984,9 @@ package body Sem_Ch10 is
    procedure Check_Body_Needed_For_SAL (Unit_Name : Entity_Id) is
 
       function Entity_Needs_Body (E : Entity_Id) return Boolean;
-      --  Determine whether use of entity E might require the presence
-      --  of its body. For a package this requires a recursive traversal
-      --  of all nested declarations.
+      --  Determine whether use of entity E might require the presence of its
+      --  body. For a package this requires a recursive traversal of all nested
+      --  declarations.
 
       ---------------------------
       -- Entity_Needed_For_SAL --
@@ -4458,7 +5019,6 @@ package body Sem_Ch10 is
            and then Present (Corresponding_Body (Unit_Declaration_Node (E)))
          then
             Ent := First_Entity (E);
-
             while Present (Ent) loop
                if Entity_Needs_Body (Ent) then
                   return True;
@@ -4569,8 +5129,8 @@ package body Sem_Ch10 is
       Item := First (Context_Items (N));
       while Present (Item) loop
 
-         --  We are interested only in with clauses which got installed
-         --  on entry, as indicated by their Context_Installed flag set
+         --  We are interested only in with clauses which got installed on
+         --  entry, as indicated by their Context_Installed flag set
 
          if Nkind (Item) = N_With_Clause
            and then Limited_Present (Item)
@@ -4592,9 +5152,6 @@ package body Sem_Ch10 is
 
          elsif Nkind (Item) = N_Use_Type_Clause then
             End_Use_Type (Item);
-
-         elsif Nkind (Item) = N_With_Type_Clause then
-            Remove_With_Type_Clause (Name (Item));
          end if;
 
          Next (Item);
@@ -4607,14 +5164,28 @@ package body Sem_Ch10 is
 
    procedure Remove_Limited_With_Clause (N : Node_Id) is
       P_Unit     : constant Entity_Id := Unit (Library_Unit (N));
-      P          : Entity_Id := Defining_Unit_Name (Specification (P_Unit));
+      E          : Entity_Id;
+      P          : Entity_Id;
+      Lim_Header : Entity_Id;
       Lim_Typ    : Entity_Id;
+      Prev       : Entity_Id;
 
    begin
-      if Nkind (P) = N_Defining_Program_Unit_Name then
+      pragma Assert (Limited_View_Installed (N));
+
+      --  In case of limited with_clause on subprograms, generics, instances,
+      --  or renamings, the corresponding error was previously posted and we
+      --  have nothing to do here.
+
+      if Nkind (P_Unit) /= N_Package_Declaration then
+         return;
+      end if;
+
+      P := Defining_Unit_Name (Specification (P_Unit));
 
-         --  Retrieve entity of Child package
+      --  Handle child packages
 
+      if Nkind (P) = N_Defining_Program_Unit_Name then
          P := Defining_Identifier (P);
       end if;
 
@@ -4625,66 +5196,107 @@ package body Sem_Ch10 is
          Write_Eol;
       end if;
 
-      --  Remove all shadow entities from visibility. The first element of the
-      --  limited view is a header (an E_Package entity) that is used to
-      --  reference the first shadow entity in the private part of the package
+      --  Prepare the removal of the shadow entities from visibility. The
+      --  first element of the limited view is a header (an E_Package
+      --  entity) that is used to reference the first shadow entity in the
+      --  private part of the package
 
-      Lim_Typ    := First_Entity (Limited_View (P));
-
-      while Present (Lim_Typ) loop
-         Unchain (Lim_Typ);
-         Next_Entity (Lim_Typ);
-      end loop;
-
-      --  Indicate that the limited view of the package is not installed
-
-      Set_From_With_Type (P, False);
-      Set_Limited_View_Installed (N, False);
+      Lim_Header := Limited_View (P);
+      Lim_Typ    := First_Entity (Lim_Header);
 
-      --  If the exporting package has previously been analyzed, it
-      --  has appeared in the closure already and should be left alone.
-      --  Otherwise, remove package itself from visibility.
+      --  Remove package and shadow entities from visibility if it has not
+      --  been analyzed
 
       if not Analyzed (P_Unit) then
          Unchain (P);
-         Set_First_Entity (P, Empty);
-         Set_Last_Entity (P, Empty);
-         Set_Ekind (P, E_Void);
-         Set_Scope (P, Empty);
          Set_Is_Immediately_Visible (P, False);
 
+         while Present (Lim_Typ) loop
+            Unchain (Lim_Typ);
+            Next_Entity (Lim_Typ);
+         end loop;
+
+      --  Otherwise this package has already appeared in the closure and its
+      --  shadow entities must be replaced by its real entities. This code
+      --  must be kept synchronized with the complementary code in Install
+      --  Limited_Withed_Unit.
+
       else
+         --  Real entities that are type or subtype declarations were hidden
+         --  from visibility at the point of installation of the limited-view.
+         --  Now we recover the previous value of the hidden attribute.
+
+         E := First_Entity (P);
+         while Present (E) and then E /= First_Private_Entity (P) loop
+            if Is_Type (E) then
+               Set_Is_Hidden (E, Was_Hidden (E));
+            end if;
 
-         --  Reinstall visible entities (entities removed from visibility in
-         --  Install_Limited_Withed to install the shadow entities).
+            Next_Entity (E);
+         end loop;
 
-         declare
-            Ent : Entity_Id;
+         while Present (Lim_Typ)
+           and then Lim_Typ /= First_Private_Entity (Lim_Header)
+         loop
+            --  Nested packages and child units were not unchained
 
-         begin
-            Ent := First_Entity (P);
-            while Present (Ent) and then Ent /= First_Private_Entity (P) loop
+            if Ekind (Lim_Typ) /= E_Package
+              and then not Is_Child_Unit (Non_Limited_View (Lim_Typ))
+            then
+               --  Handle incomplete types of the real view. For this purpose
+               --  we traverse the list of visible entities to look for an
+               --  incomplete type in the real-view associated with Lim_Typ.
+
+               E := First_Entity (P);
+               while Present (E) and then E /= First_Private_Entity (P) loop
+                  exit when Ekind (E) = E_Incomplete_Type
+                    and then Present (Full_View (E))
+                    and then Full_View (E) = Lim_Typ;
+
+                  Next_Entity (E);
+               end loop;
+
+               --  If the previous search was not sucessful then the entity
+               --  to be restored in the homonym list is the non-limited view
+
+               if E = First_Private_Entity (P) then
+                  E := Non_Limited_View (Lim_Typ);
+               end if;
+
+               pragma Assert (not In_Chain (E));
 
-               --  Shadow entities have not been added to the list of
-               --  entities associated to the package spec. Therefore we
-               --  just have to re-chain all its visible entities.
+               Prev := Current_Entity (Lim_Typ);
 
-               if not Is_Class_Wide_Type (Ent) then
+               if Prev = Lim_Typ then
+                  Set_Current_Entity (E);
 
-                  Set_Homonym (Ent, Current_Entity (Ent));
-                  Set_Current_Entity (Ent);
+               else
+                  while Present (Prev)
+                    and then Homonym (Prev) /= Lim_Typ
+                  loop
+                     Prev := Homonym (Prev);
+                  end loop;
 
-                  if Debug_Flag_I then
-                     Write_Str ("   (homonym) chain ");
-                     Write_Name (Chars (Ent));
-                     Write_Eol;
+                  if Present (Prev) then
+                     Set_Homonym (Prev, E);
                   end if;
                end if;
 
-               Next_Entity (Ent);
-            end loop;
-         end;
+               --  We must also set the next homonym entity of the real entity
+               --  to handle the case in which the next homonym was a shadow
+               --  entity.
+
+               Set_Homonym (E, Homonym (Lim_Typ));
+            end if;
+
+            Next_Entity (Lim_Typ);
+         end loop;
       end if;
+
+      --  Indicate that the limited view of the package is not installed
+
+      Set_From_With_Type         (P, False);
+      Set_Limited_View_Installed (N, False);
    end Remove_Limited_With_Clause;
 
    --------------------
@@ -4721,9 +5333,7 @@ package body Sem_Ch10 is
          --  visible while the parent is in scope.
 
          E := First_Entity (P_Name);
-
          while Present (E) loop
-
             if Is_Child_Unit (E) then
                Set_Is_Immediately_Visible (E, False);
             end if;
@@ -4741,105 +5351,81 @@ package body Sem_Ch10 is
       end if;
    end Remove_Parents;
 
-   -----------------------------
-   -- Remove_With_Type_Clause --
-   -----------------------------
+   ---------------------------------
+   -- Remove_Private_With_Clauses --
+   ---------------------------------
 
-   procedure Remove_With_Type_Clause (Name : Node_Id) is
-      Typ : Entity_Id;
-      P   : Entity_Id;
+   procedure Remove_Private_With_Clauses (Comp_Unit : Node_Id) is
+      Item : Node_Id;
 
-      procedure Unchain (E : Entity_Id);
-      --  Remove entity from visibility list
+      function In_Regular_With_Clause (E : Entity_Id) return Boolean;
+      --  Check whether a given unit appears in a regular with_clause.
+      --  Used to determine whether a private_with_clause, implicit or
+      --  explicit, should be ignored.
 
-      -------------
-      -- Unchain --
-      -------------
+      ----------------------------
+      -- In_Regular_With_Clause --
+      ----------------------------
 
-      procedure Unchain (E : Entity_Id) is
-         Prev : Entity_Id;
+      function In_Regular_With_Clause (E : Entity_Id) return Boolean
+      is
+         Item : Node_Id;
 
       begin
-         Prev := Current_Entity (E);
-
-         --  Package entity may appear is several with_type_clauses, and
-         --  may have been removed already.
-
-         if No (Prev) then
-            return;
-
-         elsif Prev = E then
-            Set_Name_Entity_Id (Chars (E), Homonym (E));
-
-         else
-            while Present (Prev)
-              and then Homonym (Prev) /= E
-            loop
-               Prev := Homonym (Prev);
-            end loop;
-
-            if Present (Prev) then
-               Set_Homonym (Prev, Homonym (E));
+         Item := First (Context_Items (Comp_Unit));
+         while Present (Item) loop
+            if Nkind (Item) = N_With_Clause
+              and then Entity (Name (Item)) = E
+              and then not Private_Present (Item)
+            then
+               return True;
             end if;
-         end if;
-      end Unchain;
-
-   --  Start of processing for Remove_With_Type_Clause
-
-   begin
-      if Nkind (Name) = N_Selected_Component then
-         Typ := Entity (Selector_Name (Name));
-
-         --  If no Typ, then error in declaration, ignore
+            Next (Item);
+         end loop;
 
-         if No (Typ) then
-            return;
-         end if;
-      else
-         return;
-      end if;
+         return False;
+      end In_Regular_With_Clause;
 
-      P := Scope (Typ);
+   --  Start of processing for Remove_Private_With_Clauses
 
-      --  If the exporting package has been analyzed, it has appeared in the
-      --  context already and should be left alone. Otherwise, remove from
-      --  visibility.
+   begin
+      Item := First (Context_Items (Comp_Unit));
+      while Present (Item) loop
+         if Nkind (Item) = N_With_Clause
+           and then Private_Present (Item)
+         then
 
-      if not Analyzed (Unit_Declaration_Node (P)) then
-         Unchain (P);
-         Unchain (Typ);
-         Set_Is_Frozen (Typ, False);
-      end if;
+            --  If private_with_clause is redundant, remove it from
+            --  context, as a small optimization to subsequent handling
+            --  of private_with clauses in other nested packages..
 
-      if Ekind (Typ) = E_Record_Type then
-         Set_From_With_Type (Class_Wide_Type (Typ), False);
-         Set_From_With_Type (Typ, False);
-      end if;
+            if In_Regular_With_Clause (Entity (Name (Item))) then
+               declare
+                  Nxt : constant Node_Id := Next (Item);
 
-      Set_From_With_Type (P, False);
+               begin
+                  Remove (Item);
+                  Item := Nxt;
+               end;
 
-      --  If P is a child unit, remove parents as well
+            elsif Limited_Present (Item) then
+               if not Limited_View_Installed (Item) then
+                  Remove_Limited_With_Clause (Item);
+               end if;
 
-      P := Scope (P);
+               Next (Item);
 
-      while Present (P)
-        and then P /= Standard_Standard
-      loop
-         Set_From_With_Type (P, False);
+            else
+               Remove_Unit_From_Visibility (Entity (Name (Item)));
+               Set_Context_Installed (Item, False);
+               Next (Item);
+            end if;
 
-         if not Analyzed (Unit_Declaration_Node (P)) then
-            Unchain (P);
+         else
+            Next (Item);
          end if;
-
-         P := Scope (P);
       end loop;
-
-      --  The back-end needs to know that an access type is imported, so it
-      --  does not need elaboration and can appear in a mutually recursive
-      --  record definition, so the imported flag on an access  type is
-      --  preserved.
-
-   end Remove_With_Type_Clause;
+   end Remove_Private_With_Clauses;
 
    ---------------------------------
    -- Remove_Unit_From_Visibility --
@@ -4863,9 +5449,17 @@ package body Sem_Ch10 is
 
       Set_Is_Potentially_Use_Visible (Unit_Name, False);
       Set_Is_Immediately_Visible     (Unit_Name, False);
-
    end Remove_Unit_From_Visibility;
 
+   --------
+   -- sm --
+   --------
+
+   procedure sm is
+   begin
+      null;
+   end sm;
+
    -------------
    -- Unchain --
    -------------
@@ -4899,6 +5493,6 @@ package body Sem_Ch10 is
          Write_Name (Chars (E));
          Write_Eol;
       end if;
-
    end Unchain;
+
 end Sem_Ch10;